Express Router

📘 Express.js 👁 51 views 📅 Nov 05, 2025
⏱ 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.js with too many routes


2. Creating a Router

Step 1: Create a router file

Example: routes/users.js

const express = require('express'); const router = express.Router(); // GET /users router.get('/', (req, res) => { res.send('List of users'); }); // GET /users/:id router.get('/:id', (req, res) => { res.send(`User ID: ${req.params.id}`); }); // POST /users router.post('/', (req, res) => { res.send('User created'); }); module.exports = router;

Step 2: Use the router in app.js

const express = require('express'); const app = express(); const port = 3000; // Import the router const userRouter = require('./routes/users'); // Mount the router on a path app.use('/users', userRouter); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
  • /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:

// users.js router.use((req, res, next) => { console.log(`Request to /users: ${req.method} ${req.url}`); next(); });
  • Middleware executes only for routes defined in this router.


4. Modular Routing Structure

Example Project Structure:

express-app/ │ ├─ routes/ │ ├─ users.js │ └─ posts.js │ ├─ views/ │ └─ ... │ └─ app.js
  • app.js handles main app and mounting routers

  • Each router file handles a specific resource


5. Advantages of Express Router

  1. Organized code – Avoids large app.js files

  2. Reusability – Routers can be reused across apps

  3. Scoped Middleware – Apply middleware to specific routes

  4. Scalability – Makes it easier to grow applications


6. Example: Multiple Routers

// app.js const express = require('express'); const app = express(); const userRouter = require('./routes/users'); const postRouter = require('./routes/posts'); app.use('/users', userRouter); app.use('/posts', postRouter); app.listen(3000, () => console.log('Server running on port 3000'));
  • /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.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes