0
0
Expressframework~30 mins

Router level middleware in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Router-level Middleware in Express
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use app.use('/users', userRouter) to connect the router to the app.