Introduction
Route parameters are dynamic values embedded within a URL that allow a server to identify or process specific resources. Unlike frameworks such as Express, the native Node.js http module does not provide built-in support for route parameters, so developers must parse the request URL manually.
Information
Prerequisites
- Node.js installed
- Basic knowledge of JavaScript
- Familiarity with the http module
- Understanding of basic routing using req.url
What are Route Parameters?
Route parameters are variable parts of a URL that represent specific resources. For example, in the URL /users/101, the value 101 identifies a particular user.
| URL | Route Parameter | Meaning |
|---|---|---|
| /users/101 | 101 | User ID |
| /products/25 | 25 | Product ID |
| /books/9781234567890 | 9781234567890 | Book ISBN |
How Route Parameters Work
Project Structure
Parsing the URL
A simple way to extract route parameters is to split the requested URL into individual path segments using the split() method.
Extracting URL Segments
const urlParts = req.url.split("/");
console.log(urlParts);
// Request: /users/101
// Output:
// ["", "users", "101"]Understanding the URL Segments
| Index | Value | Description |
|---|---|---|
| 0 | "" | Empty string before the first slash. |
| 1 | users | Resource name. |
| 2 | 101 | Route parameter. |
Example: Handling a User ID
The following example extracts a user ID from the URL and returns it in the response.
Handling a User Route Parameter
const http = require("http");
const server = http.createServer((req, res) => {
const parts = req.url.split("/");
if (parts[1] === "users" && parts.length === 3) {
const userId = parts[2];
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end(`User ID: ${userId}`);
}
else {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end("Route Not Found");
}
});
server.listen(3000);Testing the Server
| Request URL | Response |
|---|---|
| /users/1 | User ID: 1 |
| /users/25 | User ID: 25 |
| /users/999 | User ID: 999 |
Handling Multiple Route Parameters
A URL can contain more than one parameter. For example, an order may belong to a specific user.
Multiple Route Parameters
const parts = req.url.split("/");
if (
parts[1] === "users" &&
parts[3] === "orders" &&
parts.length === 5
) {
const userId = parts[2];
const orderId = parts[4];
res.end(`User: ${userId}, Order: ${orderId}`);
}| URL | User ID | Order ID |
|---|---|---|
| /users/10/orders/500 | 10 | 500 |
| /users/25/orders/1200 | 25 | 1200 |
Returning JSON Responses
Instead of plain text, APIs commonly return JSON containing the extracted route parameters.
JSON Response with Route Parameters
const parts = req.url.split("/");
if (parts[1] === "products" && parts.length === 3) {
const productId = parts[2];
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
productId: productId,
message: "Product found"
}));
}Using the URL Class
The built-in URL class provides a cleaner way to access the pathname without query parameters. This is especially useful when URLs include search parameters.
Parsing the URL with the URL Class
const url = new URL(req.url, "http://localhost:3000");
const parts = url.pathname.split("/");
console.log(parts);Tip
Route Parameters vs Query Parameters
| Feature | Route Parameters | Query Parameters |
|---|---|---|
| Purpose | Identify a specific resource. | Filter or modify a request. |
| Example | /users/101 | /users?id=101 |
| Location | Part of the URL path. | After the ? character. |
| Common Usage | Resource identification. | Searching, sorting, filtering, pagination. |
Complete Example
Complete Server with Route Parameters
const http = require("http");
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost:3000");
const parts = url.pathname.split("/");
if (parts[1] === "users" && parts.length === 3) {
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
id: parts[2],
name: "Sample User"
}));
}
else {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end("Route Not Found");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});Best Practices đĄ
- Use the URL class to parse request URLs.
- Validate route parameters before using them.
- Return 404 for invalid routes.
- Return JSON responses for API endpoints.
- Keep route parsing logic organized and reusable.
Best Practice
Common Mistakes â ī¸
- Assuming route parameters always exist without checking the URL structure.
- Ignoring query parameters when matching routes.
- Using incorrect array indexes after splitting the URL.
- Not validating parameter values before processing them.
- Returning a successful response for invalid routes.