Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 31 additions & 42 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,81 +2,70 @@
[![coveralls](https://img.shields.io/coveralls/skonves/express-http-context.svg)](https://coveralls.io/github/skonves/express-http-context)
[![npm](https://img.shields.io/npm/v/express-http-context.svg)](https://www.npmjs.com/package/express-http-context)
[![npm](https://img.shields.io/npm/dm/express-http-context.svg)](https://www.npmjs.com/package/express-http-context)
[![david](https://img.shields.io/david/skonves/express-http-context.svg)](https://david-dm.org/skonves/express-http-context)

# Express HTTP Context
Get and set request-scoped context anywhere. This is just an unopinionated, idiomatic ExpressJS implementation of [cls-hooked](https://github.com/Jeff-Lewis/cls-hooked) (forked from [continuation-local-storage](https://www.npmjs.com/package/continuation-local-storage)). It's a great place to store user state, claims from a JWT, request/correlation IDs, and any other request-scoped data. Context is preserved even over async/await (in node 8+).
Get and set request-scoped context anywhere. This package is an unopinionated, zero-dependency, Express-idiomatic implementation of [Node AsyncLocalStorage](https://nodejs.org/api/async_context.html#class-asynclocalstorage). It's a great place to store user state, claims from a JWT, request/correlation IDs, and any other request-scoped data.

## How to use it

Install: `npm install --save express-http-context`
(Note: For node v4-7, use the legacy version: `npm install --save express-http-context@<1.0.0`)
Install: `npm i express-http-context`

Use the middleware immediately before the first middleware that needs to have access to the context.
You won't have access to the context in any middleware "used" before this one.

Note that some popular middlewares (such as body-parser, express-jwt) may cause context to get lost.
To workaround such issues, you are advised to use any third party middleware that does NOT need the context
BEFORE you use this middleware.
Use the context middleware before the first middleware or handler that needs to have access to the context.

``` js
var express = require('express');
var httpContext = require('express-http-context');
import express from 'express';
import * as httpContext from 'express-http-context';

var app = express();
// Use any third party middleware that does not need access to the context here, e.g.
// app.use(some3rdParty.middleware);
const app = express();
app.use(httpContext.middleware);
// all code from here on has access to the same context for each request
// All code from here on has access to the same context for each request
```

Set values based on the incoming request:

``` js
// Example authorization middleware
app.use((req, res, next) => {
userService.getUser(req.get('Authorization'), (err, result) => {
if (err) {
next(err);
} else {
httpContext.set('user', result.user)
next();
}
});
// Example authentication middleware
app.use(async (req, res, next) => {
try {
// Get user from data on request
const bearer = req.get('Authorization');
const user = await userService.getUser(bearer);

// Add user to the request-scoped context
httpContext.set('user', user);

return next();
} catch (err) {
return next(err);
}
});
```

Get them from code that doesn't have access to the express `req` object:

``` js
var httpContext = require('express-http-context');
import * as httpContext from 'express-http-context';

// Somewhere deep in the Todo Service
function createTodoItem(title, content, callback) {
var user = httpContext.get('user');
db.insert({ title, content, userId: user.id }, callback);
}
```
async function createTodoItem(title, content) {
// Get the user from the request-scoped context
const user = httpContext.get('user');

You can access cls namespace directly as (it may be useful if you want to apply some patch to it, for example https://github.com/TimBeyer/cls-bluebird):
``` js
var ns = require('express-http-context').ns;
await db.insert({ title, content, userId: user.id });
}
```

## Troubleshooting
To avoid weird behavior with express:
1. Make sure you require `express-http-context` in the first row of your app. Some popular packages use async which breaks CLS.

For users of Node 10
1. Node 10.0.x - 10.3.x are not supported. V8 version 6.6 introduced a bug that breaks async_hooks during async/await. Node 10.4.x uses V8 v6.7 in which the bug is fixed. See: https://github.com/nodejs/node/issues/20274.
## Legacy versions

See [Issue #4](https://github.com/skonves/express-http-context/issues/4) for more context. If you find any other weird behaviors, please feel free to open an issue.
* For Node <7: `npm install --save express-http-context@0`
* For Node >=8 <12: `npm install --save express-http-context@1`

## Contributors
* Steve Konves (@skonves)
* Amiram Korach (@amiram)
* Yoni Rabinovitch (@yonirab)
* DontRelaX (@dontrelax)
* William Durand (@willdurand)
* Kristopher Morris (@beeduck)

Interesting in contributing? Take a look at the [Contributing Guidlines](/CONTRIBUTING.md)
1 change: 0 additions & 1 deletion browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@ module.exports = {
set: function (key, value) {
// noop
},
ns: null,
};
13 changes: 6 additions & 7 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { Request, Response, NextFunction } from "express";
import { Namespace } from 'cls-hooked';
import { AsyncLocalStorage } from 'async_hooks';

/** Express.js middleware that is responsible for initializing the context for each request. */
export declare function middleware(
req: Request,
res: Response,
next: NextFunction
req: any,
res: any,
next: (err?: any) => void
): void;

/**
Expand All @@ -19,6 +18,6 @@ export declare function get(key: string): any;
export declare function set(key: string, value: any): void;

/**
* Gets the underlying continuation namespace.
* Gets the instance of AsyncLocalStorage that is used to store the context for each request.
*/
export declare const ns: Namespace;
export declare const asyncLocalStorage: AsyncLocalStorage<Map<string, unknown>>;
28 changes: 15 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,41 @@
'use strict';

const cls = require('cls-hooked');

const nsid = 'a6a29a6f-6747-4b5f-b99f-07ee96e32f88';
const ns = cls.createNamespace(nsid);
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();

/** Express.js middleware that is responsible for initializing the context for each request. */
function middleware(req, res, next) {
ns.run(() => next());
if (!asyncLocalStorage.getStore()) {
asyncLocalStorage.run(new Map(), () => next());
} else {
next();
}
}

/**
* Gets a value from the context by key. Will return undefined if the context has not yet been initialized for this request or if a value is not found for the specified key.
* @param {string} key
*/
function get(key) {
if (ns && ns.active) {
return ns.get(key);
}
return asyncLocalStorage.getStore()?.get(key);
}

/**
* Adds a value to the context by key. If the key already exists, its value will be overwritten. No value will persist if the context has not yet been initialized.
* @param {string} key
* @param {*} value
* @param {string} key
* @param {*} value
*/
function set(key, value) {
if (ns && ns.active) {
return ns.set(key, value);
if (asyncLocalStorage.getStore()) {
asyncLocalStorage.getStore()?.set(key, value);
return value;
}
return undefined;
}

module.exports = {
middleware,
get: get,
set: set,
ns: ns
asyncLocalStorage
};
Loading
Loading