
When it comes to building complex web applications with Express, having a solid understanding of routers is crucial.
Routers in Express provide a modular and organized approach to handle different routes and requests within your application.
In this blog post, we’ll dive deep into the world of routers and explore how they can simplify your web application development process. So, let’s get started!
What are Routers in Express?
Express routers are a powerful feature that allows you to create modular, self-contained sets of routes within your application.
They provide a way to organize and structure your code by separating different routes and their associated logic into distinct files.
Routers act as middleware and can be used to handle specific routes or groups of related routes, making your code more maintainable and scalable.
Benefits of Using Routers
Using routers in Express offers several benefits for your web application development:
1. Modularity and Organization: Routers enable you to break down your application’s routes into separate files, making it easier to manage and maintain your codebase. Each router can focus on a specific set of routes, ensuring clean separation of concerns.
2. Code Reusability: Routers allow you to reuse common route handlers across different parts of your application. This eliminates code duplication and promotes a more efficient development workflow.
3. Route Grouping: With routers, you can group related routes together based on functionality or resource type. This makes it easier to manage and update specific sections of your application without affecting others.
4. Middleware Flexibility: Routers can define their own middleware functions, allowing you to apply specific middleware to a group of routes. This helps in implementing authentication, error handling, and other common functionalities in a centralized manner.
Desired Folder Structure

Implementing Routers in Express
Let’s explore how to implement routers in Express using a practical example:
1. Create a new file called users.js in your project directory.
2. In users.js, import the necessary modules and create a new router:
const express = require('express');
const router = express.Router();
3. Define the routes for the user-related functionality
router.get('/', (req, res) => {
// Logic for handling user list retrieval
});
router.post('/', (req, res) => {
// Logic for creating a new user
});
router.get('/:id', (req, res) => {
// Logic for retrieving a specific user by ID
});
router.put('/:id', (req, res) => {
// Logic for updating a user by ID
});
router.delete('/:id', (req, res) => {
// Logic for deleting a user by ID
});
Export the router from the users.js file:
module.exports = router;
In your main application file (e.g., app.js), import the users.js router and use it for the desired route:
const usersRouter = require('./users');
//...
app.use('/users', usersRouter);
Here’s an implementation of an Express project that uses routers
Folder Structure (click)
- app/
- controllers/
- userController.js
- models/
- userModel.js
- routes/
- userRoutes.js
- views/
- index.ejs
- config/
- database.js
- app.js
- package.json
- README.md
app/controllers/userController.js
// Example userController with a simple route handler
exports.getUsers = (req, res) => {
// Logic for retrieving users
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
];
res.json(users);
};
app/routes/userRoutes.js
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
// Route to retrieve users
router.get('/', userController.getUsers);
module.exports = router;
app/views/index.ejs
<!DOCTYPE html>
<html>
<head>
<title>Express App</title>
</head>
<body>
<h1>Welcome to the Express App!</h1>
<p>Visit the <a href="/users">users route</a>.</p>
</body>
</html>
app.js
const express = require('express');
const app = express();
// Importing the userRoutes from the routes folder
const userRoutes = require('./app/routes/userRoutes');
// Middleware to parse JSON bodies
app.use(express.json());
// Mounting the userRoutes
app.use('/users', userRoutes);
// Starting the server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
package.json
{
"name": "express-project",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "^4.17.1"
}
}
With this setup, first install all the dependencies:
npm i
you can run the project by executing the following command in your project directory:
npm start
The server will start running on port 3000, and you can visit http://localhost:3000/users to see the users route in action. Additionally, visiting the root URL (http://localhost:3000) will display the index.ejs view.
Feel free to extend and modify this code to suit your specific needs and add more routes, controllers, and views as your project evolves.
Keywords to search: routes in express, defining routes in express, express routers, how to define routes in express, routing express.
