Express Router
⏱ Estimated reading time: 2 min
The Express Router is a mini application within an Express app that helps organize routes into modular and reusable components.
It is especially useful for large applications to separate routes for different resources.
1. Why Use Express Router?
-
Keep routes modular and organized
-
Separate route logic by resource (e.g., users, posts)
-
Apply middleware only to specific routes
-
Avoid cluttering
app.jswith too many routes
2. Creating a Router
Step 1: Create a router file
Example: routes/users.js
Step 2: Use the router in app.js
-
/users→ List of users -
/users/123→ User ID: 123 -
/users(POST) → User created
3. Router-Level Middleware
You can apply middleware only to a specific router:
-
Middleware executes only for routes defined in this router.
4. Modular Routing Structure
Example Project Structure:
-
app.jshandles main app and mounting routers -
Each router file handles a specific resource
5. Advantages of Express Router
-
Organized code – Avoids large
app.jsfiles -
Reusability – Routers can be reused across apps
-
Scoped Middleware – Apply middleware to specific routes
-
Scalability – Makes it easier to grow applications
6. Example: Multiple Routers
-
/users→ Handled by users router -
/posts→ Handled by posts router
Express Router is essential for structuring medium to large applications, keeping routes clean, modular, and maintainable.
Register Now
Share this Post
← Back to Tutorials