Socket
Socket
Sign inDemoInstall

express-als-context

Package Overview
Dependencies
12
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    express-als-context

Get and set request-scoped context anywhere


Version published
Weekly downloads
151
decreased by-71.18%
Maintainers
1
Install size
2.12 MB
Created
Weekly downloads
 

Readme

Source

Express AsyncLocalStorage Context

Get and set request-scoped context anywhere. It's using a now-stable AsyncLocalStorage. It's heavily inspired by express-http-context, but doesn't suffer from the same memory leak issue that it brought (which was due to cls-hooked issue)

Support

AsyncLocalStorage supports Node.js from 12.17.0 up.

How to use it

Install: npm install --save express-als-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.

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

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

Set values based on the incoming request:

// 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();
    }
  });
});

You can read the values in the code that doesn't have access to the express's req object:

var httpContext = require('express-als-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);
}

Keywords

FAQs

Last updated on 26 May 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc