📖 Scenario: You are building a simple Node.js server using Express. Middleware functions are like helpers that run in order when a request comes in. The order you add them matters because each middleware can change the request or response, or stop the chain.
🎯 Goal: Build an Express server with two middleware functions and one route handler. Learn how changing the order of middleware affects the server's behavior.
📋 What You'll Learn
Create an Express app
Add a middleware that adds a requestTime property to req
Add a middleware that logs the request method and URL
Add a route handler for GET / that sends back the request time
Understand how changing middleware order changes the output
💡 Why This Matters
🌍 Real World
Middleware ordering is important in real web servers to control authentication, logging, data parsing, and error handling in the right sequence.
💼 Career
Understanding middleware order is key for backend developers working with Node.js and Express to build reliable and maintainable web applications.
Progress0 / 4 steps
1
Create Express app and first middleware
Create an Express app by requiring express and calling express(). Then add a middleware using app.use that adds a requestTime property to the req object with the current date and time as a string.
Node.js
Hint
Use app.use to add middleware. Inside, set req.requestTime to new Date().toISOString() and call next().
2
Add logging middleware
Add a second middleware using app.use that logs the HTTP method and URL of each request using console.log. Use req.method and req.url. Then call next() to continue.
Node.js
Hint
Use app.use again to add the logging middleware. Use template strings to log method and URL.
3
Add route handler for GET /
Add a route handler for GET requests to / using app.get. The handler should send a response with the text: Request time: followed by the requestTime property from req.
Node.js
Hint
Use app.get with path '/'. Send the request time using res.send and template strings.
4
Add server listen and test middleware order
Add app.listen to start the server on port 3000. Then explain how switching the order of the two app.use middleware calls changes whether the log shows before or after the requestTime is set.
Node.js
Hint
Use app.listen(3000) to start the server. Try moving the logging middleware before the requestTime middleware to see how the log changes.
Practice
(1/5)
1. In a Node.js Express app, why does the order of middleware matter?
easy
A. Because middleware order controls the file system permissions
B. Because middleware order changes the port the server listens on
C. Because middleware order determines the database connection string
D. Because middleware runs in the order it is added, affecting request handling
Solution
Step 1: Understand middleware execution order
Middleware functions in Express run in the sequence they are added to the app. This order controls how requests are processed.
Step 2: Recognize impact on request handling
If middleware is out of order, some requests might not be handled correctly or responses might be sent too early.
Final Answer:
Because middleware runs in the order it is added, affecting request handling -> Option D
Quick Check:
Middleware order affects request flow = D [OK]
Hint: Middleware runs top to bottom in code order [OK]
Common Mistakes:
Thinking middleware order affects server port
Confusing middleware order with database config
Assuming middleware order controls file permissions
2. Which of the following is the correct way to add middleware in Express to ensure it runs before route handlers?
easy
A. app.use(middlewareFunction); app.get('/route', handler);
B. app.get('/route', handler); app.use(middlewareFunction);
C. app.listen(3000); app.use(middlewareFunction);
D. app.get('/route', middlewareFunction, handler); app.use();
Solution
Step 1: Identify middleware placement
Middleware should be added before route handlers to process requests first.
Step 2: Check code order
app.use(middlewareFunction); app.get('/route', handler); adds middleware with app.use before defining the route, ensuring middleware runs first.
Final Answer:
app.use(middlewareFunction); app.get('/route', handler); -> Option A
Quick Check:
Middleware before routes = C [OK]
Hint: Add middleware before routes to run first [OK]
A. Middleware 1 does not call next(), so Middleware 2 runs twice
B. Middleware 2 will never run because next() is missing
C. Calling next() after res.send() causes an error or unexpected behavior
D. There is no problem; this order is correct
Solution
Step 1: Understand res.send() effect
Calling res.send() sends the response and ends the request cycle.
Step 2: Analyze calling next() after res.send()
Calling next() after res.send() can cause errors or unexpected behavior because the response is already sent.
Final Answer:
Calling next() after res.send() causes an error or unexpected behavior -> Option C
Quick Check:
Don't call next() after res.send() = A [OK]
Hint: Never call next() after sending response [OK]
Common Mistakes:
Thinking next() is optional after res.send()
Assuming middleware 2 runs normally
Ignoring that response ends request
5. You want to add a logging middleware that logs every request, an authentication middleware that blocks unauthorized users, and a route handler. Which order ensures unauthorized requests are blocked before routes run, but all requests are logged?
hard
A. Authentication middleware, Logging middleware, Route handler
B. Logging middleware, Authentication middleware, Route handler
C. Route handler, Logging middleware, Authentication middleware
D. Route handler, Authentication middleware, Logging middleware
Solution
Step 1: Determine middleware purpose order
Logging should happen for all requests first, so it must be first.
Step 2: Place authentication before route handler
Authentication must run before routes to block unauthorized access.
Step 3: Confirm route handler last
Route handler runs last after middleware passes.
Final Answer:
Logging middleware, Authentication middleware, Route handler -> Option B
Quick Check:
Log first, then auth, then route = A [OK]
Hint: Log first, authenticate second, handle route last [OK]
Common Mistakes:
Putting authentication before logging misses some logs
Running route before middleware breaks flow
Assuming order does not affect blocking unauthorized users
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.