Accessing URL Parameters in Express.js
Express.js, a popular Node.js web application framework, provides flexible ways to access information passed through URLs. This tutorial will cover how to retrieve both route parameters (those embedded directly in the route path) and query parameters (those appended to the URL after a question mark).
Understanding Route and Query Parameters
Before diving into the code, let’s clarify the difference:
- Route Parameters: These are variables embedded directly within the URL path itself. For example, in the route
/products/:productId
,:productId
is a route parameter. The value ofproductId
will change depending on the URL requested (e.g.,/products/123
,/products/456
). They define the structure of the route. - Query Parameters: These are appended to the URL after a question mark (
?
). They’re used to pass additional data to the server without changing the core route. For example,/search?q=shoes&color=blue
. Here,q
andcolor
are query parameters.
Accessing Route Parameters
To access route parameters, use the req.params
object. Express automatically populates this object with the values from your route definitions.
const express = require('express');
const app = express();
app.get('/products/:productId', (req, res) => {
const productId = req.params.productId;
res.send(`You requested product with ID: ${productId}`);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
In this example, if you navigate to /products/123
, req.params.productId
will be set to "123"
. The value is always a string, so you might need to convert it to a number if that’s what your application requires.
Accessing Query Parameters
To access query parameters, use the req.query
object. Express parses the query string and makes the values available as properties of this object.
const express = require('express');
const app = express();
app.get('/search', (req, res) => {
const query = req.query.q;
const color = req.query.color;
let results = `You searched for: ${query}`;
if (color) {
results += ` with color: ${color}`;
}
res.send(results);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
If you navigate to /search?q=shoes&color=blue
, then req.query.q
will be "shoes"
and req.query.color
will be "blue"
. Like route parameters, query parameter values are strings by default.
Express Version Considerations
The core methods for accessing parameters (req.params
and req.query
) are consistent across most versions of Express. However, older versions (Express 3.x) might use req.param()
as an alternative to req.params
for route parameters. It’s generally recommended to stick with req.params
and req.query
for better compatibility and clarity.
Parameter Middleware
Express also provides a powerful feature called parameter middleware. This allows you to define middleware functions that run before the route handler for a specific parameter. This is useful for validation, type coercion, or loading related data.
const express = require('express');
const app = express();
// Parameter middleware for tagid
app.param('tagid', (req, res, next, tagid) => {
// Validate tagid (e.g., check if it's a number)
if (isNaN(parseInt(tagid))) {
return res.status(400).send('Invalid tagid');
}
// Convert tagid to a number
req.tagid = parseInt(tagid);
next(); // Call next to pass control to the route handler
});
app.get('/api/tags/:tagid', (req, res) => {
// req.tagid is now available and guaranteed to be a valid number
res.send(`Tag ID: ${req.tagid}`);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
In this example, the parameter middleware validates that tagid
is a number before the route handler is executed. It also converts the value to an integer and stores it on the req
object for easy access.
Best Practices
- Use descriptive parameter names: Choose names that clearly indicate the purpose of the parameter (e.g.,
productId
instead of justid
). - Validate input: Always validate user input (including URL parameters) to prevent security vulnerabilities and ensure data integrity.
- Consider type coercion: Convert parameter values to the appropriate data type (e.g., number, boolean) as needed.
- Leverage parameter middleware for complex logic: Use parameter middleware to encapsulate validation, data loading, or other pre-processing tasks.