Consider this middleware function in Express:
function addRequestId(req, res, next) {
req.requestId = Date.now().toString();
next();
}What will req.requestId contain when accessed in a later route handler?
function addRequestId(req, res, next) {
req.requestId = Date.now().toString();
next();
}Think about what Date.now() returns and how it is converted.
The middleware sets req.requestId to a string of the current timestamp, which is unique for each request.
Given these two middlewares and a route handler:
app.use((req, res, next) => {
req.user = { name: 'Alice' };
next();
});
app.use((req, res, next) => {
req.user.role = 'admin';
next();
});
app.get('/', (req, res) => {
res.send(req.user.role);
});What will the client receive when requesting /?
app.use((req, res, next) => {
req.user = { name: 'Alice' };
next();
});
app.use((req, res, next) => {
req.user.role = 'admin';
next();
});
app.get('/', (req, res) => {
res.send(req.user.role);
});Consider how the middlewares modify req.user before the route handler runs.
The first middleware sets req.user to an object with name. The second adds role. The route sends req.user.role, which is 'admin'.
Choose the correct Express middleware snippet that uses async_hooks to store a unique request ID accessible in async callbacks.
Remember that enterWith sets the store for the current async context.
Option C correctly uses asyncLocalStorage.enterWith() to set the store with the request ID before calling next(). Option C calls next() inside run() callback which is valid but less common. Option C uses a Map but does not bind context properly. Option C calls getStore() before any store is set, causing an error.
Examine this middleware:
const asyncLocalStorage = new AsyncLocalStorage();
app.use((req, res, next) => {
asyncLocalStorage.run(new Map(), () => {
asyncLocalStorage.getStore().set('user', req.user);
setTimeout(() => {
console.log(asyncLocalStorage.getStore().get('user'));
}, 100);
next();
});
});Why might console.log print undefined?
const asyncLocalStorage = new AsyncLocalStorage();
app.use((req, res, next) => {
asyncLocalStorage.run(new Map(), () => {
asyncLocalStorage.getStore().set('user', req.user);
setTimeout(() => {
console.log(asyncLocalStorage.getStore().get('user'));
}, 100);
next();
});
});Think about how async context is preserved across timers.
AsyncLocalStorage does not automatically preserve context across native timers like setTimeout. The context is lost unless wrapped or patched. So inside setTimeout, getStore() returns undefined.
Why would a developer use request context middleware based on AsyncLocalStorage in an Express app?
Think about how data can be shared in async callbacks without changing function signatures.
AsyncLocalStorage allows storing data tied to a request context that is accessible in all async callbacks related to that request, avoiding manual passing of data through parameters.