0
0
Expressframework~20 mins

Request context middleware in Express - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Request Context Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
1:30remaining
What does this Express middleware add to the request object?

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?

Express
function addRequestId(req, res, next) {
  req.requestId = Date.now().toString();
  next();
}
AA unique string representing the current timestamp when the request was received
BThe IP address of the client making the request
CThe HTTP method of the request (e.g., GET, POST)
DThe URL path of the request
Attempts:
2 left
💡 Hint

Think about what Date.now() returns and how it is converted.

state_output
intermediate
1:30remaining
What is the output of this middleware chain?

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 /?

Express
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);
});
A'Alice'
B'admin'
Cundefined
DAn error is thrown because req.user is undefined
Attempts:
2 left
💡 Hint

Consider how the middlewares modify req.user before the route handler runs.

📝 Syntax
advanced
2:00remaining
Which middleware code correctly attaches a unique request ID using async hooks?

Choose the correct Express middleware snippet that uses async_hooks to store a unique request ID accessible in async callbacks.

A
const asyncHooks = require('async_hooks');
const store = new Map();

function requestContext(req, res, next) {
  const id = Date.now().toString();
  store.set(asyncHooks.executionAsyncId(), id);
  next();
}
B
const asyncHooks = require('async_hooks');
const asyncLocalStorage = new asyncHooks.AsyncLocalStorage();

function requestContext(req, res, next) {
  const id = Date.now().toString();
  asyncLocalStorage.getStore().set('requestId', id);
  next();
}
C
const asyncHooks = require('async_hooks');
const asyncLocalStorage = new asyncHooks.AsyncLocalStorage();

function requestContext(req, res, next) {
  const id = Date.now().toString();
  asyncLocalStorage.enterWith(new Map([['requestId', id]]));
  next();
}
D
const asyncHooks = require('async_hooks');
const asyncLocalStorage = new asyncHooks.AsyncLocalStorage();

function requestContext(req, res, next) {
  const id = Date.now().toString();
  asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set('requestId', id);
    next();
  });
}
Attempts:
2 left
💡 Hint

Remember that enterWith sets the store for the current async context.

🔧 Debug
advanced
2:00remaining
Why does this middleware fail to preserve request context in async callbacks?

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?

Express
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();
  });
});
ABecause <code>setTimeout</code> does not preserve the async context by default
BBecause <code>next()</code> is called inside <code>run()</code>, the async context ends before <code>setTimeout</code> runs
CBecause <code>asyncLocalStorage.getStore()</code> returns undefined inside <code>setTimeout</code> callback
DBecause <code>req.user</code> is undefined when setting the store
Attempts:
2 left
💡 Hint

Think about how async context is preserved across timers.

🧠 Conceptual
expert
1:30remaining
What is the main benefit of using request context middleware with AsyncLocalStorage in Express?

Why would a developer use request context middleware based on AsyncLocalStorage in an Express app?

ATo replace the need for session cookies and authentication
BTo improve the performance of Express by caching request data globally
CTo automatically retry failed requests without additional code
DTo store and access data specific to each request across asynchronous operations without passing it manually
Attempts:
2 left
💡 Hint

Think about how data can be shared in async callbacks without changing function signatures.