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. Ifinputis relative, provide abaseURL. 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
URLfrom theurlmodule in Node.js. - Passing a relative URL without a base, which throws an error.
- Trying to modify
hrefdirectly instead of using properties likepathnameorsearchParams.
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/Method | Description | Example |
|---|---|---|
| new URL(input[, base]) | Creates a URL object from a string | new URL('https://site.com') |
| url.protocol | Gets or sets the protocol | url.protocol = 'http:' |
| url.hostname | Gets or sets the domain name | console.log(url.hostname) |
| url.pathname | Gets or sets the path | url.pathname = '/newpath' |
| url.searchParams | Access query parameters | url.searchParams.append('key', 'value') |
| url.toString() | Returns the full URL string | console.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.