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.
Similar Reads
Express Routing in MERN Stack
Express is a powerful framework for building web applications and APIs in NodeJS. When integrated into the MERN (MongoDB, Express, React, Node.js) stack, Express handles server-side routing and provides a robust foundation for handling HTTP requests and responses. In this article, we will explore ho
3 min read
What is Express?
Express is a minimal and flexible web application framework for NodeJS. It provides a robust set of features for building dynamic web applications and APIs, making it one of the most popular frameworks used in the development of web applications on the server side.Simplifies routing and middleware m
5 min read
What is the Use of Router in Express.js ?
Express.js is a powerful and flexible web application framework for Node.js. It simplifies the process of building server-side applications and APIs by providing robust features and tools. Among these tools, routers play a pivotal role in managing and organizing the routes within an application. Thi
4 min read
What is Middleware in Express.js ?
Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle. Middlewares are used for: Change the request or response object.Execute any program or codeEnd the request-response lifecycleCall the next middlewa
2 min read
What is Express Generator ?
Express Generator is a Node.js Framework like ExpressJS which is used to create express Applications easily and quickly. It acts as a tool for generating express applications. In this article, we will discuss the Express Generator.Express GeneratorExpress Generator is a command-line tool for quickly
3 min read
Express.js router.route() Function
The router.route() function returns an instance of a single route that you can then use to handle HTTP verbs with optional middleware. You can also use the router.route() function to avoid duplicate route naming as well as typing errors. Syntax:router.route( path )Parameter: The path parameter holds
2 min read
Routing Path for ExpressJS
What and Why ? Routing in ExpressJS is used to subdivide and organize the web application into multiple mini-applications each having its own functionality. It provides more functionality by subdividing the web application rather than including all of the functionality on a single page. These mini-a
3 min read
Express.js | router.use() Function
The router.use() function uses the specified middleware function or functions. It basically mounts middleware for the routes which are being served by the specific router. Syntax:router.use( path, function )Parameters:Path: It is the path to this middleware, if we can have /user, now this middleware
2 min read
Setting a Default route in Express.js
What is a default route?As we know that in an express application, there are so many URLs and requests involved. It might be possible that the user hit a route which is not included in our express app. In that case, the user will get an error for handling these kinds of issues, we set a default rout
2 min read
Getting Started with Express JS
Express JS is a versatile, minimalist web framework for NodeJS that simplifies the development of back-end applications and APIs for web and mobile applications. Its flexibility and powerful features enable you to create robust and scalable web projects with minimal code, making it a popular choice
6 min read