How to use express.Router in Node.js

Express Router enables modular route organization by creating separate route handlers that can be mounted on different paths in your application. As the creator of CoreUI with over 25 years of backend development experience, I use express.Router extensively for building scalable, maintainable API architectures. The most effective approach is creating separate router modules for different feature areas with their own middleware and route definitions. This provides clean separation of concerns and makes large applications easier to maintain and test.

Use express.Router to create modular route handlers that can be mounted at different paths for organized, scalable API structure.

// routes/users.js
const express = require('express')
const router = express.Router()

// Middleware specific to this router
router.use((req, res, next) => {
  console.log('Users route accessed:', new Date())
  next()
})

// Route definitions
router.get('/', (req, res) => {
  res.json({ message: 'Get all users' })
})

router.get('/:id', (req, res) => {
  res.json({ message: `Get user ${req.params.id}` })
})

router.post('/', (req, res) => {
  res.json({ message: 'Create new user', data: req.body })
})

router.put('/:id', (req, res) => {
  res.json({ message: `Update user ${req.params.id}`, data: req.body })
})

router.delete('/:id', (req, res) => {
  res.json({ message: `Delete user ${req.params.id}` })
})

module.exports = router

// app.js
const express = require('express')
const userRoutes = require('./routes/users')
const productRoutes = require('./routes/products')

const app = express()

app.use(express.json())

// Mount routers
app.use('/api/users', userRoutes)
app.use('/api/products', productRoutes)

app.listen(3000)

This implementation creates a separate users router module with its own middleware and route definitions. The router is then mounted at /api/users in the main application, making all routes accessible with that prefix. Router-specific middleware runs only for routes within that router, providing isolated functionality for different API sections.

Best Practice Note:

This modular routing pattern is the foundation of CoreUI’s API templates for scalable backend architecture. Always group related routes into separate router modules and use consistent naming conventions and middleware patterns across your application.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author