Table Of Contents
Problem
Your Express.js application has many routes scattered in one file, making it hard to maintain and organize. You need to group related routes and apply middleware to specific route groups.
Solution
// app.js
const express = require('express');
const userRoutes = require('./routes/users');
const productRoutes = require('./routes/products');
const app = express();
app.use(express.json());
// Mount route groups
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);
app.get('/', (req, res) => {
res.send('Main app running');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
// routes/users.js
const express = require('express');
const router = express.Router();
// Middleware for all user routes
router.use((req, res, next) => {
console.log('User route accessed:', req.method, req.path);
next();
});
// GET /api/users
router.get('/', (req, res) => {
res.json({ users: ['John', 'Jane', 'Bob'] });
});
// GET /api/users/:id
router.get('/:id', (req, res) => {
const userId = req.params.id;
res.json({ user: `User ${userId}` });
});
// POST /api/users
router.post('/', (req, res) => {
const newUser = req.body;
res.status(201).json({
message: 'User created',
user: newUser
});
});
// PUT /api/users/:id
router.put('/:id', (req, res) => {
const userId = req.params.id;
res.json({
message: `User ${userId} updated`,
user: req.body
});
});
module.exports = router;
// routes/products.js
const express = require('express');
const router = express.Router();
// Authentication middleware for all product routes
const authenticate = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
next();
};
router.use(authenticate);
// GET /api/products
router.get('/', (req, res) => {
res.json({ products: ['Laptop', 'Phone', 'Tablet'] });
});
// POST /api/products
router.post('/', (req, res) => {
res.status(201).json({
message: 'Product created',
product: req.body
});
});
module.exports = router;
Explanation
express.Router()
creates modular route handlers that can be mounted on your main app. Each router acts like a mini-application with its own middleware and routes.
app.use('/api/users', userRoutes)
mounts the user router at the /api/users
path, so routes defined as router.get('/')
become accessible at /api/users/
. This pattern keeps your code organized and allows you to apply middleware to specific route groups easily.
Share this article
Add Comment
No comments yet. Be the first to comment!