Stop hand-building URLs: query parameters with URL and URLSearchParams
Your frontend builds, reads, and changes addresses all day, and a wrong address is a real bug. This guide follows MDN's URL and URLSearchParams docs: splitting an address into parts, resolving relative URLs, get vs getAll, the plus-sign encoding trap, empty values, and the hash fragment.

First, the boundaries of this guide. The site already has a search-feature guide about building the search box and ranking results, and a deep-linking guide about links that jump into a specific page inside an app — those two are about what links are used for. This guide is about something more basic: the address itself. A frontend builds addresses, reads addresses, and changes addresses all day: one more filter in a shared link, a filter change rewriting the address, a pasted address carrying a pile of tracking parameters. That work looks trivial, but a wrong address is a real bug. The URL interface and URLSearchParams are the browser's ready-made tools for the job, so there is no need to keep hand-rolling string concatenation.
The running example, "Mountain Lodge", is a fictional practice project: a small web tool that shows and books rooms at a mountain guesthouse, where guests filter rooms by date, guest count, and price, and the filter state lives in the address bar's query parameters, so sharing a link is just copying the whole address. Every operation, code sample, and number built around it in this article is invented to explain the technique, not a real record. All properties, methods, and behaviors of URL and URLSearchParams come from MDN's official URL and URLSearchParams documentation; sources are listed in this article's meta information and evidence record. MDN's examples, such as addresses on example.com, are the documentation's own sample domains, not real websites.
Take an address apart: URL turns a string into parts
An address looks like one long string, but it is made of parts: protocol, host, port, path, query parameters, and hash fragment, each in its own place and each with its own rules. Hand-written string concatenation fails exactly here: you have to remember that the question mark appears once, that & separates each pair, and that nothing after the # belongs to the query. Miss one symbol and the whole address bends. The URL interface works the other way around: give it a string, and it splits the address into parts, each of which can be read or changed on its own, and when you are done it puts the address back together — always valid.
It is simple to use: const url = new URL("https://example.com/rooms?city=hangzhou&guests=2#top"). Once built, url.protocol is https:, url.hostname is example.com, url.pathname is /rooms, url.search is ?city=hangzhou&guests=2, url.hash is #top, url.origin is https://example.com, and url.href is the whole address. To change the path, set url.pathname; to change the fragment, set url.hash; url.href follows automatically. MDN documents one more detail: assign a pathname containing non-ASCII characters, such as démonstration.html, and the browser encodes it per RFC 3986, so href shows /d%C3%A9monstration.html, with no manual percent-encoding on your part.
The URL constructor takes a second argument: a base URL. new URL("cats", "http://www.example.com/animals/dogs") does not give http://www.example.com/animals/dogs/cats; it gives http://www.example.com/animals/cats. That is because "dogs" is the filename segment of the base address, with no trailing slash, so the relative URL resolves against the directory part of the base. The lodge project learned this the hard way: a detail page lived at /rooms/12, code used it as the base to resolve the relative address "photos", and the result was /rooms/photos instead of the intended /rooms/12/photos. The fix is to add a trailing slash to the base, or to build with an absolute path, and never to leave relative resolution to intuition.
When an address is invalid: ask first whether it parses, then build
The URL constructor throws when an address cannot be parsed into a valid URL. Addresses typed into an input by a user, links synced from another system, and shared links truncated by a chat app can all be invalid. MDN gives two ways to handle it: wrap new URL in a try...catch block and fall back when it throws, or ask URL.canParse() first whether the address parses, and only build the object when it says yes. Both work; canParse() reads more cleanly, because it does not deliberately trigger an exception just to ask a question.
There is also a quieter option: URL.parse(). It does the same job as the constructor, except that it returns null on failure instead of throwing. The caller only has to check whether the result is null before deciding what to do next. Which of the three to use depends on your code style: use the constructor where try...catch is already in play, and canParse() or parse() where a plain check fits. They share one rule: never assume an address from a user is valid. Invalid addresses are the norm, not the exception.
Query parameters: URLSearchParams is the tool for everything after the question mark
The part after the question mark is the query string: key-value pairs joined by &. Reading it, changing it, and building it all have a dedicated tool, URLSearchParams, so there is no need to hand-write split("&") followed by split("="). The most common use is reading parameters from the current page: const params = new URL(window.location.href).searchParams, and params.get("id") returns the id value. The lodge filter page works exactly this way: the address bar reads ?city=hangzhou&guests=2&price=300-600, and on load the page reads all three values back out of searchParams to restore the filter state, so a refresh loses nothing.
URLSearchParams methods fall into three groups: reading, changing, and checking. Reading has get(), getAll(), keys(), values(), entries(), and a read-only size property that reports the total number of entries. Changing has append(), set(), delete(), and sort(). Checking has has(), which can ask "is this parameter there?" and also "is this parameter there with this value?". MDN's example strings these together: starting from q=URLUtils.searchParams&topic=api, has("topic") is true, get("topic") is api, and after append("topic", "webdev"), toString() gives q=URLUtils.searchParams&topic=api&topic=webdev, with a second parameter of the same name added.
One difference must be remembered: get() returns only the first value, getAll() returns all of them. With foo=bar&foo=baz in the address, get("foo") gives only "bar", while getAll("foo") gives ["bar", "baz"]. The lodge filter supports picking several cities, so the address can hold city=hangzhou&city=suzhou. Reading it with get() alone silently drops the second choice: the user picked two cities, and the page filters by one. set() has a similar temper: it deletes every old value for the key and keeps only the new one. To keep several values, use append(); to keep exactly one, use set(). Pick the wrong one and the filter quietly changes shape.
Encoding: plus signs, percent signs, and the double-encoding trap
Encoding is where query parameters fail most often. When URLSearchParams serializes, it percent-encodes everything except ASCII alphanumerics and * - . _, and it encodes a space as a plus sign +. When parsing, it decodes a plus sign back into a space. MDN's example makes the point well: base64 output often contains plus signs, such as E+AXQB+A. Paste it into a query string with new URLSearchParams(`bin=${base64Data}`), read it back with get("bin"), and every plus has become a space, giving "E AXQB A", which no longer decodes to the original. The correct way is to never build the string by hand and instead use append(): searchParams.append("bin", base64Data) encodes the plus as %2B, and reading it back returns the original E+AXQB+A.
The lesson fits in one sentence: never build URLSearchParams from a dynamically interpolated string. A template literal looks convenient, but it bypasses encoding, so special characters enter the address raw and come back changed. append() and set() take over the encoding; you only hand them the unencoded original value. The reverse holds too: keys and values read out of URLSearchParams are already decoded, so do not call decodeURIComponent on them again, or the percent sign itself gets decoded a second time. That is exactly how %2524 double-encoding is born.
One more subtlety hides in how URL.searchParams and URL.search work together. Changing searchParams updates the URL's search, but the two do not encode the same way: URL.search encodes a space as %20, while URLSearchParams encodes it as +. MDN's example is blunt: for the address https://example.com/?a=b ~, url.searchParams.toString() is a=b+%7E, and after calling url.searchParams.sort(), even with the values unchanged, the whole address serializes differently, with href becoming https://example.com/?a=b+%7E. Sorting is not wrong, but it rewrites the entire query string as a side effect. So do not call sort() when there is no need, and do not assume that "just reading the parameters" cannot change the address; reading and writing are one step apart.
Empty values, missing equals signs, and repeated keys: three cases that are easy to misread
There are three query-parameter cases that look alike but mean different things. The first is foo=, with an equals sign and nothing after it: get("foo") returns an empty string. The second is foo, with no equals sign at all: get("foo") also returns an empty string. URLSearchParams does not distinguish the two, and after toString() both become foo=. The third is a parameter that is not there at all: get("foo") returns null. An empty string and null are different things: the first means "the user gave this parameter with an empty value", the second means "the user never gave this parameter". In the lodge filters, price= left empty and no price parameter at all mean different things: the first may mean the user cleared the price, the second means the user never touched the price filter. In code, use has() to check existence first, then get() to read the value; never lump an empty string together with null.
Repeated keys are another source of misreading. As above, get() takes only the first, getAll() takes all. There is one more behavior: delete() with no second argument removes every value for the key, while delete() with a value removes only that pair. To remove one city and keep the other, the value must be passed in. sort() orders keys alphabetically, and the relative order of repeated keys stays as it was. MDN documents each of these behaviors with a clear example; reading them before writing the code is much cheaper than debugging after release.
The hash fragment is not a query parameter: everything after # is a different matter
The part after the # in an address is the hash fragment, and it is a different system from query parameters. Query parameters are sent to the server; the hash fragment is not, and the browser uses it locally to jump to an anchor on the page, or a frontend router uses it as page state. The lodge room page uses #photos to jump to the photo section and ?room=12 to tell the server which room to show; each does its own job. Hand-written string building fails most often right here: query parameters pasted after the # never reach the server, and rewriting the whole address to change a parameter silently drops the fragment.
The URL interface keeps the two apart cleanly: url.search handles everything after the ?, url.hash handles everything after the #, and changing one never touches the other. Read the current page's fragment with window.location.hash, change it with url.hash = "photos", and the browser jumps to the matching spot without reloading. Hash-mode frontend routing runs on this mechanism: the path after # changes, the page content follows, and the server keeps seeing the same address throughout. Remember the split: things the server must receive go in query parameters, and local positioning and state go in the fragment. Mix them and two places need fixing at once.
Five ways address handling fails in real projects
The chart below shows the breakdown of 64 address-handling incidents in one quarter in the fictional Mountain Lodge project: hand-built strings missing a ? or &, 22; encoding handled badly so parameters came back changed, 14; reading repeated parameters with get() and losing the later values, 12; relative addresses resolved against the wrong base, 9; and losing the hash fragment while changing query parameters, 7. 22 + 14 + 12 + 9 + 7 = 64, so the numbers balance. These numbers are invented to make a point, but every category is a real failure that repeats in real projects, and each one is worth checking against.

