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.
Keep routes modular and organized
Separate route logic by resource (e.g., users, posts)
Apply middleware only to specific routes
Avoid cluttering app.js with too many routes
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
You can apply middleware only to a specific router:
Middleware executes only for routes defined in this router.
Example Project Structure:
app.js handles main app and mounting routers
Each router file handles a specific resource
Organized code – Avoids large app.js files
Reusability – Routers can be reused across apps
Scoped Middleware – Apply middleware to specific routes
Scalability – Makes it easier to grow applications
/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.
Take quizzes related to this topic and see where you stand!
Start Quiz Now