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.
URL ClassThe 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'
URLSearchParamsThe 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
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);
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Parse incoming request URLs in HTTP servers.
Inspect req.query and req.params in Express.
Convert file:// URLs to file system paths.