Building URLs programmatically helps you create web addresses easily without mistakes. It saves time and avoids errors when combining parts like domain, path, and query.
0
0
Building URLs programmatically in Node.js
Introduction
When you need to create links dynamically based on user input or data.
When you want to add query parameters to a URL safely.
When you build API requests with different endpoints and parameters.
When you want to avoid manual string concatenation that can cause errors.
When you need to encode special characters in URLs automatically.
Syntax
Node.js
const url = new URL(input, base); url.pathname = '/path'; url.searchParams.append('key', 'value'); const fullUrl = url.toString();
input can be a full URL or a path string.
base is the base URL used if input is a relative path.
Examples
Creates a URL with a path and a query parameter.
Node.js
const url = new URL('https://example.com'); url.pathname = '/products'; url.searchParams.append('id', '123'); console.log(url.toString());
Builds a full URL from a relative path and base URL, then sets a query parameter.
Node.js
const url = new URL('/search', 'https://example.com'); url.searchParams.set('q', 'nodejs'); console.log(url.href);
Automatically encodes spaces and special characters in query parameters.
Node.js
const url = new URL('https://example.com'); url.searchParams.append('name', 'John Doe'); console.log(url.toString());
Sample Program
This function builds a product URL with an ID and optional category. It uses the URL class to add query parameters safely.
Node.js
import { URL } from 'url'; function buildProductUrl(productId, category) { const baseUrl = 'https://shop.example.com'; const url = new URL('/products', baseUrl); url.searchParams.append('id', productId); if (category) { url.searchParams.append('category', category); } return url.toString(); } console.log(buildProductUrl('456', 'books')); console.log(buildProductUrl('789'));
OutputSuccess
Important Notes
The URL class automatically encodes special characters in paths and query parameters.
Use searchParams.append() to add multiple values for the same key.
Always provide a base URL when using relative paths to avoid errors.
Summary
Use the URL class to build URLs safely and easily.
It helps avoid manual string errors and encodes special characters automatically.
Use searchParams to add or modify query parameters.