0
0
Expressframework~5 mins

Request context middleware in Express

Choose your learning style9 modes available
Introduction

Request context middleware helps keep data related to a single request in one place. It makes sharing information between parts of your app easier without passing many variables around.

You want to store user info after login and access it in different routes.
You need to track request-specific data like request ID for logging.
You want to share database connections or settings during a request.
You want to avoid passing many parameters through multiple functions.
You want to add timing or performance info for each request.
Syntax
Express
function requestContextMiddleware(req, res, next) {
  req.context = { /* your data here */ };
  next();
}
Middleware is a function that runs during the request before your route handlers.
You add a new property (like req.context) to store data for that request.
Examples
This example adds a unique requestId to each request using the current time.
Express
function requestContextMiddleware(req, res, next) {
  req.context = { requestId: Date.now() };
  next();
}
This example prepares a user property to store logged-in user info later.
Express
function requestContextMiddleware(req, res, next) {
  req.context = { user: null };
  next();
}
Sample Program

This Express app uses request context middleware to add a unique requestId to each request. The route then sends this ID back in the response.

Express
import express from 'express';

const app = express();

// Request context middleware
function requestContextMiddleware(req, res, next) {
  req.context = { requestId: Date.now() };
  next();
}

app.use(requestContextMiddleware);

app.get('/', (req, res) => {
  res.send(`Hello! Your request ID is ${req.context.requestId}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Each request gets its own context object, so data does not mix between users.

Always call next() to continue to the next middleware or route.

Use context to keep your code clean and avoid global variables.

Summary

Request context middleware stores data for each request in one place.

It helps share info between middleware and routes easily.

Use it to keep your app organized and avoid passing many parameters.