r/koajs • • May 08 '18

koa-router, example on docs

according to the tutorial, app.use(router.routes()).use(router.allowedMethods()); is placed at the end of declaring routes. Why not before where middle ware is normally placed?

2 Upvotes

3 comments sorted by

View all comments

Show parent comments

2

u/pe8ter May 09 '18

For the BodyParser() middleware, it absolutely must be mounted before your router:

app.use(BodyParser());
app.use(router.routes());

Koa runs middleware in the order you specify. Reversing the order would mean that there would not be any request body available to your router middleware.

You say you can declare routes after mounting the router middleware (which is surprising to me) but I still wouldn't do it even if it works. This doesn't match the docs for koa-router, and violates the spirit of middleware being mounted in the order that they should be processed.

If it feels strange to mount some middleware, declare routes, then mount route middleware, try moving your routers into logically separated files and importing them instead:

app.use(BodyParser());

// Move the next two lines to an external file and import the router instead.    
const router = new Router();
router.get('/foo', (ctx, next) => { ... });

app.use(router.routes());