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.
Building URLs programmatically in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
Node.js
const url = new URL('https://example.com'); url.pathname = '/products'; url.searchParams.append('id', '123'); console.log(url.toString());
Node.js
const url = new URL('/search', 'https://example.com'); url.searchParams.set('q', 'nodejs'); console.log(url.href);
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'));
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.
Practice
1. What is the main benefit of using the
URL class in Node.js when building URLs programmatically?easy
Solution
Step 1: Understand the purpose of the URL class
The URL class helps build URLs by handling encoding and structure automatically.Step 2: Compare options with URL class features
Only It automatically encodes special characters and manages URL parts safely. correctly describes automatic encoding and safe URL part management.Final Answer:
It automatically encodes special characters and manages URL parts safely. -> Option AQuick Check:
URL class = safe URL building [OK]
Hint: Remember: URL class handles encoding and structure safely [OK]
Common Mistakes:
- Thinking URL class just concatenates strings
- Assuming URL class disables query parameters
- Believing URL class only supports HTTP URLs
2. Which of the following is the correct way to create a new URL object for 'https://example.com' in Node.js?
easy
Solution
Step 1: Check URL constructor usage
The URL constructor requires a full URL string including protocol, e.g., 'https://example.com'.Step 2: Validate each option
const url = new URL('https://example.com'); correctly uses new URL with full URL string. const url = new URL('example.com'); misses protocol, C misses 'new', D uses empty constructor which is invalid.Final Answer:
const url = new URL('https://example.com'); -> Option AQuick Check:
Use new URL('full-url') syntax [OK]
Hint: Always include protocol and use 'new' with URL [OK]
Common Mistakes:
- Omitting 'new' keyword
- Passing URL without protocol
- Trying to create URL without constructor
3. What will be the output of this Node.js code?
const url = new URL('https://example.com/path');
url.searchParams.append('q', 'nodejs');
url.searchParams.append('page', '2');
console.log(url.toString());medium
Solution
Step 1: Understand searchParams.append behavior
Appending 'q=nodejs' then 'page=2' adds these query parameters in order.Step 2: Check URL string output
Calling toString() returns full URL with query string '?q=nodejs&page=2' appended to path.Final Answer:
https://example.com/path?q=nodejs&page=2 -> Option BQuick Check:
Appended params appear in order in URL string [OK]
Hint: searchParams.append adds parameters in order [OK]
Common Mistakes:
- Assuming parameters order is reversed
- Expecting trailing '&' at end
- Ignoring appended query parameters
4. Identify the error in this code snippet that tries to add a query parameter:
const url = new URL('https://example.com');
url.searchParams.add('key', 'value');
console.log(url.href);medium
Solution
Step 1: Check searchParams methods
The correct method to add a query parameter is 'append', not 'add'.Step 2: Validate other code parts
URL has protocol, searchParams can be modified, and href can be logged. Only method name is wrong.Final Answer:
The method 'add' does not exist on searchParams; should use 'append'. -> Option DQuick Check:
Use searchParams.append, not add [OK]
Hint: Use 'append' to add query parameters, not 'add' [OK]
Common Mistakes:
- Using 'add' instead of 'append'
- Thinking href is not accessible
- Believing searchParams is immutable
5. You want to build a URL with base 'https://api.example.com/search' and add parameters 'query' with value 'node.js tips' and 'sort' with value 'recent'. Which code correctly builds this URL with proper encoding?
hard
Solution
Step 1: Understand URL and searchParams usage
Use new URL with base URL, then append parameters with searchParams.append to add multiple values safely.Step 2: Check encoding and method correctness
const url = new URL('https://api.example.com/search'); url.searchParams.append('query', 'node.js tips'); url.searchParams.append('sort', 'recent'); console.log(url.href); uses append correctly and prints href, which includes proper encoding of spaces as '%20'. const url = new URL('https://api.example.com/search'); url.searchParams.set('query', 'node.js tips'); url.searchParams.set('sort', 'recent'); console.log(url.toString()); uses set which replaces values but also works; however, question asks for correct code with proper encoding and append is more common for adding multiple params. const url = 'https://api.example.com/search?query=node.js tips&sort=recent'; console.log(url); is manual string and misses encoding. const url = new URL('https://api.example.com/search'); url.searchParams.add('query', 'node.js tips'); url.searchParams.add('sort', 'recent'); console.log(url.href); uses non-existent 'add' method.Final Answer:
Option C code correctly builds URL with proper encoding and appends parameters. -> Option CQuick Check:
Use URL + searchParams.append for safe, encoded URLs [OK]
Hint: Use URL and searchParams.append for safe, encoded query parameters [OK]
Common Mistakes:
- Manually concatenating query strings without encoding
- Using non-existent 'add' method
- Ignoring encoding of spaces and special characters
