Express.js Router is a powerful feature that allows you to modularize your route handling in Node.js applications. It helps organize your code and makes it easier to manage routes by grouping them based on functionality or features. Here's a step-by-step guide on how to use Express.js Router for modular route handling:
Install Express.js: Ensure you have Express.js installed in your project. If not, you can install it using npm:
bashnpm install express
Create a Router Module:
Create a separate file for your router module. This file will contain the routes related to a specific feature or functionality. For example, you could have a file named userRoutes.js
for user-related routes.
javascript// userRoutes.js
const express = require('express');
const router = express.Router();
// Define routes
router.get('/', (req, res) => {
res.send('User home page');
});
router.get('/profile', (req, res) => {
res.send('User profile page');
});
// Export the router
module.exports = router;
Use the Router in Your Main App File:
In your main app file (e.g., app.js
), require the router module and use it for a specific base path. This way, all routes defined in the router module will be prefixed with the specified base path.
javascript// app.js
const express = require('express');
const app = express();
// Require the userRoutes module
const userRoutes = require('./userRoutes');
// Use the userRoutes module for the '/users' base path
app.use('/users', userRoutes);
// Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
With this setup, visiting /users
or /users/profile
will trigger the corresponding route handlers in the userRoutes.js
file.
Organize Your Routes:
You can create multiple router modules for different features and organize your routes accordingly. For example, you might have authRoutes.js
, productRoutes.js
, etc.
javascript// authRoutes.js
const express = require('express');
const router = express.Router();
router.post('/login', (req, res) => {
// Handle login logic
});
router.post('/logout', (req, res) => {
// Handle logout logic
});
module.exports = router;
Then, use these modules in your main app file as needed:
javascript// app.js
const authRoutes = require('./authRoutes');
const productRoutes = require('./productRoutes');
app.use('/auth', authRoutes);
app.use('/products', productRoutes);
This modular approach makes your codebase more maintainable and scalable, especially as your application grows with more routes and features.