What you'll learn: By the end of this lesson you will be able to decide which pieces of state belong in the URL, parse a query string as untrusted input with safe defaults, write one canonical URL for each state, choose between
pushStateandreplaceState, subscribe React to the URL so Back and Forward work, and test all of it without a browser.
Think of a street address. You can give it to a friend, write it in a diary and find the same house a year later. A page's URL can do that for a screen: "the tea category, cheapest first, page two" is a short string that can be bookmarked, sent in a chat message, reloaded, or reached again with the Back button. State kept only in a component's memory does none of that.
The running example is the product list page of a grocery catalogue (the front end of the ShopStream marketplace used in this course): a search box, three category checkboxes, a sort menu and a pager. The previous lesson in this module, Local vs Global State, asks where state lives in a component tree. This lesson covers one special place, the address bar, a store the browser owns and users can edit by hand.
The core idea
Keep three statements in mind.
- The URL is the one store a user can copy. Put state there when reload, Back or a pasted link should restore it. Keep everything else out: a URL is public and visible in logs.
- The URL is untrusted input. Anyone can type anything after the question mark. Parsing must never throw, and every field has a default.
- One state, one URL. If
?category=teaand?page=1&category=tea&category=teamean the same screen, links and analytics see two pages for one. Write one canonical form.
The screen is then a function of the URL: the list is derived from the parsed filters on each render, and nothing stores the same facts a second time.
What belongs in the URL
A quick test: if I reload the tab and lose this, did the user lose something worth keeping?
| State | In the URL? | Why |
|---|---|---|
| Search text, filters, sort order, page number | Yes | Shareable, bookmarkable, restored by reload |
| The selected item's id, or the open tab | Yes | The id, never a copy of the object |
| Half-typed form input | No | Private and transient |
| Whether a dropdown is open | No | Meaningless to anyone else |
| Access tokens, personal data | Never | URLs end up in history, logs and shared messages |
Figure 1. Where does this state live?
sensitive?"} A -->|"yes"| N["Keep it out of the URL
(component or server state)"] A -->|"no"| B{"Should a reload, the Back
button or a pasted link
restore it?"} B -->|"yes"| U["Put it in the URL
(path or query string)"] B -->|"no"| L["Component or app state"]
How to read this: privacy is checked first because it overrides convenience. Only then ask whether restoring the screen matters. Choosing the path versus the query string is a routing question: identity of the thing (which product) goes in the path, adjustments to a view (filters, sort) go in the query string.
The URL as a store
A store needs a way to read, a way to write and a way to be told of changes. The browser provides all three for the address, in a slightly unusual way.
- Read:
window.location.searchreturns a string starting with?when the URL has a query, and""when it does not. - Write:
history.pushState()adds an entry to the session history;history.replaceState()modifies the current one. The new URL must be of the same origin or the call throws. - Subscribe:
popstatefires when the active history entry changes through navigation (Back, Forward,history.go()). MDN is explicit that callingpushState()orreplaceState()yourself will not trigger it.
That last point is the trap: your own writes are invisible to your own app unless you announce them, usually with a custom event, and subscribe to both. The client-side routing lesson builds that machinery in full; this lesson needs the smallest version.
Figure 2. The URL is the store; the screen is derived
How to read this: the accent boxes are the code you write. Every change, whether the user clicked a checkbox, pressed Back or opened a pasted link, travels the same loop: the address changes, the subscription notices, the string is parsed, the view is derived. Nothing writes to the view directly.
Parse the URL like user input
A hand-edited link such as ?page=banana must not crash the page or show a blank screen. The cleanest approach is a pure function from string to a typed object, with a default for every field.
Illustration 1: the minimal example
URLSearchParams does the splitting and decoding. Run in Node:
const params = new URLSearchParams("?q=green+tea&category=tea&category=snacks&page=2");
console.log(params.get("q"));
console.log(params.get("missing"));
console.log(params.getAll("category"));
console.log(Number(params.get("page")) + 1);
params.set("q", "a&b");
console.log(params.toString());
console.log(Number("abc"), Number(""), Number("2.5"));
Output, from running it in Node 26.13.1:
green tea
null
[ 'tea', 'snacks' ]
3
q=a%26b&category=tea&category=snacks&page=2
NaN 0 2.5
The constructor strips one leading ? and reads + as a space; get() returns the first value for a key and null for a missing one; getAll() returns every value; toString() percent-encodes. The last line is the danger: Number("abc") is NaN, Number("") is 0 and Number("2.5") is 2.5, so Number() alone does not give a valid page number. The lab accepts a page only when it matches a strict digit pattern, and clamps it.
Illustration 2: the realistic example, from the lab
The lab's parseFilters and toSearch turn a query string into { q, categories, sort, page } and back. The lab's demo prints what they do with good, bad and equivalent inputs. Expected output, captured from a real run (node src/demo.ts in examples/frontend/labs/url-state, copied from examples/frontend/golden/url-state.txt), in full:
=== 1. a well-formed link becomes a typed object
link : ?q=green+tea&category=tea&category=snacks&sort=price-asc&page=2
filters : {"q":"green tea","categories":["tea","snacks"],"sort":"price-asc","page":2}
=== 2. the URL is untrusted input: bad values fall back to defaults
?sort=bogus -> sort=relevance page=1 categories=[] q=""
?page=abc -> sort=relevance page=1 categories=[] q=""
?page=0 -> sort=relevance page=1 categories=[] q=""
?page=2.5 -> sort=relevance page=1 categories=[] q=""
?page=99999 -> sort=relevance page=1 categories=[] q=""
?page=5000 -> sort=relevance page=1000 categories=[] q=""
?category=wine -> sort=relevance page=1 categories=[] q=""
?q=%3Cscript%3E -> sort=relevance page=1 categories=[] q="<script>"
=== 3. one state, one URL (canonical form)
?category=tea -> ?category=tea
?page=1&sort=relevance&category=tea -> ?category=tea
?category=tea&category=tea&page=1 -> ?category=tea
?sort=relevance&category=tea&q= -> ?category=tea
default state serialises to: ""
=== 4. special characters survive the round trip
q written : ?q=a%26b%3Dc+d%2Be
q read : "a&b=c d+e"
=== 5. parameters the page does not own are kept
before : ?utm_source=newsletter&q=old&page=4
after : ?utm_source=newsletter&q=new
=== 6. the list is derived from the URL, never stored
(no query) total=12 page 1/3 Assam black tea | Green tea sampler | Jasmine green tea | Masala chai blend
?category=coffee&sort=price-desc total=4 page 1/1 Cold brew bags | Dark roast beans | Medium roast beans | Decaf ground coffee
?q=green total=3 page 1/1 Green tea sampler | Jasmine green tea | Green tea shortbread
?page=40 total=12 page 3/3 Salted almonds | Oat biscuits | Dark chocolate squares | Green tea shortbread
?q=zzz total=0 page 1/1 -
Block 2: every bad value becomes a default, and a hostile q is still just a string, so the rendering code must treat it as text. Block 3: four spellings of one state collapse into one URL, because defaults are omitted, duplicates removed and parameters written in a fixed order. Block 5: a marketing parameter the page does not own survives. Block 6: ?page=40 shows page 3 of 3, not an empty page. The catalogue and prices are illustrative.
Push for choices, replace for typing
Both write calls change the address bar without loading a page. pushState adds a history entry, so Back returns to the previous screen; replaceState rewrites the current one, so Back skips it. Ask what a user would expect Back to do.
- A deliberate choice (a category, the sort, the next page): push. Back undoes it.
- Continuous input (typing in the search box): replace. Otherwise one search for "green" leaves five entries and Back walks through half-typed words. Debouncing and throttling covers the other half: limit the work, and replace rather than push.
- A correction (clamping an impossible page): replace, so the bad address is not left behind.
Two details: navigating to the address the page is already at should do nothing, so a repeated click adds no duplicate entry; and a filter change should reset the page to 1.
Figure 3. Back after two choices
How to read this: the app never remembers "the previous filters". The browser's history does. Back changes the address, the subscription reads it, and the same parse-and-derive path produces the earlier screen.
Subscribing React to the address
React has a hook for this shape of store: useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot). The react.dev reference requires that repeated calls to getSnapshot return the same value while the store has not changed (compared with Object.is). A string such as location.search satisfies that, so the lab's snapshot is the raw string and the parse happens in a memo; a freshly parsed object on every call would not.
export function useFilters(): Filters {
const search = useSyncExternalStore(subscribe, getSearch, getServerSearch);
return useMemo(() => parseFilters(search), [search]);
}
subscribe listens for popstate and for the lab's own app:urlchange event, and returns a function that removes both listeners.
On a server there is no window. The third argument is used for server rendering and hydration, and react.dev says it must return the same data on the first client render as on the server. The lab returns ""; a framework would pass the request's query string. A difference gives a hydration mismatch, covered in the hydration mismatches lesson.
Illustration 3: a failure, from the lab
ProductList takes a typingMode prop so the wrong choice can be exercised: with "push", five keystrokes add five history entries; with the default "replace" they add none (both asserted in test/history.test.tsx). A second edge: a link naming ?page=40 when the list has three pages would render an empty list. The lab clamps the page when it derives the list, and a test asserts "12 products, page 3 of 3".
Where URL state stops
A URL is not a database: it lands in history, logs and copied messages, and everything in it is a string, so numbers, booleans and lists are conventions you parse. Scroll position is also separate; MDN documents history.scrollRestoration (auto or manual) as the browser's own mechanism.
The other side of this topic
On the back end the same query string arrives in the request and must be validated again: client-side parsing is a convenience, not a control, and MDN's form validation guide says never to trust data passed to your server from the client.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Filters in the URL | Reload, Back and sharing work | Parsing, defaults and canonical form to maintain |
| Filters in component state | Simplest code | Lost on reload; cannot be shared |
| Push on every change | Back undoes each step | Noise when used for typing |
| Replace on every change | Clean history | Back skips real choices |
| Omit defaults from the URL | One state, one URL | A default change alters what old links mean |
Build it
The lab examples/frontend/labs/url-state implements the above: src/filters.ts (pure parse and serialise), src/selectors.ts (the derived list), src/location.ts (read, write, subscribe) and src/ProductList.tsx. Its tests run in jsdom, a JavaScript model of the DOM that keeps a session history and fires popstate but has no address bar, no Back button and no scroll restoration; the lab claims nothing about those.
cd examples/frontend/labs/url-state
../../node_modules/.bin/vitest run
node src/demo.ts
Verified. The 28 tests in two files passed with Node 26.13.1 and Vitest 5.1.0, and the type check passed. They cover parsing and canonical serialisation, the first render coming from the URL, push versus replace, Back and Forward, a new choice after Back discarding the forward entries, pushState alone not notifying the app, and listeners removed on unmount. This session added src/demo.ts (printing the output above) and moved the pure selectProducts function into src/selectors.ts so the demo can run in Node without React; ProductList.tsx re-exports it.
Break it. In ProductList.tsx, temporarily change the checkbox handler update({ categories }, "push") to "replace" and run the tests: two fail ("a category choice adds one history entry" and "a new choice made after going Back discards the forward entries"), because the history entries they count are no longer added. Or render <ProductList typingMode="push" /> and watch the entry count rise by five. Restore the line and re-run the tests afterwards.
Stretch. Add from and to price parameters and decide what happens when from is greater than to: reject, swap, or fall back to the defaults. Write the test first.
In practice: sharable filters on a product listing page
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A grocery listing page keeps its search text, categories, sort and page in component state. Support cannot send a customer a link to "the decaf coffees", shoppers lose their filters on reload, and Back leaves the page instead of undoing the last filter. Marketing also wants to link emails to pre-filtered views.
Starting architecture
Figure 4. Filters live only in memory
How to read this: the warning boxes are the gaps. The address bar is not involved, so nothing can be shared, reloaded or undone with Back.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Keep state, add a "copy link" button | Sharing | A second encoding of the state | Link and screen disagree |
| Query-string state with pure parse and serialise | Reload, Back and sharing | Defaults, canonical form, a subscription | Hand-edited and stale links |
Store filters in localStorage |
Reload | Nothing is shareable | Two tabs, two truths |
The decision
| Field | Decision record |
|---|---|
| Context | Filters are lost on reload, cannot be shared, and Back leaves the page. |
| Decision | Move the filters into the query string. One pure module parses it with defaults and writes one canonical form. Choices push, typing replaces, a filter change resets the page. |
| Consequences, good | Links, reload and Back work; the list is a pure function of the URL and easy to test. |
| Consequences, bad | Old links outlive the code that wrote them; the parser must stay tolerant. |
| Revisit when | The number of parameters grows past what a query string reads well, or filters become personal data. |
Rollout and verification
- Write the parser and serialiser first, with tests for bad, repeated and equivalent inputs.
- Test history behaviour: entries after five keystrokes, after a choice, and after Back then a new choice.
- Check the server render of a filtered URL against the hydrated list.
- Open old links with extra parameters and confirm they land on a sensible screen.
The 2 a.m. failure
A week later, support reports that Back seems "stuck" on the sort menu: it returns to the same screen. A new feature added an effect that writes the filters to the URL whenever they change, while the page also re-reads the URL on popstate. Back changes the URL, which changes the filters, which runs the effect, which pushes a new entry and discards the forward entries.
First three checks: (1) watch the history length while pressing Back; (2) search for pushState calls outside the one navigate function; (3) look for any effect that writes the URL in response to a change that came from the URL. Mitigation: remove the effect and write the URL only from event handlers. Follow-up: keep one write path and add a Back-then-Forward test.
Architect's notes
- One module owns the query string. One function parses, one writes, unknown parameters are kept, and no component calls
pushStatedirectly. - Store ids, not objects. The URL names the item; the screen looks it up.
- Make the parser total. A valid object for any string, never a throw.
- Know what a default change means. Omitting defaults keeps links short but changes what old links mean.
Common mistakes
- Forgetting that
pushStateis silent. The app does not notice its own writes. - Pushing on every keystroke. Back walks through half-typed words.
- Trusting parameters.
Number()can giveNaN,0or a fraction; validate strictly and clamp. - A snapshot that is a new object on every call.
- Secrets or personal data in the URL.
- Writing the URL from an effect that also reacts to it.
- Keeping the old page number when a filter changes.
Key takeaways
- Put state in the URL when reload, Back or a shared link should restore it; keep private and transient state out.
- Parse to a typed object with a default for every field, and write one canonical URL per state.
- Push for choices, replace for typing and corrections, and do nothing when the address is unchanged.
pushStateandreplaceStatedo not firepopstate; announce your own changes and subscribe to both.useSyncExternalStoreneeds a stable snapshot and a matching server snapshot.- The screen is derived from the URL; nothing stores it a second time.
Practice exercises
Exercise 1: Starter (30 min). Predict, then check in Node, what new URLSearchParams("?a=1&a=2") returns from get("a") and getAll("a").
Exercise 2: Intermediate (2 hours). Add a view=list|grid parameter with a default to parseFilters and toSearch, with a round-trip test and a bad-value test.
Exercise 3: Intermediate (2 hours). Write a Back-then-Forward test for a three-step sequence (category, sort, page) and assert the page number at each step.
Exercise 4: Advanced (half day). Add a test that fails if any file other than location.ts calls pushState or replaceState.
Related reading
In this course:
- Client-Side Routing Architecture: the history stack,
popstateand the router as an external store. - Debouncing and Throttling: why typing should not write to the URL on every keystroke.
- Hydration Mismatches: why the server snapshot must match the first client render.
- React Effects and Synchronization: why an effect that writes what it reads is a trap.
Official documentation
- MDN: History API and History.pushState(): the stack, the same-origin rule.
- MDN: History.replaceState(): modifying the current entry.
- MDN: Window popstate event: when it fires, and when it does not.
- MDN: URLSearchParams:
get,getAll, encoding, the leading question mark. - MDN: Location.search: the query string as a string.
- React: useSyncExternalStore: snapshots, subscription and the server snapshot.