📖 Scenario: You are building a simple Express server that handles user-related routes. You want to add middleware that only applies to these user routes to log each request's method and URL.
🎯 Goal: Create router-level middleware in Express that logs the HTTP method and URL for all requests to the /users routes.
📋 What You'll Learn
Create an Express router named userRouter
Add router-level middleware to userRouter that logs the HTTP method and URL
Create a GET route /users/profile that sends a simple text response
Mount userRouter on the main Express app at the /users path
💡 Why This Matters
🌍 Real World
Router-level middleware helps organize code by applying middleware only to specific groups of routes, like user-related routes in a web app.
💼 Career
Understanding router-level middleware is essential for building scalable Express applications and is a common task in backend web development jobs.
Progress0 / 4 steps
1
Create the Express app and userRouter
Create an Express app by calling express() and assign it to app. Then create a router by calling express.Router() and assign it to userRouter.
Express
Hint
Use const app = express() to create the app and const userRouter = express.Router() to create the router.
2
Add router-level middleware to userRouter
Add middleware to userRouter using userRouter.use(). The middleware should be a function with parameters req, res, and next. Inside it, log the HTTP method and URL using console.log(req.method, req.url). Then call next() to continue.
Express
Hint
Use userRouter.use((req, res, next) => { ... }) to add middleware that logs and calls next().
3
Add a GET route /profile to userRouter
Add a GET route to userRouter for path /profile using userRouter.get('/profile', ...). The route handler should send the text 'User Profile' as the response using res.send().
Express
Hint
Use userRouter.get('/profile', (req, res) => { res.send('User Profile') }) to add the route.
4
Mount userRouter on the app at /users
Use app.use('/users', userRouter) to mount the userRouter on the main app at the path /users.
Express
Hint
Use app.use('/users', userRouter) to connect the router to the app.
Practice
(1/5)
1. What is the main purpose of router-level middleware in Express?
easy
A. To replace the main app middleware completely
B. To run middleware only for routes defined in a specific router
C. To handle errors globally across all routers
D. To serve static files from a directory
Solution
Step 1: Understand router-level middleware scope
Router-level middleware runs only for routes defined in that router, not the entire app.
Step 2: Compare with other middleware types
Main app middleware runs for all routes, error middleware handles errors, static middleware serves files. Router middleware is specific to router routes.
Final Answer:
To run middleware only for routes defined in a specific router -> Option B
Quick Check:
Router middleware scope = specific router routes [OK]
Hint: Router middleware affects only its router's routes [OK]
Common Mistakes:
Confusing router middleware with app-level middleware
A. The last middleware does not call next(), causing requests to hang
B. The last middleware is missing next() and will cause 404 for all routes
C. The last middleware will never run because it is after a route handler
D. The last middleware should have 4 parameters to handle errors
Solution
Step 1: Analyze middleware execution order
Middleware and routes execute in the order defined. First middleware runs for all requests and calls next().
Step 2: Trace unmatched route behavior
For unmatched routes like /foo: first middleware calls next(), /hello route doesn't match so next(), last middleware runs but does nothing--no response and no next() call.
Step 3: Identify the consequence
The request pipeline stops without a response, causing the client request to hang indefinitely.
Final Answer:
The last middleware does not call next(), causing requests to hang -> Option A
Quick Check:
No response + no next() = request hangs [OK]
Hint: Every middleware must either respond or call next() [OK]
Common Mistakes:
Thinking empty catch-all middleware is harmless
Forgetting unmatched routes reach the last middleware
Assuming the router automatically handles 404s
5. You want to apply a logging middleware only to routes under /api in your Express app. You create a router and add middleware like this: