11

I have a simple setup for koa.js with koa-route and koa-ejs.

var koa     = require('koa');
var route   = require('koa-route');
var add_ejs = require('koa-ejs');
var app     = koa();

add_ejs(app, {…});

app.use(function *(next){
    console.log( 'to do layout tweak for all requests' );
    yield next;
});

app.use(route.get('/', function *(name) {
  console.log( 'root action' );
  yield this.render('index', {name: 'Hello' });
}));

What's the best way to pass values between those two methods?

beatak
  • 9,185
  • 10
  • 33
  • 42

2 Answers2

16

context.state is the low-level way of sharing data between middleware. It's an object mounted on context that's available in all middleware.

You can use it like so:

let counter = 0;

app.use((ctx, next) => {
  ctx.state.requestId = counter++;
  return next();
});

app.use((ctx, next) => {
  console.log(ctx.state.requestId);
  // => 1, 2, 3, etc
  return next();
});

source

koajs readme

jbielick
  • 2,800
  • 17
  • 28
  • Ex: `ctx.state.thingToPassToOtherMiddlware = "Something"` and in the other middlware `var thingToPassToOtherMiddlware = ctx.state.thingToPassToOtherMiddlware` – Chris Magnuson Sep 06 '19 at 14:51
1

You can use Koa Context:

app.use(function *(next) {
  this.foo = 'Foo';
  yield next;
});

app.use(route.get('/', function *(next) { // 'next' is probably what you want, not 'name'
  yield this.render('index', { name: this.foo });
  yield next; // pass to the next middleware
}));
realguess
  • 1,133
  • 2
  • 10
  • 10