Koa: Cutting short Koa's middleware cascade

Created on 15 Jun 2017  Â·  2Comments  Â·  Source: koajs/koa

Sorry, I seem to have got my wires crossed… How would I go about cancelling or cutting short Koa's middleware cascade for instance in case of a redirect? I currently store a flag in ctx.state and check it in each middleware but this seems like a waste of cpu time. There's got to be a intended, more elegant solution. Should I just return;?

app.use(async (ctx, next) => {
   if (redirect) {
      ctx.redirect(url, 303);
     // Stop the entire process here.
   }

   // only handle if there's no redirect.
   await next();
});

app.use(async (ctx, next) => {
   // only handle if there's no redirect.
   await next();
});

app.use(async (ctx, next) => {
   // only handle if there's no redirect.
   await next();
});

Most helpful comment

Yes. Have you tried it?

'use strict'
// node 7.6+

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

app.use(async ({ body }, next) => {
  console.log('1')
  body = 1
  return
  await next()
})

app.use(async ({ body }, next) => {
  console.log('2')
  body = 2
  await next()
})

app.use(async ({ body }) => {
  console.log('3')
  body = 3
})

app.listen(1337)

$ curl localhost:1337 responds with 1 (and console.log:s the same)

All 2 comments

Yes. Have you tried it?

'use strict'
// node 7.6+

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

app.use(async ({ body }, next) => {
  console.log('1')
  body = 1
  return
  await next()
})

app.use(async ({ body }, next) => {
  console.log('2')
  body = 2
  await next()
})

app.use(async ({ body }) => {
  console.log('3')
  body = 3
})

app.listen(1337)

$ curl localhost:1337 responds with 1 (and console.log:s the same)

Thanks! Felt like a hack but it works.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tracker1 picture tracker1  Â·  3Comments

ilkkao picture ilkkao  Â·  4Comments

felixfbecker picture felixfbecker  Â·  5Comments

dounine picture dounine  Â·  4Comments

SteveCruise picture SteveCruise  Â·  3Comments