- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js Route Parameters
In modern web development, we rarely deal with purely static URLs. Instead of creating a unique route for every single user or product in your database, Express.js allows you to define Route Parameters. These are dynamic segments of a URL that act as placeholders. When a request is made, Express captures the values in these segments and provides them to you inside the req.params object.
Route parameters are essential for building RESTful APIs. For example, rather than having a route like /view-profile-123, you define a single route as /users/:id. This makes your URL structure clean, hierarchical, and easy to maintain.
Key Features of Route Parameters
- Dynamic Segments: You can turn any part of a URL into a variable by prefixing it with a colon (e.g.,
:usernameor:productId). - The req.params Object: Express automatically parses these values and attaches them to the
req.paramsobject, where the keys match the names you defined in the route. - Flexible Routing: Parameters work across all HTTP methods, including GET (fetching data), POST (submitting data to a specific resource), and DELETE (removing a specific item).
:data, use :userId or :slug. This makes your code self-documenting and easier for other team members to understand.
Steps to Use Route Parameters in Express.js
1. Set up a Basic Express Application
First, prepare your environment. Initialize your Node.js project and install the Express framework using the terminal:
npm init -y
npm install express --save
2. Create an Express Application with Route Parameters
Create a file named app.js. In the example below, we will handle a variety of common scenarios, from fetching a single user to handling complex product categories.
const express = require('express');
const app = express();
// Basic route with a single parameter
// Example: /user/42
app.get('/user/:id', (req, res) => {
// Accessing the parameter via destructuring (cleaner code)
const { id } = req.params;
res.send(`Fetching data for User ID: ${id}`);
});
// Route with multiple parameters
// Example: /shop/electronics/laptops
app.get('/shop/:category/:item', (req, res) => {
const { category, item } = req.params;
res.send(`Category: ${category}, Item: ${item}`);
});
// Route with an optional parameter using the '?' suffix
// Example: /reports or /reports/daily
app.get('/reports/:type?', (req, res) => {
const reportType = req.params.type || 'standard';
res.send(`Generating ${reportType} report...`);
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
:) when defining the route. If you write app.get('/user/id'), Express will look for the literal string "id" instead of treating it as a dynamic parameter.
3. Run the Application
Fire up your server by running the following command in your terminal:
node app.js
4. Test the Routes
You can test these immediately in your browser or through a tool like Postman:
http://localhost:3000/user/101→ Returns "Fetching data for User ID: 101"http://localhost:3000/shop/books/fiction→ Returns "Category: books, Item: fiction"http://localhost:3000/reports→ Returns "Generating standard report..." (Optional parameter handled)
parseInt() or Number() before using it in mathematical operations or strict database queries.
Handling Multiple Parameters
When building complex applications like a blog or an e-commerce platform, you often need to drill down through multiple levels of data. You can chain as many parameters as needed, separated by slashes. Express will map them in the order they appear.
// Real-world example: Accessing a specific comment on a specific blog post
app.get('/posts/:postId/comments/:commentId', (req, res) => {
const { postId, commentId } = req.params;
res.json({
message: `Reading comment ${commentId} on post ${postId}`,
timestamp: new Date()
});
});
Optional Parameters
Sometimes a piece of information is helpful but not strictly required for the route to function. By adding a question mark ? to the end of a parameter name, you tell Express that the segment is optional. If the user doesn't provide it, the value in req.params will be undefined.
/search?q=javascript) for filtering or sorting, as they are generally more standard for non-identifying data.
Summary
Route parameters are an incredibly powerful feature of Express.js that transform static paths into dynamic API endpoints. They allow you to capture data directly from the URL, making your application more interactive and SEO-friendly. By mastering req.params, handling multiple segments, and properly validating your inputs, you can build robust backends that scale gracefully as your data grows.