liveBook · Manning

Query string

As explained in Vanilla Web

A query string is the URL component containing name-value parameters that modify a resource request or represent view state.

A query string holds optional key-value parameters after `?`, describing which variation of a view is shown rather than identifying a different resource. Use it for state that should survive reloads or be shared and bookmarked, such as filters, sorting, pagination, and search. The path identifies the resource; the hash points to a fragment within the document. section 10.1.8 section 10.1.9

Keep query-string behavior predictable:

  • Set defaults for parameters and remove default values when useful to keep URLs clean. section 10.1.11
  • Sort parameters when canonical URLs matter; consistent ordering can help caching and analytics deduplication. section 10.1.11
  • Replace the current history entry for small state normalization; add an entry when users would expect Back to undo the change. section 10.1.11
const url = new URL(location.href);

url.searchParams.set("sort", "price");
url.searchParams.set("view", "grid");

if (url.searchParams.get("page") === "1") {
  url.searchParams.delete("page");
}

url.searchParams.sort();

history.replaceState(null, "", url);

This example updates sorting and view parameters, removes the default page, sorts the parameters, and replaces the current history entry. section 10.1.11

How Vanilla Web covers it

How deep it goes
Defines query parameters against paths and fragments, then covers defaults, cleanup, canonical ordering, and history updates.
Examples
Uses product filters, sorting, pagination, view mode, search text, and a URLSearchParams update example.
What you can do after
Operate view-state URLs with URLSearchParams, normalize defaults, and choose whether changes replace or add browser history.
How it connects
Connects routes and URL paths with fragments, browser history, caching, and analytics.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.