express-http-context

repository·master·Indexed 43 days ago

https://github.com/skonves/express-http-context

A zero-dependency implementation of Node's AsyncLocalStorage for Express applications, providing a way to get and set request-scoped context anywhere in the application. Version 2.0.1.

Tokens
1.5K
Snippets
9
Records
9
Agent score
5%

What's inside express-http-context

  1. Install legacy versions for older Node.js runtimes

    master

    If you are running on an older version of Node.js, use the following installation commands:

    • For Node < 7: npm install --save express-http-context@0
    • For Node >= 8 and < 12: npm install --save express-http-context@1
    # For Node < 7
    npm install --save express-http-context@0
    
    # For Node >= 8 < 12
    npm install --save express-http-context@1
  2. Set up express-http-context middleware

    master

    To enable request-scoped context, you must use httpContext.middleware in your Express application. This middleware must be placed before any other middleware or route handlers that require access to the context.

    import express from 'express';
    import * as httpContext from 'express-http-context';
    
    const app = express();
    app.use(httpContext.middleware);
    // All code from here on has access to the same context for each request
  3. Get values from the request-scoped context

    master

    Use httpContext.get(key) to retrieve data stored in the context. This allows you to access request-specific information in parts of your application that do not have direct access to the Express req object, such as deep service layers or database utilities.

    import * as httpContext from 'express-http-context';
    
    // Somewhere deep in the Todo Service
    async function createTodoItem(title, content) {
    	// Get the user from the request-scoped context
    	const user = httpContext.get('user');
    
    	await db.insert({ title, content, userId: user.id });
    }
  4. Set values in the request-scoped context

    master

    Use httpContext.set(key, value) to store data (such as user objects, JWT claims, or correlation IDs) during the request lifecycle. This is typically done in an authentication or initialization middleware.

    // 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);
    	}
    });
  5. Install and use express-http-context middleware

    master

    To enable request-scoped context in an Express.js application, you must use the middleware function. This middleware initializes a new Map for each incoming request using AsyncLocalStorage, allowing you to store and retrieve data throughout the lifecycle of that specific request without passing objects through every function call.

    Note: The middleware must be registered early in your Express middleware stack to ensure the context is available for subsequent handlers.

    const express = require('express');
    const httpContext = require('express-http-context');
    
    const app = express();
    
    // Initialize the context middleware
    app.use(httpContext.middleware);
    
    app.get('/', (req, res) => {
      httpContext.set('requestId', '12345');
      res.send('Context initialized');
    });
  6. Get values from the HTTP context

    master

    Use get(key) to retrieve a value from the current request's context.

    • key: The string identifier used when the value was stored.

    Returns the stored value if found. Returns undefined if the key does not exist or if the context has not been initialized for the current request.

    const httpContext = require('express-http-context');
    
    // Retrieve a value stored earlier in the request lifecycle
    const user = httpContext.get('user');
    console.log(user?.name);
  7. Access the underlying AsyncLocalStorage instance

    master

    The asyncLocalStorage property exports the raw AsyncLocalStorage instance used by the library. This allows advanced users to interact directly with the storage mechanism if needed, though standard usage should rely on get and set.

    const httpContext = require('express-http-context');
    
    // Access the internal AsyncLocalStorage instance
    const storage = httpContext.asyncLocalStorage;
  8. Set values in the HTTP context

    master

    Use set(key, value) to add or update a value in the current request's context.

    • key: A string representing the identifier for the value.
    • value: Any JavaScript value.

    If the context has not been initialized (i.e., the middleware has not run for the current request), set will return undefined and no value will be persisted.

    const httpContext = require('express-http-context');
    
    // Inside a request handler or service
    httpContext.set('user', { id: 1, name: 'John Doe' });