Skip to content

The URL Owns Shareable Filters

The Course
•
22 min study

The decision

A filter that must survive reload, sharing and the Back button belongs in the URL. A text field can keep a responsive draft, but it must reconcile with the address when navigation changes it.

Read, predict, run

The input contains an existing query string and the new search text. The function copies URLSearchParams, changes only q and returns the canonical query:

JavaScript
export function run({ query, text }) {
  const params = new URLSearchParams(query);
  if (text.trim()) params.set("q", text.trim());
  else params.delete("q");
  return params.toString();
}

Before pressing Run, predict what run returns for {"query": "tag=react", "text": "a & b"} and {"query": "q=old&tag=react", "text": ""}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

The URL Owns Shareable Filters Next.js · 6 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import SearchBox from "./SearchBox.jsx"; export default async function Page({ searchParams }) { const params = await searchParams; const q = typeof params.q === "string" ? params.q : ""; const tag = typeof params.tag === "string" ? params.tag : ""; return ( <main> <h1>The URL Owns Shareable Filters</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <SearchBox /> <p role="status"> The server read q={JSON.stringify(q)} tag={JSON.stringify(tag)} </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useState } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { run } from "@/lib/contract.js"; // The URL owns the filter; the input keeps a draft so typing stays smooth. // Each keystroke replaces the address (no history entry per letter). When // the URL changes some other way, such as Back or an edited address, the // draft follows it. export default function SearchBox() { const router = useRouter(); const pathname = usePathname(); const searchParams = useSearchParams(); const current = searchParams.get("q") ?? ""; const [draft, setDraft] = useState(current); const [seen, setSeen] = useState(current); if (current !== seen) { setSeen(current); // Our own replace gives back the trimmed draft; anything else is news. if (current !== draft.trim()) setDraft(current); } function handleChange(event) { setDraft(event.target.value); const query = run({ query: searchParams.toString(), text: event.target.value }); router.replace(query ? `${pathname}?${query}` : pathname); } return ( <label> Search <input value={draft} onChange={handleChange} /> </label> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ query, text }) { const params = new URLSearchParams(query); if (text.trim()) params.set("q", text.trim()); else params.delete("q"); return params.toString(); } export const examples = [ [{ query: "tag=react", text: "a & b" }, "tag=react&q=a+%26+b"], [{ query: "q=old&tag=react", text: "" }, "tag=react"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"query": "tag=react", "text": "a & b"} → "tag=react&q=a+%26+b".
  • Input {"query": "q=old&tag=react", "text": ""} → "tag=react".

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

Wiring it to the input

In the lab, SearchBox.jsx calls run on every keystroke and puts the result in the address, and page.jsx reads q back from searchParams on the server. The input keeps its own draft, so typing isn't interrupted, and follows the URL when something else changes it:

JSX
const current = searchParams.get("q") ?? "";
const [draft, setDraft] = useState(current);
const [seen, setSeen] = useState(current);

if (current !== seen) {
  setSeen(current);
  if (current !== draft.trim()) setDraft(current);
}

function handleChange(event) {
  setDraft(event.target.value);
  const query = run({ query: searchParams.toString(), text: event.target.value });
  router.replace(query ? `${pathname}?${query}` : pathname);
}

Three choices matter here:

  • router.replace, not push. Typing "forms" with push would add five history entries, and Back would step through "form", "for", "fo"… one letter at a time. replace changes the address without adding an entry, as Beginner Day 3 recommended for typing.
  • A draft in state. The URL holds the trimmed query, so if the input read its value straight from the URL, typing a space between two words would vanish at once.
  • Following the URL. When q changes and isn't just our own trimmed draft coming back, as when Back is pressed or someone edits the address, the draft takes the new value. Updating state during render when a value you watch changes is React's pattern for this; it needs no effect.

Predict what the box, the address and the server's line show after you type a b into Search one letter at a time, and after you then edit the address bar to ?q=other&tag=react and press Enter. Then try both.

A search box the URL owns Next.js · 6 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import SearchBox from "./SearchBox.jsx"; export default async function Page({ searchParams }) { const params = await searchParams; const q = typeof params.q === "string" ? params.q : ""; const tag = typeof params.tag === "string" ? params.tag : ""; return ( <main> <h1>The URL Owns Shareable Filters</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <SearchBox /> <p role="status"> The server read q={JSON.stringify(q)} tag={JSON.stringify(tag)} </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useState } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { run } from "@/lib/contract.js"; // The URL owns the filter; the input keeps a draft so typing stays smooth. // Each keystroke replaces the address (no history entry per letter). When // the URL changes some other way, such as Back or an edited address, the // draft follows it. export default function SearchBox() { const router = useRouter(); const pathname = usePathname(); const searchParams = useSearchParams(); const current = searchParams.get("q") ?? ""; const [draft, setDraft] = useState(current); const [seen, setSeen] = useState(current); if (current !== seen) { setSeen(current); // Our own replace gives back the trimmed draft; anything else is news. if (current !== draft.trim()) setDraft(current); } function handleChange(event) { setDraft(event.target.value); const query = run({ query: searchParams.toString(), text: event.target.value }); router.replace(query ? `${pathname}?${query}` : pathname); } return ( <label> Search <input value={draft} onChange={handleChange} /> </label> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ query, text }) { const params = new URLSearchParams(query); if (text.trim()) params.set("q", text.trim()); else params.delete("q"); return params.toString(); } export const examples = [ [{ query: "tag=react", text: "a & b" }, "tag=react&q=a+%26+b"], [{ query: "q=old&tag=react", text: "" }, "tag=react"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction

After typing, the box says a b, keeps focus, and the server read q="a b"; the address is /?q=a+b. After editing the address, the box says other and the server read q="other" tag="react".

An earlier version of this lab gave the input key={current} and defaultValue, so it would follow the URL. But current changes on every keystroke, so React replaced the input after the first letter: focus was lost and only f of "forms" arrived. A key that changes while someone types is always a bug.

The failure to avoid

Building ?q= with string concatenation loses other filters and mishandles ampersands. An input that reads only defaultValue doesn't update when Back changes the URL, and one that is remounted to fix that loses focus on every keystroke.

Trace {"query": "tag=react&q=old", "text": " "}: what does run return, and what will the server render for that address?

Exercise

Extend the contract

Reset page to 1 by removing the page parameter whenever the search changes. Preserve tag.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"query": "tag=react&page=4", "text": "forms"} must return "tag=react&q=forms".
Your working space Next.js · 6 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import SearchBox from "./SearchBox.jsx"; export default async function Page({ searchParams }) { const params = await searchParams; const q = typeof params.q === "string" ? params.q : ""; const tag = typeof params.tag === "string" ? params.tag : ""; return ( <main> <h1>The URL Owns Shareable Filters</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <SearchBox /> <p role="status"> The server read q={JSON.stringify(q)} tag={JSON.stringify(tag)} </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } "use client"; import { useState } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { run } from "@/lib/contract.js"; // The URL owns the filter; the input keeps a draft so typing stays smooth. // Each keystroke replaces the address (no history entry per letter). When // the URL changes some other way, such as Back or an edited address, the // draft follows it. export default function SearchBox() { const router = useRouter(); const pathname = usePathname(); const searchParams = useSearchParams(); const current = searchParams.get("q") ?? ""; const [draft, setDraft] = useState(current); const [seen, setSeen] = useState(current); if (current !== seen) { setSeen(current); // Our own replace gives back the trimmed draft; anything else is news. if (current !== draft.trim()) setDraft(current); } function handleChange(event) { setDraft(event.target.value); const query = run({ query: searchParams.toString(), text: event.target.value }); router.replace(query ? `${pathname}?${query}` : pathname); } return ( <label> Search <input value={draft} onChange={handleChange} /> </label> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ query, text }) { const params = new URLSearchParams(query); if (text.trim()) params.set("q", text.trim()); else params.delete("q"); return params.toString(); } export const examples = [ [{ query: "tag=react", text: "a & b" }, "tag=react&q=a+%26+b"], [{ query: "q=old&tag=react", text: "" }, "tag=react"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

A page number belongs to one particular list of results. A new search makes a new list, so the old page number no longer means anything.

Hint 2: a first step

Pagination belongs to the old result set; it should not be carried into a new search.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ query, text }) {
  const params = new URLSearchParams(query);
  if (text.trim()) params.set("q", text.trim());
  else params.delete("q");
  params.delete("page");
  return params.toString();
}

params.delete("page") runs on every change of search text, so the reader can't be left on page 4 of a shorter list, which might be empty. tag is untouched because the reader didn't change it. Deleting page only when the text is non-empty would leave a stale page after clearing the search.

Explain it without the code

A reader sends /?tag=react&q=forms to a colleague. Write what the colleague's page shows, and what would be lost if the filter lived only in React state.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.