Node.js URL Module
The URL module provides tools for parsing and working with URLs. Node.js 10+ includes the WHATWG URL API (the same standard used in browsers), so URL is available as a global in modern Node.js without importing. The url module import is only needed if you are using the older url.parse() API, which is now deprecated.
Importing
import { URL } from 'node:url';
// In modern Node.js, URL is also available globally without importing
URL structure
A URL has several named components:
scheme://host:port/path?query
http://www.example.com:8000/software/index.html?id=10&status=active
Parsing a URL
Use the URL() constructor to create a URL object. You can then read each component as a property.
const newUrl = new URL('https://www.example.com:8000/software/index.html?q=abc');
console.log(newUrl.href); // 'https://www.example.com:8000/software/index.html?q=abc'
console.log(newUrl.host); // 'www.example.com:8000'
console.log(newUrl.hostname); // 'www.example.com' (no port)
console.log(newUrl.port); // '8000'
console.log(newUrl.pathname); // '/software/index.html'
console.log(newUrl.search); // '?q=abc'
Working with query parameters
The searchParams property is a URLSearchParams object that lets you read and modify query parameters.
const myUrl = new URL('https://example.com/search?q=nodejs&page=1');
// Read params
console.log(myUrl.searchParams.get('q')); // 'nodejs'
console.log(myUrl.searchParams.get('page')); // '1'
// Add a param
myUrl.searchParams.append('limit', '10');
// Iterate over all params
for (const [key, value] of myUrl.searchParams) {
console.log(`${key}: ${value}`);
}
// q: nodejs
// page: 1
// limit: 10
Deprecated API
The older url.parse() function is deprecated. Use new URL() instead.
// Old (deprecated)
const url = require('url');
const parsed = url.parse('https://example.com/path?q=1');
// New (recommended)
const parsed = new URL('https://example.com/path?q=1');
What to read next
- HTTP Server : handling request URLs in a Node.js server
- Core Modules : overview of all built-in modules