What if you could share data across your app during a request without messy manual passing?
Why Request context middleware in Express? - Purpose & Use Cases
Imagine building a web app where you need to share user info, request IDs, or settings across many parts of your code during a single request.
You try passing this data manually through every function call.
Manually passing data everywhere is tiring and error-prone.
You might forget to pass it, or pass wrong data, causing bugs that are hard to find.
It also clutters your code with extra parameters, making it messy and hard to read.
Request context middleware automatically attaches data to each request and makes it accessible anywhere during that request's life.
This keeps your code clean and reliable without passing data manually.
function handle(req, res, user) { logUser(user); process(user); }app.use(requestContextMiddleware);
function handle(req, res) { const user = req.context.user; logUser(user); process(user); }It enables sharing data easily and safely across all parts of your app during a request, improving code clarity and reliability.
In an online store, you can track a unique request ID and user info throughout logging, error handling, and database calls without passing them manually everywhere.
Manual data passing is messy and error-prone.
Request context middleware attaches data to each request automatically.
This makes your code cleaner and easier to maintain.
Practice
Solution
Step 1: Understand request context middleware role
Request context middleware stores data that belongs to a single request, making it accessible throughout that request's lifecycle.Step 2: Compare with other options
The other options describe different middleware roles but not the core purpose of request context middleware.Final Answer:
To store and share data specific to each request across middleware and routes -> Option CQuick Check:
Request context middleware = store per-request data [OK]
- Confusing request context with global app state
- Thinking it manages static files
- Assuming it only handles authentication
Solution
Step 1: Identify where to store request-specific data
In Express, the request object (req) is unique per request, so adding a property to req is correct.Step 2: Check other options for correctness
res is for response, app is global, and context alone is undefined, so only req.context works properly.Final Answer:
req.context = { userId: 123 }; next(); -> Option AQuick Check:
Store data on req object for request context [OK]
- Using res or app instead of req for context
- Forgetting to call next() after middleware
- Assigning context to undefined variable
/user?
app.use((req, res, next) => {
req.context = { user: 'Alice' };
next();
});
app.get('/user', (req, res) => {
res.send(`User: ${req.context.user}`);
});Solution
Step 1: Analyze middleware setting req.context
The middleware sets req.context to an object with user property 'Alice' before passing control.Step 2: Check route handler usage
The route reads req.context.user and sends it in the response, so it will output 'User: Alice'.Final Answer:
User: Alice -> Option AQuick Check:
Middleware sets req.context.user = 'Alice' [OK]
- Assuming req.context is undefined in route
- Forgetting middleware runs before route
- Confusing res.context with req.context
app.use((req, res, next) => {
req.context.user = 'Bob';
next();
});Solution
Step 1: Check initialization of req.context
The code tries to assign user to req.context.user, but req.context was never created, so it's undefined.Step 2: Understand the error cause
Accessing a property on undefined causes a runtime error. next() is called, so no hanging issue.Final Answer:
req.context is undefined, so assigning user property causes an error -> Option BQuick Check:
Initialize req.context before adding properties [OK]
- Not initializing req.context as an object
- Forgetting to call next()
- Misusing res instead of req
Solution
Step 1: Understand request-specific data storage
Request ID is unique per request, so it must be stored in a per-request object like req.context.Step 2: Evaluate options for sharing data
Global variables cause conflicts between concurrent requests, query parameters are not suitable for internal data sharing, and res.locals is primarily for template data rather than request processing.Final Answer:
Create middleware that sets req.context = { requestId: uniqueId } and call next(), then read req.context.requestId in routes -> Option DQuick Check:
Use req.context for per-request data sharing [OK]
- Using global variables for request data
- Relying on query parameters for context
- Confusing res.locals with request context
Ready to prove it?
Pass the test and this pattern moves unknown
