🔍 Handling Query Parameters in the Node.js http Module

Introduction

Query parameters are key-value pairs appended to the end of a URL after a ? character. They are commonly used to filter data, search records, sort results, paginate responses, or pass optional information to the server. In Node.js, the built-in http module provides the request URL, which can be parsed using the standard URL class to easily access query parameters.

Information

The URL class is available globally in modern versions of Node.js, so no additional package is required to parse URLs and query parameters.

What are Query Parameters?

Query parameters appear after the path in a URL. Each parameter consists of a name and a value separated by an equals sign (=). Multiple parameters are separated using an ampersand (&).

Example URLQuery Parameters
/products?category=bookscategory=books
/search?q=nodejs&page=2q=nodejs, page=2
/users?id=10&active=trueid=10, active=true

URL Structure

🌐 Complete URL
http://localhost:3000/search?q=nodejs&page=2
Protocol → http
Host → localhost:3000
Path → /search
Query → q=nodejs&page=2

Parsing the URL

The URL class parses the incoming request URL into useful components such as the pathname and query parameters.

Parsing the request URL

const http = require("http");

const server = http.createServer((req, res) => {

  const url = new URL(req.url, "http://localhost:3000");

  console.log(url.pathname);
  console.log(url.search);

  res.end("URL parsed");
});

server.listen(3000);

Accessing Query Parameters

The searchParams property provides methods to retrieve query parameter values.

Reading query parameters

const http = require("http");

const server = http.createServer((req, res) => {

  const url = new URL(req.url, "http://localhost:3000");

  const name = url.searchParams.get("name");
  const age = url.searchParams.get("age");

  res.writeHead(200, {
    "Content-Type": "application/json"
  });

  res.end(JSON.stringify({
    name,
    age
  }));

});

server.listen(3000);

Example Request

Request URL

GET /?name=Alice&age=25 HTTP/1.1
Host: localhost:3000

Example Response

JSON response

{
  "name": "Alice",
  "age": "25"
}

Handling Multiple Query Parameters

APIs often receive several query parameters simultaneously for filtering, sorting, and pagination.

Reading multiple parameters

const url = new URL(req.url, "http://localhost:3000");

const category = url.searchParams.get("category");
const sort = url.searchParams.get("sort");
const page = url.searchParams.get("page");

console.log(category);
console.log(sort);
console.log(page);

Example URL

Multiple query parameters

GET /products?category=electronics&sort=price&page=2 HTTP/1.1
Host: localhost:3000

Using Query Parameters for Search

Query parameters are frequently used to implement search functionality.

Search endpoint

const http = require("http");

const server = http.createServer((req, res) => {

  const url = new URL(req.url, "http://localhost:3000");

  if (url.pathname === "/search") {

    const keyword = url.searchParams.get("q");

    res.writeHead(200, {
      "Content-Type": "application/json"
    });

    res.end(JSON.stringify({
      search: keyword
    }));

    return;
  }

  res.writeHead(404);
  res.end();

});

server.listen(3000);

Checking for Missing Parameters

If a parameter does not exist, the get() method returns null. Your application should validate required parameters before processing the request.

Validate required query parameters

const id = url.searchParams.get("id");

if (!id) {

  res.writeHead(400, {
    "Content-Type": "application/json"
  });

  return res.end(JSON.stringify({
    error: "Missing id parameter"
  }));

}

Important

Always validate user input before using query parameter values. Query parameters originate from client requests and should never be assumed to be valid.

Retrieving All Values for the Same Parameter

A URL may contain the same query parameter multiple times. Use the getAll() method to retrieve every value.

Using getAll()

const tags = url.searchParams.getAll("tag");

console.log(tags);

// URL:
// /posts?tag=node&tag=javascript&tag=http

Expected Output

Result

[
  "node",
  "javascript",
  "http"
]

Useful searchParams Methods

MethodDescription
get(name)Returns the first matching value.
getAll(name)Returns all matching values.
has(name)Checks whether a parameter exists.
entries()Returns all parameter name-value pairs.
keys()Returns all parameter names.
values()Returns all parameter values.

Typical Request Flow

🌍 Client Sends URL
📍 Parse Request URL
🔍 Read searchParams
✅ Validate Parameters
âš™ī¸ Process Request
📨 Return JSON Response

Practical Use Cases

  • 🔎 Search functionality.
  • 📄 Pagination using page and limit.
  • 📂 Filtering records by category or status.
  • â†•ī¸ Sorting results using fields such as sort.
  • đŸŽ¯ Optional request customization.

Best Practices

  • Use the URL class instead of manually parsing URLs.
  • Validate required parameters before processing requests.
  • Return meaningful HTTP status codes for invalid input.
  • Convert numeric values using Number() or parseInt() when needed.
  • Provide sensible default values for optional parameters.

Best Practice

Query parameter values are always received as strings. Convert them to numbers, booleans, or other types when your application requires typed values.

Common Mistakes

MistakeRecommended Solution
Manually splitting the URL stringUse the built-in URL class.
Ignoring missing parametersValidate required inputs.
Treating numbers as stringsConvert values before using them.
Not handling invalid inputReturn a 400 Bad Request response.

Official Documentation

Node.js URL API Documentation and Node.js HTTP Module Documentation

Summary

Summary

Query parameters provide a flexible way to pass optional information in HTTP requests. Using the built-in URL class and its searchParams API, you can easily parse request URLs, retrieve parameter values, validate user input, support filtering and pagination, and build robust HTTP APIs using the Node.js http module.