Skip to content

URL Filter State Needs a Canonicalization Contract

A shared list URL opens with default filters. After query parameters are added, Back navigates through every typed character and refresh sends duplicate requests. URL state is more than serialized component state: it is external input, a sharing format, and browser history.

This example owns a query space containing keyword, status, and page only. A production route sharing parameters with analytics or other modules needs an ownership policy before adopting this example's decision to discard unknown fields.

Validate at the boundary and keep one internal representation ​

URLs can be edited or generated by older versions. Pages can be negative, enormous, or duplicated; status values can be unknown. Parsing must define defaults and duplicate policies. The example allowlists, deduplicates, and sorts statuses. Single-value fields use their first occurrence, and page values are restricted to 1 through 9999.

The keyword cap is explicitly one hundred UTF-16 units, not a general visible-character limit. A product needing grapheme limits should use consistent segmentation instead. Encoding and repeated-parameter behavior are defined by the WHATWG URL Standard.

javascript
export function parseFilters(search) {
  const params = new URLSearchParams(search);
  const allowed = new Set(['open', 'closed']);
  const status = [...new Set(params.getAll('status')
    .filter(value => allowed.has(value)))].sort();
  const rawPage = params.get('page') ?? '1';
  const page = /^\d{1,4}$/.test(rawPage) && Number(rawPage) >= 1
    ? Number(rawPage) : 1;
  return { q: (params.get('q') ?? '').trim().slice(0, 100), status, page };
}

export function serializeFilters(filters) {
  const params = new URLSearchParams();
  if (filters.q) params.set('q', filters.q);
  for (const status of filters.status) params.append('status', status);
  if (filters.page !== 1) params.set('page', String(filters.page));
  return params.toString();
}

export function canonicalSearch(search) {
  return serializeFilters(parseFilters(search));
}

The serializer expects a normalized internal model. Validate arbitrary external objects before calling it. Omitting the default page and writing statuses in one order makes equivalent inputs converge. Test that canonicalization is idempotent and that parse/serialize round trips preserve the query's meaning.

Draft input need not become a history entry ​

Keep an actively edited search string locally until submission or a defined debounce boundary. Use push when committing a meaningful user navigation. Use replace when cleaning invalid parameters or updating intermediate state within one action. Every keystroke need not become another Back step.

If a router owns history, use its navigation API rather than independently calling native history methods. On Back and Forward, parse the URL again and restore committed controls. A new filter usually resets pagination, whereas restoring a history entry should retain its recorded page. A single effect that resets page one on every change confuses these distinct events.

Derive requests and caches from the same model ​

Controls, requests, and cache identity should come from one committed normalized model. Reversed status-parameter ordering can then represent the same query. Check identity before applying a response so a slow previous search cannot overwrite the current one.

Avoid loops where a control writes the URL, a URL effect rewrites controls, and controls write the URL again. Establish one path: draft input creates an action, the action commits navigation, route parsing yields a query model, and that model drives rendering and loading. Only replace an address when its canonical form differs, and avoid loading the same effective query twice during cleanup.

Sharing has privacy and lifetime boundaries ​

Query strings appear in history, logs, copied links, and potentially referrer data. Tokens, sensitive personal searches, and large private conditions should not be embedded casually. Complex shared views can use server-held records and short IDs, but possession of an ID must not replace authorization.

Changing enums or field definitions requires a migration policy. Changed defaults can alter old links that omitted fields. When exact reproduction matters, version the query protocol or write critical defaults explicitly. A link remaining reachable does not prove it still means the same thing.

Test external entry and history restoration ​

Cover empty queries, duplicates, invalid pages, unknown enums, Chinese text, plus signs, reordered parameters, and older links. Then test direct entry, refresh, Back/Forward, and rapid searches. Assert agreement among controls, URL, and requested filters, including no duplicate request caused solely by normalization.

A shared page lets another person inspect the same situation. Treating its query as a small protocol keeps that promise as filters evolve.

MIT Licensed