Middleware for injecting a request context on req.context. This makes it easy to define loggers, services, … that depend on information in the current request (request-id for logs, api token for services, …) to work optimally.

Options

The options object should be a dictionary of key-value pairs where:

  • key: is a string and the name of the property you wish to add to the context
  • value: is a getter function that gets passed the current context and should return the value for key. The current context will at least have “req” and “res” set on it, plus any other properties you define through options.

Caching and reloading

The getter functions passed when defining context keys are cached after the first time they are accessed. In case you need the context of one or more keys to be re-evaluated, you can call context.reload(key) (where key is optional) to reload one or all keys.

Cloning

The context can be cloned using context.clone(). Changes to a cloned context’s keys will not affect it’s source. A cloned context gets a fresh cache so every key will be re-evaluated when used.

Example

const app = require('express')();
const createContextMiddleware = require('@ambassify/expressify/middleware/context');
const services = require('./services');

app.use(createContextMiddleware({
    // req and res are available
    token: context => context.res.locals.auth,
    services: context => services.extend({
        // you can use properties you defined yourself as well
        Message: { token: context.token }
    })
}));

app.get('/test', (req, res) => {
    const { services } = req.context;

    res.locals.auth = 'swapped token';
    req.context.reload();
    // context.token and context.services now use the new token

    return services.Message.get('foo')
        .then(result => res.send(result));
});