Volume 2

Q135: URL, URLSearchParams and Encoding

Difficulty: SeniorFrequency: HighAnswer time: 8-12 minutes

What Interviewers Want To Evaluate

This question checks whether you understand URL parsing and safe query construction. Interviewers want URL, URLSearchParams, encoding, decoding, path vs query, repeated params, routing state, security boundaries, open redirects, and why string concatenation is risky.

Senior answers should connect URLs to frontend routing, API requests, filters, deep links, and security.

Short Interview Answer

Use the URL and URLSearchParams APIs to parse and build URLs instead of manual string concatenation. URL separates origin, path, search, hash, and other parts. URLSearchParams handles query parameters and encoding. Query strings should encode user-provided values with the platform APIs. URLs are also security-sensitive: validate redirect targets, avoid leaking sensitive data in query strings, and treat route state as untrusted input.

Detailed Interview Answer

URLs look like strings, but they have structure.

https://example.com/products?category=books&page=2#reviews

Important parts include:

protocol
host
origin
pathname
search
hash

The URL API parses these parts safely.

URL Parsing

const url = new URL("https://example.com/products?category=books&page=2");

url.origin; // "https://example.com"
url.pathname; // "/products"
url.searchParams.get("category"); // "books"

This is clearer than manually splitting strings.

Building URLs

const url = new URL("/api/products", "https://example.com");

url.searchParams.set("category", "books");
url.searchParams.set("page", "2");

fetch(url.toString());

URLSearchParams handles encoding.

Encoding

User values may contain spaces, ampersands, slashes, question marks, or non-ASCII characters.

const params = new URLSearchParams();
params.set("q", "react hooks & effects");

params.toString();

Manual concatenation can break the URL:

`/search?q=${query}`;

Use the API unless you have a very deliberate reason not to.

encodeURIComponent

For individual query values, encodeURIComponent is useful.

const url = `/search?q=${encodeURIComponent(query)}`;

But when building multiple params, URLSearchParams is usually cleaner.

Repeated Parameters

Some filters use repeated params.

const params = new URLSearchParams();

params.append("tag", "react");
params.append("tag", "typescript");

params.getAll("tag"); // ["react", "typescript"]

Decide whether your app uses repeated params, comma-separated values, or JSON-like encoding. Keep it consistent.

set vs append

set replaces existing values.

params.set("tag", "react");

append adds another value.

params.append("tag", "typescript");

This matters for multi-select filters.

Route State

URLs are great for shareable state.

Examples:

search query
filters
sort order
pagination
selected tab
date range

But URL state is user-controlled and should be parsed and validated.

Sensitive Data

Avoid putting sensitive data in URLs.

URLs can appear in:

browser history
server logs
analytics
referrer headers
screenshots
shared links

Tokens, secrets, and personal sensitive values usually do not belong in query strings.

Open Redirects

Redirect parameters can be dangerous.

/login?next=https://evil.example

If the app redirects blindly, attackers can abuse trust in your domain.

Validate redirect targets.

function isSafeInternalPath(value) {
  return value.startsWith("/") && !value.startsWith("//");
}

For robust systems, parse and validate with stricter rules.

Hash Fragment

The hash is client-side fragment data.

url.hash; // "#reviews"

It is not sent to the server in normal HTTP requests.

It is useful for anchors and some client-side state, but still should not carry secrets casually.

Common Mistakes

A common mistake is manually joining query params with & and forgetting encoding.

Another mistake is assuming query params are trusted because the app generated them.

Another mistake is losing repeated params by using only get instead of getAll.

Senior Trade-Offs

Use URL state for shareable, restorable UI state. Keep sensitive or large state elsewhere.

Use schema parsing to turn URL strings into typed app state.

Avoid custom encoding formats unless they solve a real product need.

Code or Design Example

function buildProductUrl(filters) {
  const url = new URL("/products", window.location.origin);

  if (filters.query) {
    url.searchParams.set("q", filters.query);
  }

  for (const tag of filters.tags) {
    url.searchParams.append("tag", tag);
  }

  url.searchParams.set("page", String(filters.page ?? 1));

  return `${url.pathname}${url.search}`;
}

This creates a safe internal URL path with encoded query params.

Debugging Workflow

When URL behavior is wrong:

inspect pathname, search, and hash separately
check encoding of special characters
check set vs append
check repeated params with getAll
validate route state types
check sensitive data exposure
validate redirect targets
test copied and shared links

Interview Framing

Explain URL and URLSearchParams, then discuss encoding, repeated params, URL state, and redirect safety.

Revision Notes

URLs are structured data and user-controlled input. Build and parse them with platform APIs.

Key Takeaways

Good URL handling improves shareability, routing, API correctness, and security.

Follow-Up Questions

  1. What does the URL API parse?
  2. What does URLSearchParams do?
  3. Why is manual query string concatenation risky?
  4. When should you use encodeURIComponent?
  5. What is the difference between set and append?
  6. How do repeated params work?
  7. Why is URL state useful?
  8. Why should query params be validated?
  9. Why are secrets in URLs risky?
  10. What is an open redirect?

How I Would Answer This In A Real Interview

I would say URLs are structured and should be handled with URL and URLSearchParams. Then I would cover encoding, repeated params, URL-driven UI state, sensitive data risk, and redirect validation.