javascriptnode.jskoa2

How to create Koa2 middleware which will modify response body and run last in a chain?


I have a Koa2 application, which renders templates on different routes. I'd like to introduce a middleware which will modify rendered templates in some way and I need it to be the last in a chain of other middlewares. Are there any way to enforce some middleware to be applied last before firing response using Koa2 and without modification of the already defined routes?

I have tried the code below:

// modification middleware
app.use(async function (ctx, next) {
  await next();
  ctx.body = ctx.body.toUpperCase();
})

// template rendering
app.use(async function (ctx, next) {
  const users = [{ }, { name: 'Sue' }, { name: 'Tom' }];
  await ctx.render('content', {
    users
  });
});

app.listen(7001);

It works as expected, but if any other middleware will be introduced before the modification one, it will be not the last in the chain.

Is it possible to achieve described behavior?


Solution

  • Figured out solution to this question sometime ago. In case someone else will need to do something like in the question, here's the code:

    // modification middleware
    const mw = async function(ctx, next) {
      await next();
      ctx.body = ctx.body.toUpperCase();
    }
    
    app.middleware.unshift(mw);
    

    Basically middleware member of the application object can be accessed externally. Using standard array method unshift, it can be enforced to add needed middle-ware first in middlewares array, which will be treated by Koa as the last one in chain.