Koa middleware misbehave when next() thenable is not returned

Koajs is nicer in many aspects than its predecessor express.  Probably it’s still in early stage, there are rough edges and some answers are hard to be found.

Consider this code below:

[code] app.use((ctx, next) => { ctx.response.type = ‘json’; next(); }); router.get(‘/’, async (ctx, next) => { if (req.query.someData) // do async stuff else // directly write ctx.response.body }); app.use(router.routes()); [/code]

This above, will give correct result when someData query param is not present. But it will give 404 when someData is there! Why?

You need to return next(), on top of invoking next() in your middlewares. This ensures a thenable to chain, and then async operations will be respected. Otherwise only synchronous ops will work - and it does work.

The last piece is that Koa is being smart and give 404 when response.body is empty and never written.

Written on September 23, 2017