Bird
Raised Fist0
Node.jsframework~10 mins

Building URLs programmatically in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Building URLs programmatically
Start with base URL string
Create URL object
Set or update URL parts (path, query, hash)
Serialize URL object to string
Use the final URL string
This flow shows how to start with a base URL, build or update parts using the URL object, then get the final URL string.
Execution Sample
Node.js
const base = 'https://example.com';
const url = new URL(base);
url.pathname = '/search';
url.searchParams.set('q', 'nodejs');
console.log(url.toString());
This code builds a URL by starting with a base, adding a path and a query parameter, then prints the full URL.
Execution Table
StepActionURL Object StateOutput
1Create URL object with base 'https://example.com'href: 'https://example.com/'
2Set pathname to '/search'href: 'https://example.com/search'
3Add query parameter 'q=nodejs'href: 'https://example.com/search?q=nodejs'
4Call toString() to get full URL stringhref unchanged'https://example.com/search?q=nodejs'
5End of code executionfinal URL string ready
💡 All URL parts set; final URL string produced for use.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
base'https://example.com''https://example.com''https://example.com''https://example.com''https://example.com'
url.hrefundefined'https://example.com/''https://example.com/search''https://example.com/search?q=nodejs''https://example.com/search?q=nodejs'
url.pathnameundefined'/''/search''/search''/search'
url.searchParamsundefinedemptyemptycontains 'q=nodejs'contains 'q=nodejs'
Key Moments - 3 Insights
Why does url.href end with a slash after creating the URL object with base 'https://example.com'?
When creating a URL object from a base without a path, Node.js adds a trailing slash '/' as the default pathname. See execution_table step 1 and variable_tracker url.href after step 1.
How does setting url.pathname affect the URL string?
Setting url.pathname replaces the path part of the URL. This changes url.href to include the new path, as shown in execution_table step 2.
What happens when we add a query parameter using url.searchParams.set()?
Adding a query parameter updates the search part of the URL, reflected in url.href with '?q=nodejs' appended, as in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 2. What is the value of url.href?
A'https://example.com/search'
B'https://example.com/'
C'https://example.com/search?q=nodejs'
D'https://example.com'
💡 Hint
Check the 'URL Object State' column for step 2 in the execution_table.
At which step does the URL gain a query parameter?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for when 'q=nodejs' appears in the URL Object State in execution_table.
If we changed url.pathname to '/about', what would url.href be after step 2?
A'https://example.com/about'
B'https://example.com/search'
C'https://example.com/'
D'https://example.com/about?q=nodejs'
💡 Hint
Refer to how pathname changes url.href in execution_table step 2 and variable_tracker.
Concept Snapshot
Building URLs programmatically in Node.js:
- Use new URL(base) to create a URL object
- Modify parts like pathname and searchParams
- Use url.toString() to get the full URL string
- URL object auto-formats and encodes parts
- Great for safe, dynamic URL construction
Full Transcript
This lesson shows how to build URLs step-by-step in Node.js using the URL class. We start with a base URL string, create a URL object, then update its pathname and query parameters. Each change updates the URL object's href property. Finally, we convert the URL object back to a string for use. This method avoids manual string concatenation and ensures URLs are valid and properly encoded.

Practice

(1/5)
1. What is the main benefit of using the URL class in Node.js when building URLs programmatically?
easy
A. It automatically encodes special characters and manages URL parts safely.
B. It allows direct string concatenation without any checks.
C. It disables query parameters to simplify URLs.
D. It only works with HTTP URLs, ignoring others.

Solution

  1. Step 1: Understand the purpose of the URL class

    The URL class helps build URLs by handling encoding and structure automatically.
  2. 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.
  3. Final Answer:

    It automatically encodes special characters and manages URL parts safely. -> Option A
  4. Quick 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
A. const url = new URL('https://example.com');
B. const url = new URL('example.com');
C. const url = URL('https://example.com');
D. const url = new URL(); url.href = 'https://example.com';

Solution

  1. Step 1: Check URL constructor usage

    The URL constructor requires a full URL string including protocol, e.g., 'https://example.com'.
  2. 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.
  3. Final Answer:

    const url = new URL('https://example.com'); -> Option A
  4. Quick 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
A. https://example.com/path?page=2&q=nodejs
B. https://example.com/path?q=nodejs&page=2
C. https://example.com/path?q=nodejs&page=2&
D. https://example.com/path

Solution

  1. Step 1: Understand searchParams.append behavior

    Appending 'q=nodejs' then 'page=2' adds these query parameters in order.
  2. Step 2: Check URL string output

    Calling toString() returns full URL with query string '?q=nodejs&page=2' appended to path.
  3. Final Answer:

    https://example.com/path?q=nodejs&page=2 -> Option B
  4. Quick 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
A. The 'href' property is read-only and cannot be logged.
B. URL constructor is missing the protocol.
C. You cannot modify searchParams after URL creation.
D. The method 'add' does not exist on searchParams; should use 'append'.

Solution

  1. Step 1: Check searchParams methods

    The correct method to add a query parameter is 'append', not 'add'.
  2. Step 2: Validate other code parts

    URL has protocol, searchParams can be modified, and href can be logged. Only method name is wrong.
  3. Final Answer:

    The method 'add' does not exist on searchParams; should use 'append'. -> Option D
  4. Quick 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
A. 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());
B. const url = 'https://api.example.com/search?query=node.js tips&sort=recent'; console.log(url);
C. 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);
D. 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);

Solution

  1. Step 1: Understand URL and searchParams usage

    Use new URL with base URL, then append parameters with searchParams.append to add multiple values safely.
  2. 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.
  3. Final Answer:

    Option C code correctly builds URL with proper encoding and appends parameters. -> Option C
  4. Quick 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