Bird
Raised Fist0
Expressframework~20 mins

Request context middleware in Express - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of request context middleware in Express?
easy
A. To serve static files like images and CSS
B. To handle database connections globally for all requests
C. To store and share data specific to each request across middleware and routes
D. To manage user authentication tokens only

Solution

  1. 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.
  2. Step 2: Compare with other options

    The other options describe different middleware roles but not the core purpose of request context middleware.
  3. Final Answer:

    To store and share data specific to each request across middleware and routes -> Option C
  4. Quick Check:

    Request context middleware = store per-request data [OK]
Hint: Remember: context middleware holds data per request only [OK]
Common Mistakes:
  • Confusing request context with global app state
  • Thinking it manages static files
  • Assuming it only handles authentication
2. Which of the following is the correct way to add a property to the request context in Express middleware?
easy
A. req.context = { userId: 123 }; next();
B. res.context.userId = 123; next();
C. app.context.userId = 123; next();
D. context.userId = 123; next();

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    req.context = { userId: 123 }; next(); -> Option A
  4. Quick Check:

    Store data on req object for request context [OK]
Hint: Attach context data to req, not res or app [OK]
Common Mistakes:
  • Using res or app instead of req for context
  • Forgetting to call next() after middleware
  • Assigning context to undefined variable
3. Given this middleware and route, what will be the output when a GET request is made to /user?
app.use((req, res, next) => {
  req.context = { user: 'Alice' };
  next();
});

app.get('/user', (req, res) => {
  res.send(`User: ${req.context.user}`);
});
medium
A. User: Alice
B. User: undefined
C. Error: Cannot read property 'user' of undefined
D. User:

Solution

  1. Step 1: Analyze middleware setting req.context

    The middleware sets req.context to an object with user property 'Alice' before passing control.
  2. Step 2: Check route handler usage

    The route reads req.context.user and sends it in the response, so it will output 'User: Alice'.
  3. Final Answer:

    User: Alice -> Option A
  4. Quick Check:

    Middleware sets req.context.user = 'Alice' [OK]
Hint: Middleware runs before route, so context is set [OK]
Common Mistakes:
  • Assuming req.context is undefined in route
  • Forgetting middleware runs before route
  • Confusing res.context with req.context
4. Identify the error in this request context middleware code:
app.use((req, res, next) => {
  req.context.user = 'Bob';
  next();
});
medium
A. Middleware should not modify req object
B. req.context is undefined, so assigning user property causes an error
C. res object is used incorrectly
D. next() is missing, so request hangs

Solution

  1. 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.
  2. Step 2: Understand the error cause

    Accessing a property on undefined causes a runtime error. next() is called, so no hanging issue.
  3. Final Answer:

    req.context is undefined, so assigning user property causes an error -> Option B
  4. Quick Check:

    Initialize req.context before adding properties [OK]
Hint: Always initialize req.context before use [OK]
Common Mistakes:
  • Not initializing req.context as an object
  • Forgetting to call next()
  • Misusing res instead of req
5. You want to store a request ID in the context for every request and access it in multiple routes. Which is the best way to implement this in Express?
hard
A. Pass requestId as a query parameter in every route URL
B. Store requestId in a global variable and access it in routes
C. Attach requestId to res.locals and access it in routes
D. Create middleware that sets req.context = { requestId: uniqueId } and call next(), then read req.context.requestId in routes

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Create middleware that sets req.context = { requestId: uniqueId } and call next(), then read req.context.requestId in routes -> Option D
  4. Quick Check:

    Use req.context for per-request data sharing [OK]
Hint: Use middleware to set req.context with request ID [OK]
Common Mistakes:
  • Using global variables for request data
  • Relying on query parameters for context
  • Confusing res.locals with request context
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard