0
0
Expressframework~30 mins

Request context middleware in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Request Context Middleware in Express
📖 Scenario: You are building a simple Express server that needs to keep track of some information about each request, like a unique request ID and the time the request started. This helps in logging and debugging.
🎯 Goal: Create a middleware in Express that adds a requestContext object to each incoming request. This object should contain a unique requestId and a startTime. Then, use this context in a route to send back the request ID and start time.
📋 What You'll Learn
Create an Express app with a middleware function
Middleware adds a requestContext object to req
requestContext must have requestId as a unique string
requestContext must have startTime as the current timestamp
Create a GET route /info that returns JSON with requestId and startTime
💡 Why This Matters
🌍 Real World
Middleware like this is used in real web servers to track requests uniquely for logging, debugging, and performance monitoring.
💼 Career
Understanding request context middleware is important for backend developers working with Express or similar frameworks to build maintainable and debuggable web applications.
Progress0 / 4 steps
1
Setup Express app and import required modules
Write code to import express and create an Express app called app. Also, import crypto from Node.js to generate unique IDs.
Express
Need a hint?

Use require('express') to import Express and express() to create the app.

2
Create request context middleware
Create a middleware function called requestContextMiddleware that adds a requestContext object to req. This object should have a requestId generated by crypto.randomUUID() and startTime set to Date.now(). Use app.use(requestContextMiddleware) to apply it.
Express
Need a hint?

Middleware functions take req, res, next. Add requestContext to req and call next().

3
Create GET /info route using request context
Add a GET route /info to app that sends a JSON response with requestId and startTime from req.requestContext.
Express
Need a hint?

Use app.get with path /info. Send JSON with res.json() using values from req.requestContext.

4
Start the Express server
Add code to start the Express server on port 3000 using app.listen. Log a message Server running on port 3000 when it starts.
Express
Need a hint?

Use app.listen(3000, () => { ... }) to start the server and log the message.