4

Is there any reason why Koa is being executed twice per request?

const Koa = require('koa')
const app = new Koa()

const index = async(ctx, next) => {
  console.log('Hello world!')
  await next()
  ctx.body = 'Hello world!'
}

app.use(index);

app.listen(3000)

On my terminal, I get:

Hello world!
Hello world!

Any ideas?

Run
  • 54,938
  • 169
  • 450
  • 748

1 Answers1

7

There are two reasons why this could happen:

First is - as already mentioned in the comments that browsers also fire a request for favicon.ico Second: some browsers do a prefentching, so before you even hit the return key, they prefetch the url when entering.

const Koa = require('koa')
const app = new Koa()

const index = async(ctx, next) => {
  console.log('URL --> ' + ctx.request.url); // This logs out the requested route
  console.log('Hello world!')
  await next()
  ctx.body = 'Hello world!'
}

app.use(index);

app.listen(3000)

I added one line to your code so that you can see which routes your browser asks for. This might help identify the reason for your problem.

Sebastian Hildebrandt
  • 2,661
  • 1
  • 14
  • 20
  • Correct: most of the time it's just the browser asking for `/favicon.ico` as @robertklep has pointed out. even when specifying the type to be `application/json` the browser still does that. – jadinerky Jun 22 '23 at 13:16