0
0
NodejsHow-ToBeginner · 3 min read

How to Use URL Class in Node.js: Syntax and Examples

In Node.js, you can use the URL class from the built-in url module to parse and manipulate URLs easily. Create a new URL object with new URL(input[, base]), then access or change parts like hostname, pathname, or searchParams. This helps handle URLs in a structured way.
📐

Syntax

The URL class is used by importing it from the url module. You create a new URL object by passing a URL string. You can then access or modify its parts like protocol, hostname, pathname, and searchParams.

  • new URL(input[, base]): Creates a URL object from input. If input is relative, provide a base URL.
  • url.protocol: The protocol part (e.g., https:).
  • url.hostname: The domain name or IP.
  • url.pathname: The path after the domain.
  • url.searchParams: An object to get or set query parameters.
javascript
import { URL } from 'url';

const myUrl = new URL('https://example.com/path?name=value');

console.log(myUrl.protocol);    // 'https:'
console.log(myUrl.hostname);    // 'example.com'
console.log(myUrl.pathname);    // '/path'
console.log(myUrl.searchParams.get('name')); // 'value'
Output
https: example.com /path value
💻

Example

This example shows how to create a URL object, read its parts, add a query parameter, and convert it back to a string.

javascript
import { URL } from 'url';

const url = new URL('https://nodejs.org/api/url.html');

// Read parts
console.log('Protocol:', url.protocol);
console.log('Host:', url.host);
console.log('Pathname:', url.pathname);

// Add a query parameter
url.searchParams.append('version', '18');

// Output the full URL string
console.log('Full URL:', url.toString());
Output
Protocol: https: Host: nodejs.org Pathname: /api/url.html Full URL: https://nodejs.org/api/url.html?version=18
⚠️

Common Pitfalls

Common mistakes include:

  • Not importing URL from the url module in Node.js.
  • Passing a relative URL without a base, which throws an error.
  • Trying to modify href directly instead of using properties like pathname or searchParams.

Always provide a base URL if your input is relative.

javascript
import { URL } from 'url';

// Wrong: relative URL without base
try {
  const badUrl = new URL('/path');
} catch (err) {
  console.log('Error:', err.message);
}

// Right: provide base URL
const goodUrl = new URL('/path', 'https://example.com');
console.log(goodUrl.href);
Output
Error: Invalid URL https://example.com/path
📊

Quick Reference

Property/MethodDescriptionExample
new URL(input[, base])Creates a URL object from a stringnew URL('https://site.com')
url.protocolGets or sets the protocolurl.protocol = 'http:'
url.hostnameGets or sets the domain nameconsole.log(url.hostname)
url.pathnameGets or sets the pathurl.pathname = '/newpath'
url.searchParamsAccess query parametersurl.searchParams.append('key', 'value')
url.toString()Returns the full URL stringconsole.log(url.toString())

Key Takeaways

Import the URL class from the 'url' module to work with URLs in Node.js.
Create a URL object with 'new URL(input[, base])' to parse and manipulate URLs.
Always provide a base URL when parsing relative URLs to avoid errors.
Use 'searchParams' to easily read and modify query parameters.
Modify URL parts via properties like 'protocol', 'hostname', and 'pathname' instead of changing the full string.