What is Routing in Express?
Last Updated :
24 Feb, 2025
In web applications, without routing it becomes difficult for the developers to handle multiple different requests because they have to manually process each URL request in a single function this problem was solved by the express router which provides a structured way to map different requests to their respective handlers.
What is Routing?
Routing in ExpressJS defines how your application responds to different HTTP requests (GET, POST, PUT, DELETE, etc.) to specific URL endpoints. It involves associating each request type and URL path with a handler function that will process that request. ExpressJS uses a routing table to store these mappings and efficiently direct incoming requests to the correct handler.
How Does Routing Work in ExpressJS?
Routing in Express follows a simple pattern
app.METHOD(PATH, HANDLER);
- app: Represents an instance of an Express application.
- METHOD: Represents an HTTP method like GET, POST, PUT, DELETE.
- PATH: Defines the endpoint (route) where the request will be handled.
- HANDLER: A function that executes when the route is accessed.
JavaScript
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Express Routing!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Output
Express RoutingThis sets up a GET route at /, which responds with 'Welcome to Express Routing!'.
Types of Routes
Basic Routes in ExpressJS
Basic routing involves defining a URL and specifying an HTTP method (GET, POST, PUT, DELETE, etc.).
app.get('/home', (req, res) => {
res.send('Welcome to the Home Page!');
});
app.post('/submit', (req, res) => {
res.send('Form Submitted Successfully!');
});
- /home handles GET requests.
- /submit handles POST requests.
Route Parameters in ExpressJS
Route parameters allow capturing dynamic values from URLs, making routes flexible and reusable.
app.get('/users/:userId', (req, res) => {
res.send(`User ID: ${req.params.userId}`);
});
- :userId is a route parameter.
- req.params.userId extracts the value.
Optional and Multiple Route Parameters
Express allows defining optional parameters and multiple parameters in a single route.
app.get('/products/:productId?', (req, res) => {
res.send(`Product ID: ${req.params.productId || 'No product selected'}`);
});
- /products/123 → Product ID: 123
- /products/ → No product selected
Multiple Route Parameters
app.get('/posts/:category/:postId', (req, res) => {
res.send(`Category: ${req.params.category}, Post ID: ${req.params.postId}`);
});
/posts/tech/456 → Category: tech, Post ID: 456
Query Parameters in ExpressJS
Query parameters are used for filtering or modifying requests. They appear after the ? symbol in URLs.
app.get('/search', (req, res) => {
res.send(`Search results for: ${req.query.q}`);
});
req.query.q extracts q from the URL.
Route Handlers in ExpressJS
Route handlers define how Express responds to requests.
app.get('/example', (req, res, next) => {
console.log('First handler executed');
next();
}, (req, res) => {
res.send('Response from second handler');
});
The next() function passes control to the next handler.
Route Chaining in ExpressJS
Chaining allows defining multiple handlers for a route using .route().
app.route('/user')
.get((req, res) => res.send('Get User'))
.post((req, res) => res.send('Create User'))
.put((req, res) => res.send('Update User'))
.delete((req, res) => res.send('Delete User'));
/user supports multiple HTTP methods using .route().
Implementing Routing in Express
To implement routing in an ExpressJS application, follow these steps:
Step 1: Initialize the Node.js Application
Open your terminal, navigate to your project directory, and initialize the application:
npm init -y
Step 2: Install ExpressJS
Install ExpressJS as a dependency:
npm install express
Step 3: Create the Server File
Create a file named server.js and add the following code:
JavaScript
const express = require('express');
const app = express();
const PORT = 4000;
app.get('/', (req, res) => {
res.send('<h1>Welcome to the Home Page!</h1>');
});
app.get('/about', (req, res) => {
res.send('<h1>About Us</h1><p>This is the About page.</p>');
});
app.get('/contact', (req, res) => {
res.send('<h1>Contact Us</h1><p>Feel free to reach out!</p>');
});
app.listen(PORT, () => {
console.log(`Server is listening at http://localhost:${PORT}`);
});
Step 4: Start the Server
In the terminal, run the server
node server.js
Output
In this example
- Import and initialize the Express app using const app = express().
- Set up routes for /, /about, and /contact, each sending HTML content.
- Start the server to listen on port 4000 with app.listen(PORT).
- Print a message in the terminal confirming the server is running at http://localhost:4000.
Advantages of Routing in Express
- Code Organization: Express routing simplifies code structure by managing functionalities separately.
- Readability: It enhances code understanding by clearly defining how different URLs are handled.
- Scalability: Routing allows for the easy addition of new features without major codebase changes.
- SEO-friendly: Good routing means creating web addresses that search engines like, making your app more visible and user-friendly in search results.
- RESTful API Design: Routing in Express is great for building powerful and scalable services, especially when creating APIs that follow the RESTful design principles.
Best Practices for Routing in ExpressJS
- Use Express Router: Utilize express.Router() to create modular route handlers, enhancing code organization and maintainability.
- Define Clear Route Paths: Establish explicit and consistent route paths to ensure predictable application behavior.
- Implement Middleware Functions: Apply middleware for tasks like authentication and logging to keep route handlers concise.