Node.js URL Module
Servers receive URLs, clients build them, and configuration files are full of them. Parsing a URL by hand with split('?') and split('&') goes wrong as soon as a value contains an encoded character. Node.js ships the same WHATWG URL API that browsers use, so the code you write here works in the front end too.
URL and URLSearchParams are globals — no import needed. The node:url module adds a few Node-specific helpers, such as converting between file paths and file: URLs.
Parsing a URL
const url = new URL('https://ana:secret@shop.example.com:8080/products/42?color=red&size=M#reviews');
console.log(url.protocol);
console.log(url.username, url.password);
console.log(url.hostname);
console.log(url.port);
console.log(url.host);
console.log(url.origin);
console.log(url.pathname);
console.log(url.search);
console.log(url.hash);https:
ana secret
shop.example.com
8080
shop.example.com:8080
https://shop.example.com:8080
/products/42
?color=red&size=M
#reviews
| Property | Part of the URL |
|---|---|
protocol |
scheme including the colon, e.g. https: |
hostname / port / host |
name, port, and both together |
origin |
protocol + host (read-only) |
pathname |
the path, starting with / |
search / searchParams |
query string as text / as an object |
hash |
fragment, starting with # |
href |
the complete URL |
An invalid URL throws a TypeError. Use URL.canParse() (Node 19.9+) to check first, or wrap new URL() in try…catch.
Relative URLs
The second argument is a base. This is exactly what an HTTP server needs: req.url contains only the path and query, such as /search?q=node, so you combine it with a base to parse it.
console.log(new URL('/search?q=node', 'http://localhost').searchParams.get('q'));
console.log(new URL('../img/logo.png', 'https://site.dev/blog/posts/').href);
console.log(new URL('//cdn.dev/app.js', 'https://site.dev').href);
console.log(URL.canParse('not a url'));
try {
new URL('not a url');
} catch (err) {
console.log(err.name + ':', err.code);
}node
https://site.dev/blog/img/logo.png
https://cdn.dev/app.js
false
TypeError: ERR_INVALID_URL
Query strings with URLSearchParams
searchParams is a live view of the query string: change it and url.href updates. It handles encoding for you — spaces, &, = and non-ASCII characters are escaped automatically.
const url = new URL('https://api.example.com/items?page=2&tag=js&tag=node');
console.log(url.searchParams.get('page'));
console.log(url.searchParams.getAll('tag'));
console.log(url.searchParams.has('sort'));
url.searchParams.set('page', '3');
url.searchParams.append('q', 'fish & chips');
url.searchParams.delete('tag');
console.log(url.href);
const params = new URLSearchParams({ city: 'Hà Nội', limit: 10 });
console.log(params.toString());
console.log(Object.fromEntries(new URLSearchParams('a=1&b=2&b=3')));2
[ 'js', 'node' ]
false
https://api.example.com/items?page=3&q=fish+%26+chips
city=H%C3%A0+N%E1%BB%99i&limit=10
{ a: '1', b: '3' }
All values are strings — convert them with Number() yourself. Note that Object.fromEntries() keeps only the last value of a repeated key.
Tip: Never build query strings with template literals like
`?q=${text}`. A user typinga&admin=truewould inject an extra parameter. UseURLSearchParamsinstead.
File URLs
ES modules identify files by URL (import.meta.url is a file: URL). node:url converts in both directions and handles spaces and special characters correctly:
import { fileURLToPath, pathToFileURL } from 'node:url';
const href = 'file:///home/ana/my%20project/app.js';
console.log(fileURLToPath(href, { windows: false }));
console.log(pathToFileURL('/home/ana/my project/app.js', { windows: false }).href);
console.log(new URL('./data.json', href).pathname);/home/ana/my project/app.js
file:///home/ana/my%20project/app.js
/home/ana/my%20project/data.json
new URL('./data.json', import.meta.url) is a common way to point at a file next to your module — fs functions accept URL objects directly.
The legacy API
Older code uses url.parse() and the querystring module. They still work but are deprecated or legacy, accept malformed input in surprising ways, and have known security pitfalls. Use new URL() and URLSearchParams in new code.
| Legacy | Modern replacement |
|---|---|
url.parse(str) |
new URL(str, base) |
url.format(obj) |
url.href / url.toString() |
querystring.parse(str) |
new URLSearchParams(str) |
querystring.stringify(obj) |
new URLSearchParams(obj).toString() |
Test yourself
Inside an HTTP server, req.url is /users?id=7. How do you parse it with URL?
new URL(req.url)new URL(req.url, 'http://localhost')URL.parse(req.url).idnew URLSearchParams(req.url).id
What type does url.searchParams.get('page') return for ?page=2?
- number
2 - string
'2' - array
['2'] undefined
Which property gives https://shop.dev:8080 for https://shop.dev:8080/a?b=1?
hosthreforiginhostname