The url Module: Parsing URLs and Query Parameters
Objectives
By the end of this lesson, you should be able to:
- Parse a URL string into its parts with
new URL() - Read query parameters with
searchParams.get()and.has() - Modify a URL’s query parameters and get the result back as a string
💡 Why this matters: A route handler frequently needs whatever comes after the
?in a URL, a search term, a page number, a filter. Manually splitting a URL string on?and&is error-prone,urldoes it correctly.
⚠️ A note on verification: every snippet and output in this lesson was actually run with Node.js.
Parsing a URL
const { URL } = require('url');
const myUrl = new URL('https://example.com/search?q=nodejs&sort=recent&sort=popular');
console.log('hostname:', myUrl.hostname);
console.log('pathname:', myUrl.pathname);
console.log('search:', myUrl.search);
hostname: example.com
pathname: /search
search: ?q=nodejs&sort=recent&sort=popular
new URL(urlString) parses a full URL into an object with named properties, hostname (the domain), pathname (the path, without the query string), and search (the raw query string, including the leading ?).
Reading Query Parameters
console.log('q param:', myUrl.searchParams.get('q'));
console.log('has sort:', myUrl.searchParams.has('sort'));
q param: nodejs
has sort: true
myUrl.searchParams is a URLSearchParams object, .get(name) returns the first value for a given parameter name, .has(name) checks whether a parameter is present at all. This is far more reliable than manually splitting the query string on & and =, URLSearchParams correctly handles edge cases like repeated parameter names and URL-encoded characters.
Modifying a URL
myUrl.searchParams.set('page', '2');
console.log('after set:', myUrl.toString());
after set: https://example.com/search?q=nodejs&sort=recent&sort=popular&page=2
.set(name, value) adds a new query parameter (or replaces every existing value for that name if it already exists), and .toString() renders the full URL back out, including every parameter, as a single string.
Try It
- Parse the URL
'https://shop.example.com/products?category=shoes&inStock=true', and log itshostnameandpathnameseparately. - Read the
categoryandinStockquery parameters with.get(). - Use
.set()to changecategoryto'boots', and print the resulting full URL. - Parse a URL with no query string at all, and confirm
.searchis an empty string and.searchParams.has('anything')returnsfalse.
Recap
new URL(urlString)parses a URL intohostname,pathname,search, and more.searchParams.get(name)/.has(name)read query parameters reliably, without manual string splitting.searchParams.set(name, value)and.toString()modify a URL’s query string and render the result back as a string.
Next lesson: stream and readline, handling data as it arrives.