Sub topic 10
Applied Filters, Reset, and Shareable URLs
This chapter assumes you know how filter controls and facets work from the earlier chapters. It also assumes you can read TypeScript and know the basics of the browser History API (pushState, replaceState, popstate). The chapter covers how an app should show which filters are active, how users undo them, and how the whole state can live in the URL.
Why filter state needs a design
Once a user picks a filter, the result list changes and the controls usually close or scroll out of view. The user now has a hidden condition shaping what they see. If they can't tell which conditions are active, they misread the results. A short list of boots may look like "this store has few boots" when it really means "only size 44 in black under $80."
Three questions must always have a visible answer:
- What is applied right now?
- How do I remove one condition?
- How do I get back to the unfiltered state?
A fourth question is invisible but just as important: can I send this exact view to someone else, or come back to it tomorrow? The URL is how you answer that.
Showing applied filters
Display applied filters near the results, not only inside the filter panel. The panel may be collapsed on small screens, and a user scanning results needs the summary in their line of sight.
A common pattern is a row of removable chips. Each chip names the filter and its value ("Category: Boots", "Min price: $50") and has a remove button.
- Write chips in the user's vocabulary, not the field name in your data model. "In stock" is better than
availability=1. - Give the remove button an accessible name that includes the filter, such as "Remove filter: Category Boots". A bare "×" tells a screen reader user nothing.
- Keep chips in a stable order, matching the order of the filter panel, so the row doesn't reshuffle as people add filters.
- Show the result count next to the chips and update it with every change. The
role="status"pattern from the search field chapter works here too. - Don't hide the search query among the chips unless you give it the same removal behavior. The query is also a condition.
When many filters are applied, wrap the chips or collapse them behind "+3 more". Never silently truncate the list. An applied filter the user can't see is the worst case.
Designing reset
Reset has more decisions than it appears to. Decide each of these deliberately.
Clear one versus clear all. Offer both. Removing one chip handles the common case of "slightly too narrow." A "Clear all" control handles "start over." Show "Clear all" only when at least one filter is applied. A disabled button that never does anything adds noise.
What "all" includes. Users disagree about whether the search query counts as a filter. A safe rule is that "Clear all filters" keeps the query and resets the facets, while a separate action (clearing the search field) removes the query. Label the button to match what it does. "Clear filters" and "Start over" promise different things.
Sort order. Sort is a view preference, not a narrowing condition. Most apps leave it alone on reset. If you do reset it, say so.
Pagination. Any change to filters or query must return the user to page one. Staying on page 4 of a result set that now has two pages produces an empty page that looks like a bug.
Undo. Resetting after careful selection can be costly. For heavy filter setups, keep the previous state for a few seconds and offer an "Undo" message. Because filters live in the URL, the browser back button gives a free version of this, as the history section below shows.
Defaults. If the page has a default filter, such as "In stock only," make that visible as an applied chip. Decide whether reset returns to the default or to nothing, and keep that consistent.
Putting state in the URL
Filter state belongs in the URL for four reasons. People can share a view. They can bookmark it. The back button can restore it. A page reload doesn't wipe it. It also makes the state easy to debug, because you can read it in the address bar.
The rule: the URL is the source of truth, and the UI renders from it. When a user clicks a control, you update the URL, and the screen follows. This avoids the situation where component state and URL drift apart.
Use readable, stable parameter names. Repeat a key for multi-select values, and omit parameters that have no value.
type Filters = {
query: string;
categories: string[];
minPrice?: number;
};
function toSearchParams(f: Filters): URLSearchParams {
const params = new URLSearchParams();
if (f.query) params.set("q", f.query);
for (const c of f.categories) params.append("category", c);
if (f.minPrice !== undefined) params.set("min_price", String(f.minPrice));
return params;
}
function fromSearchParams(params: URLSearchParams): Filters {
const min = params.get("min_price");
return {
query: params.get("q") ?? "",
categories: params.getAll("category"),
minPrice: min !== null ? Number(min) : undefined,
};
}A URL such as /search?q=boots&category=hiking&category=winter&min_price=50 round-trips through these two functions without loss. URLSearchParams handles the percent-encoding of spaces and special characters, so don't build query strings by concatenation.
Parse defensively
The URL is user input. Anyone can edit it, and old bookmarks can contain values you no longer support. fromSearchParams above has a bug: ?min_price=abc produces NaN, which then flows into your UI and your API call. Validate at this boundary.
const KNOWN_CATEGORIES = new Set(["hiking", "winter", "rain", "casual"]);
function parseMinPrice(raw: string | null): number | undefined {
if (raw === null || raw.trim() === "") return undefined;
const n = Number(raw);
return Number.isFinite(n) && n >= 0 ? n : undefined;
}
function parseFilters(params: URLSearchParams): Filters {
return {
query: (params.get("q") ?? "").trim(),
categories: params.getAll("category").filter((c) => KNOWN_CATEGORIES.has(c)),
minPrice: parseMinPrice(params.get("min_price")),
};
}
function removeCategory(f: Filters, category: string): Filters {
return { ...f, categories: f.categories.filter((c) => c !== category) };
}
function clearFilters(f: Filters): Filters {
return { query: f.query, categories: [], minPrice: undefined };
}clearFilters keeps the query, following the rule from the reset section. If a bookmark holds a category you removed, dropping it is safe. Better still, tell the user "Some filters in this link are no longer available" so the results don't surprise them.
Push or replace
Each URL update needs a history decision.
| Action | History method | Reason |
|---|---|---|
| Adding or removing a filter | `pushState` | The back button should undo the change. |
| Submitting a new search | `pushState` | It is a new view the user may want to leave and return to. |
| Typing in the field (live suggestions or live results) | `replaceState` | One history entry per keystroke makes back unusable. |
| Normalizing a bad URL (dropping invalid values) | `replaceState` | The user didn't navigate, so don't add an entry. |
This code applies the rule and restores state when the user navigates back or forward:
type HistoryMode = "push" | "replace";
function syncUrl(filters: Filters, mode: HistoryMode): void {
const qs = toSearchParams(filters).toString();
const url = qs ? `${location.pathname}?${qs}` : location.pathname;
if (mode === "push") {
history.pushState(null, "", url);
} else {
history.replaceState(null, "", url);
}
}
function render(filters: Filters): void {
console.log("render results for", filters);
}
function applyFilters(filters: Filters, mode: HistoryMode = "push"): void {
syncUrl(filters, mode);
render(filters);
}
window.addEventListener("popstate", () => {
render(parseFilters(new URLSearchParams(location.search)));
});
render(parseFilters(new URLSearchParams(location.search)));Note that popstate calls render directly and doesn't call syncUrl. The browser has already changed the URL. Writing it again would add a history entry and break the forward button.
The last line handles the first page load. Without it, a shared link would open with the right URL and an unfiltered page.
Common errors
| Problem | Symptom | Fix |
|---|---|---|
| State only in memory | Reload or shared link shows an unfiltered page | Read the URL on load and render from it |
| Pushing on every keystroke | Back button steps through each letter | Use `replaceState` while typing, `pushState` on commit |
| Page number kept after a filter change | Empty page 4 of a two-page set | Remove the `page` parameter when filters change |
| Unvalidated parameters | `NaN` in requests, errors on odd links | Parse and whitelist at the boundary |
| Panel controls out of sync with URL | A checkbox looks unchecked while its filter applies | Derive control state from the parsed filters |
| Chips hidden on small screens | Users can't see why results are narrow | Keep the summary outside the collapsed panel |
| Different parameter order for the same state | Duplicate URLs, bad caching and analytics | Build the query string from one function with a fixed order |
Edge cases
- Very long filter sets. Browsers and servers limit URL length, commonly around 2,000 characters in practice. If a user can select hundreds of values, consider a compact encoding or a saved-search ID.
- Saved searches. A saved search is a named URL. If the design stores the URL itself, your parameter names become a contract. Version them or keep them backward compatible.
- Logged-in preferences. Remembering a user's last filters is useful, but a URL with explicit parameters must always override remembered values. Otherwise a shared link shows different results to different people.
- Zero-result filter combinations. When the URL describes a view with no results, the empty state should name the active filters and offer a one-click removal of each. The next chapter covers this.
Exercise
A user selects the "winter" category, then the "rain" category, then presses the browser back button. Which history calls should the app have made, and what should the user see after pressing back? Also, why should the popstate handler not call syncUrl?
Show answer
Each filter change is a deliberate navigation, so the app should call pushState for both. Pressing back returns to the URL with only "winter" applied, and the handler renders results and chips from that URL. The popstate handler must not call syncUrl because the browser has already restored the URL. Writing it again would push a new entry, which would erase the forward history and make the back button misbehave.
Exercise
A shared link contains ?q=boots&category=hiking&min_price=-20&page=3. Using the rules in this chapter, describe how the app should handle the link and what the user should see.
Show answer
Parse and validate each value. q and category=hiking are valid and stay. min_price=-20 fails the check (n >= 0), so the app treats it as unset, and it may tell the user that part of the link was ignored. The app should use replaceState to normalize the URL, since this isn't a user navigation. Page 3 is only valid if the filtered result set has at least three pages. If it doesn't, fall back to page one. The chips should show "boots" and "Category: hiking".