0
0
NodejsHow-ToBeginner · 3 min read

How to Parse URL in Node.js Using the URL Module

In Node.js, you can parse a URL using the built-in URL class from the url module. Create a new URL object with the URL string, then access parts like hostname, pathname, and searchParams easily.
📐

Syntax

Use the URL class from the url module to parse URLs. You create a new URL object by passing the URL string. Then you can access properties like protocol, hostname, pathname, and searchParams.

  • new URL(input[, base]): Creates a URL object from input string. base is optional for relative URLs.
  • 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 work with query parameters.
javascript
const { URL } = require('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 parse a full URL string and extract its parts like protocol, host, path, and query parameters using the URL class.

javascript
const { URL } = require('url');

const urlString = 'https://www.example.com:8080/products?id=123&category=books';
const parsedUrl = new URL(urlString);

console.log('Protocol:', parsedUrl.protocol);       // 'https:'
console.log('Host:', parsedUrl.host);               // 'www.example.com:8080'
console.log('Hostname:', parsedUrl.hostname);       // 'www.example.com'
console.log('Port:', parsedUrl.port);               // '8080'
console.log('Pathname:', parsedUrl.pathname);       // '/products'
console.log('Search Params:', parsedUrl.searchParams.toString()); // 'id=123&category=books'
console.log('Get id:', parsedUrl.searchParams.get('id'));        // '123'
console.log('Get category:', parsedUrl.searchParams.get('category')); // 'books'
Output
Protocol: https: Host: www.example.com:8080 Hostname: www.example.com Port: 8080 Pathname: /products Search Params: id=123&category=books Get id: 123 Get category: books
⚠️

Common Pitfalls

Common mistakes when parsing URLs in Node.js include:

  • Using url.parse() from older Node.js versions instead of the modern URL class.
  • Not providing a base URL when parsing relative URLs, which causes errors.
  • Trying to access query parameters as a string instead of using searchParams methods.

Always use the URL class for modern, reliable parsing.

javascript
const { URL } = require('url');

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

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

Quick Reference

Property/MethodDescriptionExample
protocolThe URL protocol scheme'https:'
hostnameDomain name or IP address'example.com'
portPort number if specified'8080'
pathnamePath after the domain'/products'
searchParams.get(name)Get query parameter valuesearchParams.get('id') // '123'
searchParams.toString()Get full query string'id=123&category=books'
hrefFull URL stringparsedUrl.href

Key Takeaways

Use the built-in URL class from the url module to parse URLs in Node.js.
Create a new URL object with the URL string to access parts like protocol, hostname, and query parameters.
Always provide a base URL when parsing relative URLs to avoid errors.
Use searchParams methods to work with query parameters easily.
Avoid legacy url.parse() method; prefer the modern URL class for better reliability.