Complete the code to create a middleware function that adds a context object to the request.
function contextMiddleware(req, res, next) {
req.[1] = {};
next();
}The middleware adds a context object to the req so other handlers can store data there.
Complete the code to attach a user ID to the request context inside the middleware.
function contextMiddleware(req, res, next) {
req.context = {};
req.context.[1] = req.headers['x-user-id'];
next();
}id which may be ambiguous.We store the user ID under userId in the context for clarity.
Fix the error in the middleware to ensure the context is initialized only once per request.
function contextMiddleware(req, res, next) {
if (!req.[1]) {
req.context = {};
}
next();
}We check if req.context exists before initializing to avoid overwriting.
Fill both blanks to create a middleware that adds a timestamp and a request ID to the context.
function contextMiddleware(req, res, next) {
req.context = {
[1]: Date.now(),
[2]: req.headers['x-request-id']
};
next();
}We use timestamp for the current time and requestId for the unique request identifier.
Fill all three blanks to create a middleware that initializes context, sets a user role, and logs the context.
function contextMiddleware(req, res, next) {
req.[1] = {};
req.context.[2] = req.headers['x-user-role'] || 'guest';
console.log('Context:', req.[3]);
next();
}The context is initialized on req.context. The user role is stored as role. The console logs the context property.