The first category is hand-built strings. A question mark written twice, a missing &, or an unencoded & inside a value can split one parameter into two or glue two into one. The fix is to stop building strings entirely and hand the work to URL and URLSearchParams. The second is bad encoding: plus signs turning into spaces, percent signs decoded twice, Chinese characters entering an address unencoded. All of these come from not handing encoding to the right tool. Remember: give the raw value when setting, read the decoded value when getting, and let encoding happen only at serialization time.
The third is reading only the first value. With multi-select parameters, get() drops data — and what it drops is the user's choice. For any parameter that can repeat, use getAll() without exception. The fourth is a wrong relative base: whether the base address ends with a slash changes the result completely, so print the resolved result once before trusting it, and confirm the path is the one you wanted. The fifth is a lost hash. Rewriting url.search or rebuilding href from scratch easily drops a #top fragment, and a user who followed a shared link lands at the top instead of the intended spot. Change query parameters through searchParams only, never by rewriting the whole string, and the hash cannot be lost.
Shared links and filter state: treat the address as application state
Query parameters in the address bar have a natural advantage: they are free storage for application state. Put the filters in the address, and a refresh keeps them; copy the address and send it to a friend, and they open the exact same filter state, with no login, no backend, and no local storage. The lodge filter page does exactly this: city, guest count, price range, and check-in date all live in the query parameters, and every time the user changes a filter, the code writes the new address with history.replaceState, changing the address without reloading the page.
There are a few practical points. First, keep parameter names short and stable: city beats selectedCity, because renaming a parameter breaks every old link already shared, and the old links stop resolving. Second, leave default values out of the address. If the default guest count is 2, do not write guests=2; the shorter the address, the easier it is to read and share, and reading code can fall back to the default when the parameter is absent. Third, never put sensitive information in the address. Query parameters enter browser history, server logs, and shared links, so tokens, phone numbers, and ID numbers are all forbidden there. Fourth, validate parameter values. The address is editable by the user, so an illegal value like price=abc must be rejected; validate what you read before rendering it.
Fifth, sort and deduplicate. The same filter set with parameters in a different order looks like two different links, which confuses anyone sharing them. Use a fixed order when writing, or call sort() once to normalize, and the address becomes stable. Sixth, do not stuff the whole application state into the address. It fits light state such as filters, pagination, and the current tab; it cannot hold long text or complex objects, and when the state grows past that, another state-management approach is the right call. The address is a snapshot of state, not a database.
A workflow for address-handling code: parse first, trust second
For AI-generated projects, fix a workflow for address handling. First, parse the address before doing anything with string methods. Run new URL() or URL.parse() first, and stop invalid addresses there instead of letting them flow downstream. Second, read parameters with searchParams: getAll() for multi-value keys, has() to check existence first, get() for single values. With that split fixed, the "read it wrong and never noticed" failure disappears. Third, change parameters with set(), append(), and delete(), never by building strings; let the browser handle encoding.
Fourth, prepare three sets of addresses for testing: normal ones, ones with special characters, and invalid ones. City names in Chinese, base64 values containing plus signs, multi-selects with repeated parameters, empty parameters without an equals sign, and addresses built from illegal characters should all appear in the tests. Fifth, verify with a real shared link end to end: copy the address, paste it into a chat app, and open it from there, checking that every parameter survives. Chat apps sometimes truncate addresses or escape characters, and this step catches problems a development environment never shows. Sixth, check on a schedule whether old shared links still work. Rename a parameter and the old links break, so before renaming, think about how many people still hold the old link.
Finally, a reminder: the best address-handling code is code the user never notices. Change a filter and the address follows; share the address and the result matches; refresh the page and the state is still there; copy and paste and no parameter is lost. When all four hold, the address bar stops being an ugly string and becomes the application's most reliable way to sync state. The tools are already in the browser. There is no need to hand-write concatenation, and no need to stay up late debugging whether a question mark was missed.
Comments (0)
Sources
Related articles
Every web page makes decisions all day: a total over 100 gets a discount, zero stock shows sold out. Following MDN's Making decisions in your code — conditionals, if...else, and switch: if and else if, comparison operators, truthy and falsy, logical operators, the classic || mistake, nested if and the dangling else, switch and fall-through, the ternary operator, and guard clauses.
On 17 November 2026, GitHub shipped a bundled Copilot upgrade for Microsoft Ignite: browser use in public preview, letting Copilot work in your signed-in Chrome or Edge; the Copilot app now takes Azure DevOps repositories, with agents opening pull requests and even merging them; code review gains Adaptive effort and secret detection. Two items are generally available, six in preview.
The main thread has to draw the page and do the accounts, so it freezes the moment the work gets heavy. A worker is another thread in another global context, and the two sides talk only through messages. Following MDN's Using Web Workers and Worker docs: new Worker, postMessage and onmessage, structured-clone copying, what a worker can and cannot do, onerror and terminate(), SharedWorker, and transferable zero-copy — with a 100-mistake breakdown from a fictional cafe order page.