When building web applications with Node.js and Express, routes and routers are the pathways that connect incoming client requests to specific parts of your code. Understanding routes and routers is essential for organizing your application, especially as it grows in size and complexity.
Think of routes as streets in a city. Each street leads to a different place — some take you to a park, others to a store. Similarly, routes in Express direct HTTP requests to different parts of your server logic.
A route in Express defines a URL pattern and connects it to a function that handles the request. These are typically based on HTTP methods like GET, POST, PUT, DELETE.
const express = require('express');
const app = express();
app.get('/welcome', (req, res) => {
res.send('Welcome to the homepage!');
});
app.post('/submit', (req, res) => {
res.send('Form submitted!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Explanation: This code sets up two routes: one for GET requests to /welcome and another for POST requests to /submit. When the server receives a request at one of these paths, it runs the corresponding function.
Imagine a restaurant. When a customer walks through the main door, they’re directed to a specific table depending on their reservation. Similarly, routes handle different requests and direct them to the right "table" or function.
As your application grows, managing all routes in a single file becomes messy. Routers help you organize routes into separate files or modules — like zoning a city into districts. Each district (router) manages its own set of streets (routes), making the city easier to navigate and maintain.
Routers in Express are mini-applications. You can define routes within them and then use them in your main app.
Folder structure:
project_folder/
├── routes/
│ └── users.js
├── app.js
routes/users.js:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('User list');
});
router.get('/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
module.exports = router;
app.js:
const express = require('express');
const app = express();
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Explanation: The users.js router handles all routes starting with /users. In app.js, app.use('/users', userRoutes) tells Express to use the router for all /users paths. This helps organize code and makes it modular and scalable.
In a blogging platform:
/users router handles user registration and login./posts router handles creating, viewing, and deleting blog posts./comments router handles commenting on posts.This modularity makes development faster and easier, especially as the platform grows in complexity.
/api/v1, /api/v2).Route Parameters:
app.get('/product/:id', (req, res) => {
res.send(`Product ID: ${req.params.id}`);
});
Route Middleware Example:
const checkAuth = (req, res, next) => {
if (req.headers.token === 'secret') {
next();
} else {
res.status(401).send('Unauthorized');
}
};
app.get('/dashboard', checkAuth, (req, res) => {
res.send('Welcome to your dashboard');
});
Express routes and routers are the navigation system of your application. Routes define the paths, and routers help you organize them into manageable parts. Like a well-planned city, a well-structured application is easier to maintain, scale, and develop.
Start with basic routes, then grow into routers as your app evolves. Practice by building small apps like task managers or blog platforms, and explore more advanced topics like route protection, middleware, and error handling to solidify your skills. Happy routing!