0
0
Expressframework~10 mins

Request context middleware in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a middleware function that adds a context object to the request.

Express
function contextMiddleware(req, res, next) {
  req.[1] = {};
  next();
}
Drag options to blanks, or click blank then click option'
Acontext
Bdata
Cinfo
Dstate
Attempts:
3 left
💡 Hint
Common Mistakes
Using a property name that conflicts with existing Express properties.
Forgetting to call next() to continue the middleware chain.
2fill in blank
medium

Complete the code to attach a user ID to the request context inside the middleware.

Express
function contextMiddleware(req, res, next) {
  req.context = {};
  req.context.[1] = req.headers['x-user-id'];
  next();
}
Drag options to blanks, or click blank then click option'
Auid
Buser
Cid
DuserId
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic name like id which may be ambiguous.
Not reading the user ID from the correct header.
3fill in blank
hard

Fix the error in the middleware to ensure the context is initialized only once per request.

Express
function contextMiddleware(req, res, next) {
  if (!req.[1]) {
    req.context = {};
  }
  next();
}
Drag options to blanks, or click blank then click option'
Acontext
Bctx
Cstate
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Checking a different property name than the one used to store context.
Not guarding initialization causing data loss.
4fill in blank
hard

Fill both blanks to create a middleware that adds a timestamp and a request ID to the context.

Express
function contextMiddleware(req, res, next) {
  req.context = {
    [1]: Date.now(),
    [2]: req.headers['x-request-id']
  };
  next();
}
Drag options to blanks, or click blank then click option'
Atimestamp
BrequestId
CreqId
Dtime
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent or unclear property names.
Not reading the request ID from the correct header.
5fill in blank
hard

Fill all three blanks to create a middleware that initializes context, sets a user role, and logs the context.

Express
function contextMiddleware(req, res, next) {
  req.[1] = {};
  req.context.[2] = req.headers['x-user-role'] || 'guest';
  console.log('Context:', req.[3]);
  next();
}
Drag options to blanks, or click blank then click option'
Acontext
Brole
Dstate
Attempts:
3 left
💡 Hint
Common Mistakes
Using different property names for context initialization and logging.
Forgetting to provide a default user role.