Handling Route Parameters in the Node.js http Module 🔗

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

Understanding how to manually handle route parameters helps you learn how routing works internally before using higher-level frameworks.

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.

URLRoute ParameterMeaning
/users/101101User ID
/products/2525Product ID
/books/97812345678909781234567890Book ISBN

How Route Parameters Work

Client Requests /users/101
Server Receives Request
Split URL into Segments
Extract Parameter
Process Request
Send Response

Project Structure

route-parameters
server.js

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

IndexValueDescription
0""Empty string before the first slash.
1usersResource name.
2101Route 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 URLResponse
/users/1User ID: 1
/users/25User ID: 25
/users/999User 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}`);
}
URLUser IDOrder ID
/users/10/orders/50010500
/users/25/orders/1200251200

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

Using the URL class prevents query strings from interfering with route matching. For example, the pathname for /users/101?active=true is simply /users/101.

Route Parameters vs Query Parameters

FeatureRoute ParametersQuery Parameters
PurposeIdentify a specific resource.Filter or modify a request.
Example/users/101/users?id=101
LocationPart of the URL path.After the ? character.
Common UsageResource 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

As your application grows, move route matching and parameter extraction into separate helper functions or modules. This makes your server easier to maintain and prepares you for migrating to frameworks like Express.

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.

Warning

Always validate user-provided route parameters. Never assume they contain valid IDs or trusted data, as malformed or unexpected values can lead to application errors.

Learning Roadmap 🚀

HTTP Server Basics
Basic Routing
Route Parameters
Query Parameters
Request Body Parsing
REST APIs
Express.js Routing

Official Resources

>>"Dynamic URLs allow applications to serve thousands of resources using a single route pattern."

Summary

In this tutorial, you learned how to handle route parameters using the native Node.js http module by manually parsing URL paths, extracting dynamic values, supporting multiple parameters, returning JSON responses, and using the URL class for more reliable route matching. These techniques provide a solid foundation for building RESTful APIs without external routing libraries.