Course contentsShow
← Node.js
Lesson 530 of 1,9806. Networking and HTTP FundamentalsFree lesson

Query String Parsing and Encoding

Sanitize and extract complex query parameters from incoming request URIs.

Mastering Query String Data

In this lesson, you will learn how to safely extract and sanitize complex data sent via URL query parameters in your Node.js applications.

When a client sends data to your server via the URL—like example.com/search?user=dev&role=admin—that information arrives as a raw string. While we previously discussed the structure of the HTTP request line, today we focus on the "payload" embedded directly in the path.

The Anatomy of a Query

A query string starts after the ? character. It consists of key-value pairs separated by &. Because URLs only allow specific characters, data like spaces or symbols are "encoded" (for example, a space becomes %20). To make this data usable, we must perform two steps: parsing (turning the string into a usable object) and sanitization (ensuring the data doesn't contain malicious or malformed content).

Parsing and Sanitization in Practice

Using the built-in URL object allows us to handle encoding automatically. However, never trust the input blindly. If you expect a numerical ID, you must validate that the extracted string is actually a number.

const { URL } = require('url');

const rawUrl = 'https://api.myapp.com/data?id=123&filter=active%20users';
const myUrl = new URL(rawUrl);

// 1. Extraction
const rawId = myUrl.searchParams.get('id');

// 2. Sanitization (Crucial step)
const sanitizedId = parseInt(rawId, 10);

if (isNaN(sanitizedId)) {
  console.error("Invalid input received!");
} else {
  console.log(`Processing request for ID: ${sanitizedId}`);
}

Why Sanitization Matters

If you extract a string from a query parameter and pass it directly into a database query or a file system operation, you risk security vulnerabilities like injection attacks. Always treat query parameters as "tainted" input. Before using them, transform them into the expected type (like an integer) or validate them against a strict list of allowed values. By decoding and sanitizing at the entry point of your server, you ensure that your application logic only ever works with predictable, safe data.

Key Takeaway: Always decode incoming query strings using standard URL tools, then immediately validate and cast the extracted values to prevent malformed data from reaching your application logic.