What's the best way to pass values among middlewares in koa.js
Asked Answered
T

2

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?

Tyndall answered 16/6, 2014 at 3:14 Comment(0)
A
17

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

Aspirate answered 1/3, 2015 at 20:54 Comment(1)
Ex: ctx.state.thingToPassToOtherMiddlware = "Something" and in the other middlware var thingToPassToOtherMiddlware = ctx.state.thingToPassToOtherMiddlwareFairlie
M
0

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
}));
Methaemoglobin answered 16/6, 2014 at 19:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.