Nearby lessons
13 of 14π Router-Level Middleware in Express JS | Beginner-Friendly Guide
π What is Router-Level Middleware?
π‘ What Is Router-Level Middleware?
Router-level middleware works exactly like application-level middleware,
but it is applied only to routes defined under a specific express.Router() instance.
This helps organize your project by grouping related routes and applying middleware only where needed.
βοΈ Step 1: Understanding Router-Level Middleware
Router-level middleware is attached to a specific router object instead of the entire Express application.
This means the middleware will run only for routes handled by that router.
π Step 2: Router-Level Middleware Example (index.js)
Below is a complete example demonstrating router middleware, router routes, and prefix usage.
Example03
Loading editorβ¦
π How It Works
- π
express.Router()creates a mini Express instance for grouping routes. - βοΈ
router.use()applies middleware to all routes in this router. - π§ The router is used with a prefix using
app.use('/test', router). - π Now all routes inside this router become:
/test//test/about
- π Middleware runs only for routes starting with /test.
π§ Test Your Knowledge
5 QuestionsProgress: 0 / 5