Node.js URL & QueryString API - Modern WHATWG URL Parsing & Parameter Manipulation

Handling incoming query strings, extracting search parameters, and constructing valid outbound URLs are everyday tasks in web backend development. In this tutorial, you will master the WHATWG URL Standard implemented natively in Node.js.

The Modern WHATWG URL Class

The URL class is globally available in modern Node.js without requiring an import:

const targetUrl = new URL('https://veewom.com:8080/tutorials/search?category=nodejs&sort=desc&page=1#top');

console.log('Protocol:', targetUrl.protocol);  // 'https:'
console.log('Host:', targetUrl.host);          // 'veewom.com:8080'
console.log('Hostname:', targetUrl.hostname);  // 'veewom.com'
console.log('Port:', targetUrl.port);          // '8080'
console.log('Pathname:', targetUrl.pathname);  // '/tutorials/search'
console.log('Search:', targetUrl.search);      // '?category=nodejs&sort=desc&page=1'
console.log('Hash:', targetUrl.hash);          // '#top'

Working with URLSearchParams

The searchParams property returns an instance of URLSearchParams, providing intuitive methods to inspect, add, modify, and delete parameters:

const params = targetUrl.searchParams;

// 1. Get values
console.log('Category:', params.get('category')); // 'nodejs'
console.log('Has Page?', params.has('page'));     // true

// 2. Append new parameters
params.append('filter', 'beginner');

// 3. Set/Overwrite a parameter
params.set('page', '2');

// 4. Delete a parameter
params.delete('sort');

console.log('Updated URL:', targetUrl.toString());
// Output: https://veewom.com:8080/tutorials/search?category=nodejs&page=2&filter=beginner#top

Parsing Query Strings from Incoming HTTP Requests

const http = require('http');

http.createServer((req, res) => {
  // Construct absolute URL from request
  const fullUrl = new URL(req.url, `http://${req.headers.host}`);

  const term = fullUrl.searchParams.get('q');
  const limit = parseInt(fullUrl.searchParams.get('limit')) || 10;

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ searchTerm: term, limit: limit }));
}).listen(3000);

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why is the legacy url.parse() deprecated in modern Node.js?

The legacy url.parse() API has security flaws (it can be spoofed by malformed hostnames) and does not comply with international standards. Node.js now officially recommends the browser-compatible WHATWG 'URL' and 'URLSearchParams' standard global classes.

Q2. How do you loop through all query parameters with URLSearchParams?

You can use 'for (const [key, value] of myUrl.searchParams) { ... }' or 'myUrl.searchParams.forEach((val, key) => { ... })' to inspect all incoming parameters.

Q3. How do you convert a file:// URL to a local absolute path?

Use the 'fileURLToPath' function from the 'node:url' module: 'import { fileURLToPath } from "url"; const localPath = fileURLToPath(import.meta.url);'.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

HTTP Server Module

Parse incoming request URLs in HTTP servers.

Express Routing & Controllers

Inspect req.query and req.params in Express.

Path & OS Modules

Convert file:// URLs to file system paths.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!