smartyfy.mrindigi.com

Web Development Pro | Lesson 038 | URLs, Search Parameters, and History

Web Development Pro · Lesson 38 of 60

Module 4: Data, modules, and state

In this lesson

Prerequisites and learning outcomes

Complete lesson 37 first. This lesson builds on url state and navigation semantics. By the end, you can share filter state through a URL and restore it on browser navigation. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Make a filtered view shareable

A directory can encode its public search and category in the URL so a reload, bookmark, or shared link restores the same view. URL state is different from a saved device preference: the URL travels with the link. Define which source wins when they disagree. In the later integrated project, the URL controls the initial filters and saved preferences are applied only by an explicit user action.

Do not put private information in query parameters. URLs can appear in browser history, server logs, copied links, and other contexts. This example uses public workshop title searches and categories only. A convenient state mechanism is not a private storage channel.

Parse with the URL APIs

URL and URLSearchParams handle encoding and parameter boundaries. Avoid splitting a query string manually on ampersands and equals signs, because encoded characters and repeated parameters complicate that approach. The helper receives an absolute URL and returns the normalized filter contract from lesson 36.

File url-state.mjs:

const categories = ['all', 'repair', 'textiles'];
export function readFilters(href) {
  const url = new URL(href);
  const query = (url.searchParams.get('q') || '').trim().slice(0, 100);
  const rawCategory = url.searchParams.get('category') || 'all';
  return { query, category: categories.includes(rawCategory) ? rawCategory : 'all' };
}
export function writeFilters(href, filters) {
  const url = new URL(href);
  const query = filters.query.trim().slice(0, 100);
  if (query) url.searchParams.set('q', query);
  else url.searchParams.delete('q');
  if (categories.includes(filters.category) && filters.category !== 'all') {
    url.searchParams.set('category', filters.category);
  } else {
    url.searchParams.delete('category');
  }
  return url.href;
}

Get returns the first value for a named parameter or null when absent. This example deliberately uses that first-value policy when reading duplicates. Set replaces the parameter's values with one normalized value. Unrelated parameters and the fragment remain intact because the helper edits only the two keys it owns.

Distinguish push from replace

History.pushState adds a same-document history entry without loading a new document. ReplaceState changes the current entry instead. Use push when a committed search should be navigable with Back; use replace when correcting or updating the current entry without creating another meaningful step. Neither method automatically reruns your renderer.

The complete entry module reads the current URL at startup, copies the parsed filters into the controls, and displays their interpretation. On submit it writes the new URL with pushState and then renders the resulting filters. The update is explicit: changing the address bar is not itself a data-flow system.

History API URLs must satisfy the browser's same-origin rules for the current document. This helper preserves the original URL's origin while modifying its query. Do not accept an arbitrary external destination and pass it to pushState expecting navigation; use a real link for navigating to another origin.

Restore state on Back and Forward

A popstate event lets the page respond to history navigation. Its handler should read the current location and render it. Do not call pushState again inside that restoration handler, or you can create extra entries while the user is trying to move backward. History restoration is a read-and-apply path, not a fresh user search.

PushState does not itself dispatch popstate. That is why the submit handler must update the interface directly after changing history. This distinction is easy to miss when a page appears correct after Back but fails to update immediately after Search. Test both directions through the full journey.

The query field's draft value is synchronized when a URL is restored. That is appropriate because Back or Forward selects a previously committed view. A background data refresh, by contrast, should not overwrite unfinished input. The source of a state change determines whether control synchronization is helpful or disruptive.

Keep defaults and normalization consistent

An absent category means all, and an unknown category also becomes all. An empty or whitespace-only query becomes an empty string. Queries longer than one hundred UTF-16 code units are bounded consistently with the state helper and input. These policies should be shared or tested for agreement so URL and form paths cannot produce incompatible states.

The writer omits default values for a concise URL. Therefore an absent filter in a shared URL must retain its defined default, rather than being silently replaced by a different saved device preference. The integrated project uses an explicit “Use saved category” action to avoid that ambiguity.

Encoding is handled by the API. A query containing an ampersand remains one query value instead of accidentally creating another parameter. Do not pre-encode it and then let URLSearchParams encode it again; that can produce double encoding. Supply the actual string value and let the API serialize it.

Test URLs and navigation separately

Pure tests cover empty filters, encoded punctuation, unknown categories, repeated keys, preserved unrelated parameters, fragments, and long queries. A round-trip test writes filters into a URL and reads them back to confirm the intended normalized result. These tests run the real URL APIs in Node.

The entry-module fixture models location changes and explicitly invokes its registered popstate handler. It checks that restoration updates controls without pushing another entry. It does not implement a browser's complete session-history behavior, address bar, scroll restoration, or navigation events. Those remain manual tests with actual Back and Forward controls.

Worked practice

Worked exercise 1: Preserve a query containing punctuation

Task: Search for “repair & reuse.” Worked answer: pass that exact string to URLSearchParams through writeFilters. The serialized URL encodes it as one q value. Manual concatenation could mistakenly treat the ampersand as a parameter separator.

Worked exercise 2: Avoid a history loop

Task: The popstate handler calls pushState after reading the restored URL. Worked answer: remove that push from the restoration path. Read current location, synchronize controls, and render without adding another history entry.

Worked exercise 3: Resolve preference ambiguity

Task: A shared URL omits category, while the device saved repair. Worked answer: honor the URL contract's all default. Let the person explicitly apply the saved category if desired, rather than making the same shared link mean different initial filters on different devices.

Knowledge check

Question 1

Why use URLSearchParams instead of manual splitting? A) It handles parameter encoding and boundaries. B) It hides the URL from history. C) It encrypts query values. D) It rejects all unsupported application category values automatically.

Check question 1: answer and explanation

Answer: A. Correct parsing and serialization are its role; privacy is not.

Question 2

What does pushState do here? A) Reloads the server document automatically. B) Adds a same-document history entry. C) Replaces the current entry without adding a step. D) Fires popstate immediately by definition.

Check question 2: answer and explanation

Answer: B. The app must still update its own view after the call.

Question 3

What should the popstate handler avoid? A) Reading location. B) Synchronizing controls. C) Pushing a new entry during restoration. D) Rendering the restored filters.

Check question 3: answer and explanation

Answer: C. Restoration should not manufacture another search step.

Question 4

What is the default category when the parameter is absent? A) The first record's category. B) Whatever any device previously saved. C) The last category selected in an unrelated tab. D) all.

Check question 4: answer and explanation

Answer: D. The URL contract defines a stable default for shared links.

Question 5

What does the Node URL test not establish? A) Actual browser Back/Forward and scroll behavior. B) The asserted encoding round trip. C) The helper's default values. D) Preservation of checked unrelated parameters.

Check question 5: answer and explanation

Answer: A. Browser session-history integration needs its own evidence.

Sources and further reading