Data encapsulation for express.

Usage no npm install needed!

<script type="module">
  import expressContext from '';



Middleware for express to seamlessly contextualize specific properties.

build status coverage license version downloads

It allows for other middleware to be oblivious that properties they are manipulating are encapsulated within a specific context. For example, a property "foo" contextualized on a per-middleware basis means that every time middleware tries to access it manipulates a variable specific to that piece of middleware. You may then later recover all the different versions of foo, each specific to one particular middleware.

var express = require('express'),
    contextualize = require('express-context'),
    app = express();

function mw1(req, res, next) { = 5; = 10;

function mw2(req, res, next) { = 7; = 1;

var context = contextualize(['foo', 'bar']);

var cmw1 = context.for('a').use(mw1),
    cmw2 = context.for('b').use(mw2);

app.get('/', cmw1, cmw2, function (req, res, next) {

    // { foo: 5, bar: 10 }

    // { foo: 7, bar: 1 }


Building Fluent APIs

Create your API by creating a new context with an ID that's unique to your module, declaring all the properties that your API is concerned with, and then adding in all the mixins your module provides:

var context = require('express-context');

var mixins = {
    ok: function() {
        return this.use(function(req, res, next) {

function api() {
    return context({
        context: '__my_api',
        properties: [ 'data' ]

module.exports = api;

Then make use of your API:

var api = require('api')(),
    app = require('express')();

app.get('/all', api.ok());
app.get('/bob', api.for('my-consumer').use(function(req, res, next) { = 'bob';


use(method1, method2, ...)

Continue the chain with a new method. This works just like how it does in express.

// res is now middleware that invokes context AND the new given function
var res = context.use(function(req, res, next) {


Add new properties to the chain. This does not mutate the chain on which it was called.

// res now has everything in context plus foo = 5
var res = context.mixin({ foo: 5 });


Get chained middleware representing the contextualized version of the arguments. This does not do anything but set the current context.

// res is a chain whose context is 'abc'
var res = context.for('abc');
// res is a function for the parallel execution of contextualized versions of
// anything used after it in the chain.
var res = context.for(['abc', 'def']);


Get the value of the chain's context for a specific request

// res is an object whose keys correspond to all the contexts that were set
// during the processing of req.
var res = context.of(req);
// res is the result of the single context for mw1 that was set during the
// processing of req.
var res = context.for('abc').of(req);