Skip to content
tezvyn:

URLSearchParams: Safely Build and Parse URL Queries

Source: developer.mozilla.orgMediumHow cards are made

URLSearchParams: Safely Build and Parse URL Queries

Think of URLSearchParams as a structured object for a URL's query string, saving you from messy string manipulation. Use it to read incoming parameters or build a query for a fetch request. The footgun: get() only returns the first value for a key.

Why it exists

Before this API, developers manually parsed query strings with string splits and regular expressions. This was tedious, error-prone, and often forgot to handle URL encoding and decoding correctly, leading to bugs and security issues. URLSearchParams provides a standardized, safe, and convenient way to handle this common task.

The mental model

Treat URLSearchParams as a helper object that turns a messy query string like ?q=search&page=2 into a structured, map-like object you can safely read from and write to. It handles all the tricky encoding and formatting details for you. Instead of building a string, you call methods like set('page', 3), and it takes care of the rest.

How it works

You create a URLSearchParams object from a query string (e.g., new URLSearchParams("q=api&topic=js")). It provides methods to manipulate the parameters. get(key) retrieves the first value for a key. getAll(key) retrieves all values as an array, which is critical for keys that can appear multiple times. set(key, value) replaces any existing values for that key, while append(key, value) adds a new value, allowing for duplicate keys. has(key) checks for existence. Finally, toString() converts the object back into a URL-safe query string.

When to use it

Use it anytime you need to interact with URL query parameters. Three key places are: first, reading initial state from the URL when a page loads (e.g., search terms, filters); second, constructing URLs for API calls with fetch; third, updating the URL in the browser's address bar without a full page reload, in combination with the History API.

When not to use it

It is specifically for the ?key=value part of a URL. Do not use it to parse the path, domain, or hash fragment. It is not a general-purpose key-value store; while it acts like a Map, it has specific behaviors tailored to URL query strings, like the distinction between set and append.

One canonical example

To build a search URL for an API, you can do this:

const params = new URLSearchParams();
params.append('q', 'TypeScript');
params.append('sort', 'stars');
const url = https://api.example.com/search?${params.toString()};

This correctly generates the string q=TypeScript&sort=stars and appends it to the base URL, handling all necessary encoding.

Interview question

What is the primary benefit URLSearchParams offers to web developers?

  • a.It provides a standardized and safe way to handle URL query strings, including encoding and decoding.Correct
  • b.It automatically validates the structure of all URL components, not just query parameters.
  • c.It allows for the secure storage of user authentication tokens within the URL.
  • d.It enables client-side routing and navigation without requiring full page reloads.
Why?

The card states URLSearchParams provides a "standardized, safe, and convenient way to handle this common task" of parsing and building query strings, and that "It handles all the tricky encoding and formatting details for you." Option C is incorrect because storing sensitive data like authentication tokens directly in the URL is generally insecure, even with URLSearchParams. While URLSearchParams can be used with the History API for client-side routing (Option D), it does not enable routing itself; it only manages the query part of the URL. Option B is incorrect as it explicitly states not to use it for other URL components like path or hash fragment.

Just read this? Test yourself on what you have been reading.

Read the original → developer.mozilla.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles