Node.js URL Module

What is the URL Module?

The Node.js URL module provides methods and properties to handle URL strings. It allows you to:

  1. Parse URLs into structured objects.
  2. Access or modify different parts of a URL (hostname, pathname, query parameters, etc.).
  3. Format URLs into strings for easy usage.

The URL module follows the WHATWG URL Standard (used in modern web browsers) but also supports legacy methods for backward compatibility.

Importing the URL Module

The URL module is a built-in module, so you can start using it right away by importing it:

const url = require('url');

For modern applications, you should use the WHATWG URL API, which provides a cleaner and more intuitive way to work with URLs.

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

Parsing a URL

The most common task is parsing a URL to break it into its components.

Example: Parsing a URL

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

// Parse the URL
const myUrl = new URL('https://www.example.com:8080/path/name?query=test&lang=en#section1');

console.log('Full URL:', myUrl.href);
console.log('Protocol:', myUrl.protocol);
console.log('Hostname:', myUrl.hostname);
console.log('Port:', myUrl.port);
console.log('Pathname:', myUrl.pathname);
console.log('Search Params:', myUrl.search);
console.log('Hash:', myUrl.hash);

Output:

Full URL: https://www.example.com:8080/path/name?query=test&lang=en#section1  
Protocol: https:
Hostname: www.example.com
Port: 8080
Pathname: /path/name
Search Params: ?query=test&lang=en
Hash: #section1

Accessing Query Parameters

The URL module makes it easy to access and manipulate query parameters using the searchParams property.

Example: Working with Query Parameters

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

// Parse the URL
const myUrl = new URL('https://www.example.com/search?query=nodejs&category=programming');

// Access query parameters
console.log('Query Parameter "query":', myUrl.searchParams.get('query')); // nodejs
console.log('Query Parameter "category":', myUrl.searchParams.get('category')); // programming

// Add a new query parameter
myUrl.searchParams.append('page', '2');
console.log('Updated URL:', myUrl.href);

// Delete a query parameter
myUrl.searchParams.delete('category');
console.log('After Deletion:', myUrl.href);

Formatting a URL

If you modify a URL object, you can convert it back into a string using the toString() or toJSON() methods.

Example: Formatting a URL

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

// Create and modify a URL
const myUrl = new URL('https://example.com');
myUrl.pathname = '/new/path';
myUrl.searchParams.set('query', 'nodejs');

console.log('Formatted URL:', myUrl.toString());

Output:

Formatted URL: https://example.com/new/path?query=nodejs

Handling Relative URLs

You can resolve relative URLs using the URL constructor.

Example: Resolving Relative URLs

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

const baseUrl = new URL('https://www.example.com/path/');
const relativeUrl = new URL('subpage', baseUrl);

console.log('Resolved URL:', relativeUrl.href);

Output:

Resolved URL: https://www.example.com/path/subpage

Legacy URL Parsing (Deprecated)

For backward compatibility, Node.js provides a legacy API using url.parse() and url.format(). However, you should use the modern WHATWG URL API for new projects.

Example: Legacy Parsing

const url = require('url');

const parsedUrl = url.parse('https://example.com:8080/path?query=test', true);

console.log('Host:', parsedUrl.host); // example.com:8080
console.log('Pathname:', parsedUrl.pathname); // /path
console.log('Query:', parsedUrl.query); // { query: 'test' }

Common Use Cases

  1. Building Dynamic URLs: Construct URLs for API requests or redirects.
  2. Extracting Information: Extract hostname, path, or query parameters from user requests.
  3. Updating Query Parameters: Add or remove query parameters in URLs dynamically.
  4. Resolving Relative URLs: Handle navigation or API requests based on relative paths.

Real-World Example

Here’s how you can use the URL module to dynamically handle routing in a server:

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

// Create a simple server
const server = http.createServer((req, res) => {
const parsedUrl = new URL(req.url, `http://${req.headers.host}`);

if (parsedUrl.pathname === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the Home Page');
} else if (parsedUrl.pathname === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Page');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Page Not Found');
}
});

// Start the server
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

Leave a Comment

BoxofLearn