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.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read