When building web applications or APIs with Express.js, it's essential to understand how to work with route parameters and query strings. These two features allow your server to respond dynamically based on values sent in the URL.
In this post, you’ll learn:
- What route parameters and query strings are
- How to use them in Express
- Real-world examples
What Are Route Parameters?
Route parameters are parts of the URL path that are treated as variables. They are defined using a colon (:
).
Example:
GET /users/123
In this case, 123
is a dynamic route parameter, typically representing a user ID.
How to Access Route Parameters in Express
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is ${userId}`);
});
If you visit http://localhost:3000/users/42
, the server will respond with:
User ID is 42
You can also have multiple parameters:
app.get('/users/:userId/posts/:postId', (req, res) => {
const { userId, postId } = req.params;
res.send(`User: ${userId}, Post: ${postId}`);
});
What Are Query Strings?
Query strings are key-value pairs added to the end of a URL after a ?
.
Example:
GET /search?term=express&page=2
Here:
term=express
page=2
How to Access Query Strings in Express
app.get('/search', (req, res) => {
const { term, page } = req.query;
res.send(`Searching for "${term}" on page ${page}`);
});
If you visit http://localhost:3000/search?term=node&page=3
, the response will be:
Searching for "node" on page 3
Combining Both
You can use route parameters and query strings together.
Example:
app.get('/users/:id/details', (req, res) => {
const userId = req.params.id;
const { includePosts } = req.query;
res.send(`User ID: ${userId}, Include Posts: ${includePosts}`);
});
Visit:
http://localhost:3000/users/5/details?includePosts=true
Response:
User ID: 5, Include Posts: true
Use Cases
Feature | Use Case Example |
---|---|
Route Parameters |
/products/:id for product details |
Query Strings | /products?category=books&sort=price |
Summary
Feature | Syntax Example | Access in Express |
---|---|---|
Route Parameters |
/users/:id → /users/12
|
req.params.id |
Query Strings | /search?term=book&page=2 |
req.query.term , req.query.page
|
Understanding how to handle route parameters and query strings helps you build flexible, dynamic APIs and pages with Express.
Top comments (0)