Bird
Raised Fist0
Node.jsframework~30 mins

Building URLs programmatically in Node.js - Mini Project: Build & Apply

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
Building URLs programmatically
📖 Scenario: You are creating a small Node.js utility to build URLs dynamically for a web application. This utility will help combine a base URL with query parameters to create full URLs for API requests or page navigation.
🎯 Goal: Build a Node.js script that programmatically constructs a URL string by combining a base URL with query parameters stored in an object.
📋 What You'll Learn
Create a variable called baseUrl with the exact string "https://example.com/search".
Create an object called queryParams with these exact key-value pairs: term: "nodejs", page: "2", sort: "asc".
Create a variable called queryString that converts queryParams into a URL query string.
Create a variable called fullUrl that combines baseUrl and queryString with a question mark "?" separator.
💡 Why This Matters
🌍 Real World
Building URLs dynamically is common in web development for API calls, navigation, and linking with parameters.
💼 Career
Understanding how to programmatically build URLs helps in backend and frontend roles, especially when working with REST APIs or routing.
Progress0 / 4 steps
1
Set up the base URL
Create a variable called baseUrl and assign it the string "https://example.com/search".
Node.js
Hint

Use const baseUrl = "https://example.com/search"; to create the base URL variable.

2
Create the query parameters object
Create an object called queryParams with these exact key-value pairs: term: "nodejs", page: "2", sort: "asc".
Node.js
Hint

Use const queryParams = { term: "nodejs", page: "2", sort: "asc" }; to create the query parameters object.

3
Convert query parameters to a query string
Create a variable called queryString that converts the queryParams object into a URL query string using new URLSearchParams(queryParams).toString().
Node.js
Hint

Use new URLSearchParams(queryParams).toString() to create the query string.

4
Combine base URL and query string
Create a variable called fullUrl that combines baseUrl and queryString with a question mark "?" separator to form the complete URL.
Node.js
Hint

Use template literals to combine baseUrl and queryString with a "?" in between.

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