How To Handle Route Parameters in Express?
Last Updated :
24 Feb, 2025
Route parameters in ExpressJS capture dynamic values from URLs, like /users/:userId. These values are accessible in your route handler via req.params, enabling dynamic content generation. This allows for creating reusable routes that handle various inputs with a single pattern.
JavaScript
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
// Logic to handle the user with the specified userId
});
- /users/:userId: The :userId is the route parameter that captures the value in the URL after /users/.
- req.params.userId: This retrieves the captured value from the URL, allowing you to use it within the route handler to fetch data or perform actions.
Handling Route Parameters in ExpressJS
Route parameters in ExpressJS allow you to capture dynamic values from the URL and use them in your application. This section explains how to handle basic, optional, and multiple route parameters.
1. Basic Route Parameter Handling
Route parameters are used to capture values from the URL. You can access these parameters through req.params and use them in your route handler.
JavaScript
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
res.send(`<h1>User Profile</h1><p>User ID: ${userId}</p>`);
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- /users/:userId: :userId is a route parameter that captures the value after /users/.
- req.params.userId: Access the captured value and use it in the route handler for further logic.
Output: Accessing http://localhost:3000/users/123 will display
Basic Route Parameter Handling2. Optional Route Parameters
You can define optional route parameters by adding a question mark (?) after the parameter name. This means that the route will match even if the parameter is not provided.
JavaScript
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/products/:productId?', (req, res) => {
const productId = req.params.productId || 'default';
res.send(`<h1>Product Page</h1><p>Product ID: ${productId}</p>`);
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- /products/:productId?: :productId is optional, meaning the route will match with or without the productId.
- req.params.productId || 'default': If no productId is provided, 'default' will be used instead.
Output: Accessing http://localhost:3000/products/123 will display
Route ParametersAccessing http://localhost:3000/products/ will display
Product Page
Product ID: default
3. Multiple Route Parameters
Express allows you to define multiple route parameters in a single route. You can capture several dynamic values from the URL by adding multiple colon-prefixed parameters.
JavaScript
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/posts/:category/:postId', (req, res) => {
const category = req.params.category;
const postId = req.params.postId;
res.send(`<h1>Post</h1><p>Category: ${category}, Post ID: ${postId}</p>`);
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- /posts/:category/:postId: The route captures both category and postId from the URL.
- req.params.category and req.params.postId: Access the captured values for use in the handler.
Output Accessing http://localhost:3000/posts/tech/456 will display
Multiple Route ParametersBest Practices for Handling Route Parameters
- Use Descriptive Parameter Names: Choose clear and meaningful names for route parameters to enhance code readability and maintainability.
- Validate Parameter Values: Implement validation to ensure that the captured parameter values meet the expected format and constraints.
- Handle Missing Parameters Gracefully: Provide default values or appropriate error messages when optional parameters are absent.
How to handle Route Parameters in Express - FAQs
How do I define a route with parameters in ExpressJS?
Use the colon syntax in the route path to define parameters, such as /users/:userId.
Can I use regular expressions with route parameters?
Yes, Express allows the use of regular expressions in route parameters to match specific patterns.
How can I handle multiple parameters in a single route?
Define multiple parameters in the route path, separated by slashes, like /posts/:category/:postId.
Is it possible to make route parameters optional?
Express does not natively support optional route parameters; however, you can simulate optional parameters by using regular expressions in the route path.
How do I access route parameters in the route handler?
Access route parameters through the req.params object, using the parameter name as the key.
Similar Reads
How To Handle Route Parameters in Express?
Route parameters in ExpressJS capture dynamic values from URLs, like /users/:userId. These values are accessible in your route handler via req.params, enabling dynamic content generation. This allows for creating reusable routes that handle various inputs with a single pattern. [GFGTABS] JavaScript
4 min read
How to handle URL parameters in Express ?
In this article, we will discuss how to handle URL parameters in Express. URL parameters are a way to send any data embedded within the URL sent to the server. In general, it is done in two different ways. Table of Content Using queriesUsing Route parameterSteps to Create Express Application:Let's i
3 min read
How to Handle Route Parameters in Angular?
In Angular, routing plays an important role in building single-page applications (SPAs). Often, you need to pass data between components through the URL using route parameters. Route parameters allow you to define dynamic segments in your routes, which can be extracted and used in your components. T
3 min read
How do you handle nested routes in Express.js?
In this article we are going to learn that how can we setup nested routes in Express JS. Nested routes are the routes that are defined within other routes. This is used to organize your code. We are going to implement the nested routes using the below given two approaches. Table of Content Using Exp
2 min read
How to use get parameter in Express.js ?
Express Js is a web application framework on top of Node.js web server functionality that reduces the complexity of creating a web server. Express provides routing services i.e., how an application endpoint responds based on the requested route and the HTTP request method (GET, POST, PUT, DELETE, UP
2 min read
How do you access query parameters in an Express JS route handler?
Express JS is a popular web framework for Node JS, simplifies the development of web applications. One common task is accessing query parameters from URLs within route handlers. In this article, we'll explore the fundamentals of working with query parameters in Express JS and demonstrate how to acce
2 min read
How to receive post parameter in Express.js ?
Express is a small framework that sits on top of Node.jsâs web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing; it adds helpful utilities to Node.jsâs HTTP objects; it facilitates the
3 min read
How to handle redirects in Express JS?
Express JS uses redirects to send users from one URL to another. This can be done for various reasons, such as handling outdated URLs or guiding users through a process. In ExpressJS, you define routes and use them to direct users to the desired URL. It's a way to keep your application organized and
2 min read
How to filter path of routes in Express.js ?
Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client's different incoming requests. In this article, we will be discussing how to filter the paths of routes using the express.js in node.js. The ap
2 min read
How to Use Handle Get Request in Express.js ?
Express.js is a popular web application framework for Node.js, known for its simplicity and flexibility. One of the fundamental tasks in web development is handling HTTP requests, and GET requests are among the most common. This article will guide you through the process of handling GET requests in
3 min read