Skip to content

Search Params

The Course
•
25 min study

The part of an address after ? is the query string: /?day=2 means "the home page, with day set to 2". It's the natural place for filters, sorting and searches: the address can be bookmarked, shared and reloaded, and the back button undoes a filter.

Filter with the URL Next.js · 5 files
import Link from "next/link"; import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <nav> <Link href="/">Topics</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { getTopics } from "@/lib/topics.js"; // /?day=2 shows Day 2's topics. searchParams holds the part after the "?". export default async function HomePage({ searchParams }) { const { day } = await searchParams; const topics = await getTopics(); const shown = day ? topics.filter((topic) => topic.day === Number(day)) : topics; return ( <main> <h1>Topics</h1> <p> Show: <Link href="/">All</Link> · <Link href="/?day=1">Day 1</Link> ·{" "} <Link href="/?day=2">Day 2</Link> · <Link href="/?day=3">Day 3</Link> </p> <ul> {shown.map((topic) => ( <li key={topic.slug}> <Link href={`/topics/${topic.slug}`}>{topic.title}</Link> <span className="muted">· {topic.minutes} min</span> </li> ))} </ul> <p className="muted">{shown.length} of {topics.length} topics</p> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } nav a[aria-current="page"] { font-weight: 700; text-decoration: none; color: #1c2430; } import { notFound } from "next/navigation"; import { getTopic } from "@/lib/topics.js"; export default async function TopicPage({ params }) { const { slug } = await params; const topic = await getTopic(slug); if (!topic) notFound(); return ( <main> <h1>{topic.title}</h1> <p>{topic.summary}</p> <p className="muted"> Day {topic.day} · {topic.minutes} minutes </p> </main> ); } // Pretend database of topics, looked up by their slug: the part of the URL // that names them. const topics = [ { slug: "routing", title: "Routing", day: 1, minutes: 20, summary: "Folders become pages." }, { slug: "layouts", title: "Layouts", day: 1, minutes: 20, summary: "Shared parts that wrap pages." }, { slug: "server-components", title: "Server components", day: 2, minutes: 20, summary: "Components that run on the server." }, { slug: "client-components", title: "Client components", day: 2, minutes: 20, summary: "Components that respond in the browser." }, { slug: "dynamic-routes", title: "Dynamic routes", day: 3, minutes: 25, summary: "One file for many pages." }, ]; const wait = () => new Promise((resolve) => setTimeout(resolve, 100)); export async function getTopics() { await wait(); return topics; } export async function getTopic(slug) { await wait(); return topics.find((topic) => topic.slug === slug) ?? null; }
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.

Follow Day 2 and Day 3, then press the address bar's back button. Try typing /?day=9.

searchParams

JavaScript
export default async function HomePage({ searchParams }) {
  const { day } = await searchParams;
  …
}

Pages receive searchParams as well as params. Like params, it's a promise. Its values are strings: /?day=2 gives "2", not 2, so the page turns it into a number with Number(day) before comparing. A key that isn't in the address is undefined, which is how / shows every topic.

The filtering happens on the server: the browser only receives the topics it shows:

JavaScript
const shown = day ? topics.filter((topic) => topic.day === Number(day)) : topics;
JSX
<Link href="/?day=2">Day 2</Link>

A filter is just a link to the same page with a different query string.

Predict

What does /?day=two show?

Check your prediction

0 of 5 topics. Number("two") is NaN, and no topic's day equals NaN. Values from the URL come from the reader, so a page should cope with anything. Here, an empty list is a reasonable answer.

Exercise

Longest first

Add a Longest first link that sorts the shown topics by minutes, longest first, using ?sort=minutes. It should keep the day filter: on /?day=1, it goes to /?day=1&sort=minutes.

Your working space Next.js · 5 files
import Link from "next/link"; import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <nav> <Link href="/">Topics</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { getTopics } from "@/lib/topics.js"; // /?day=2 shows Day 2's topics. searchParams holds the part after the "?". export default async function HomePage({ searchParams }) { const { day } = await searchParams; const topics = await getTopics(); const shown = day ? topics.filter((topic) => topic.day === Number(day)) : topics; return ( <main> <h1>Topics</h1> <p> Show: <Link href="/">All</Link> · <Link href="/?day=1">Day 1</Link> ·{" "} <Link href="/?day=2">Day 2</Link> · <Link href="/?day=3">Day 3</Link> </p> <ul> {shown.map((topic) => ( <li key={topic.slug}> <Link href={`/topics/${topic.slug}`}>{topic.title}</Link> <span className="muted">· {topic.minutes} min</span> </li> ))} </ul> <p className="muted">{shown.length} of {topics.length} topics</p> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } nav a[aria-current="page"] { font-weight: 700; text-decoration: none; color: #1c2430; } import { notFound } from "next/navigation"; import { getTopic } from "@/lib/topics.js"; export default async function TopicPage({ params }) { const { slug } = await params; const topic = await getTopic(slug); if (!topic) notFound(); return ( <main> <h1>{topic.title}</h1> <p>{topic.summary}</p> <p className="muted"> Day {topic.day} · {topic.minutes} minutes </p> </main> ); } // Pretend database of topics, looked up by their slug: the part of the URL // that names them. const topics = [ { slug: "routing", title: "Routing", day: 1, minutes: 20, summary: "Folders become pages." }, { slug: "layouts", title: "Layouts", day: 1, minutes: 20, summary: "Shared parts that wrap pages." }, { slug: "server-components", title: "Server components", day: 2, minutes: 20, summary: "Components that run on the server." }, { slug: "client-components", title: "Client components", day: 2, minutes: 20, summary: "Components that respond in the browser." }, { slug: "dynamic-routes", title: "Dynamic routes", day: 3, minutes: 25, summary: "One file for many pages." }, ]; const wait = () => new Promise((resolve) => setTimeout(resolve, 100)); export async function getTopics() { await wait(); return topics; } export async function getTopic(slug) { await wait(); return topics.find((topic) => topic.slug === slug) ?? null; }
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

The sort order is one more value in the URL, read on the server just like day. A link replaces the whole query string, so a link that should keep the day filter has to write day back in.

Hint 2: a first step

Make the sorting work before you add the link: read sort, and when it's "minutes", show a sorted copy (toSorted). Type /?day=1&sort=minutes into the address bar to check it. Then add a link, and test it from both / and /?day=1.

Show one solution
JavaScript
const { day, sort } = await searchParams;
const topics = await getTopics();
const filtered = day ? topics.filter((topic) => topic.day === Number(day)) : topics;
const shown = sort === "minutes" ? filtered.toSorted((a, b) => b.minutes - a.minutes) : filtered;
JSX
<p>
  <Link href={day ? `/?day=${day}&sort=minutes` : "/?sort=minutes"}>Longest first</Link>
</p>

The choice lives only in the address, so reloading or sharing /?day=1&sort=minutes gives the same list. toSorted returns a new array; sort would reorder the array getTopics() returned, in place. The link writes day back in because a plain href="/?sort=minutes" would drop the filter.

Forms that set it

Links suit a few fixed choices. For something the reader types or picks, a form can write the query string. Form from next/form is a form whose fields become the query string of its action address:

JSX
import Form from "next/form";

<Form action="/">
  <input name="q" />
  <button>Search</button>
</Form>

Submitting it with rout goes to /?q=rout, without reloading the page, like a Link. The server page reads q as usual. A plain <form> does the same navigation, but reloads the whole page on a real site.

Exercise

A day picker

Replace the day links with a form: a Day select (All, 1, 2, 3) and a Show button, that goes to /?day=2. The select should show the current day.

Your working space Next.js · 5 files
import Link from "next/link"; import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <nav> <Link href="/">Topics</Link> </nav> </header> {children} </body> </html> ); } import Link from "next/link"; import { getTopics } from "@/lib/topics.js"; // /?day=2 shows Day 2's topics. searchParams holds the part after the "?". export default async function HomePage({ searchParams }) { const { day } = await searchParams; const topics = await getTopics(); const shown = day ? topics.filter((topic) => topic.day === Number(day)) : topics; return ( <main> <h1>Topics</h1> <p> Show: <Link href="/">All</Link> · <Link href="/?day=1">Day 1</Link> ·{" "} <Link href="/?day=2">Day 2</Link> · <Link href="/?day=3">Day 3</Link> </p> <ul> {shown.map((topic) => ( <li key={topic.slug}> <Link href={`/topics/${topic.slug}`}>{topic.title}</Link> <span className="muted">· {topic.minutes} min</span> </li> ))} </ul> <p className="muted">{shown.length} of {topics.length} topics</p> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } nav a[aria-current="page"] { font-weight: 700; text-decoration: none; color: #1c2430; } import { notFound } from "next/navigation"; import { getTopic } from "@/lib/topics.js"; export default async function TopicPage({ params }) { const { slug } = await params; const topic = await getTopic(slug); if (!topic) notFound(); return ( <main> <h1>{topic.title}</h1> <p>{topic.summary}</p> <p className="muted"> Day {topic.day} · {topic.minutes} minutes </p> </main> ); } // Pretend database of topics, looked up by their slug: the part of the URL // that names them. const topics = [ { slug: "routing", title: "Routing", day: 1, minutes: 20, summary: "Folders become pages." }, { slug: "layouts", title: "Layouts", day: 1, minutes: 20, summary: "Shared parts that wrap pages." }, { slug: "server-components", title: "Server components", day: 2, minutes: 20, summary: "Components that run on the server." }, { slug: "client-components", title: "Client components", day: 2, minutes: 20, summary: "Components that respond in the browser." }, { slug: "dynamic-routes", title: "Dynamic routes", day: 3, minutes: 25, summary: "One file for many pages." }, ]; const wait = () => new Promise((resolve) => setTimeout(resolve, 100)); export async function getTopics() { await wait(); return topics; } export async function getTopic(slug) { await wait(); return topics.find((topic) => topic.slug === slug) ?? null; }
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 form whose fields go into the URL is another way to write the query string. A select named day sends ?day=2, which the page already reads, so the page's filtering code doesn't change.

Hint 2: a first step

Put a select named day (options 1, 2, 3) and a Show button inside <Form action="/">, from next/form. Choose 2 and press Show: the address should become /?day=2. Then add All, and make the select start on the current day.

Show one solution
JavaScript
import Form from "next/form";
JSX
<Form action="/">
  <label>
    Day{" "}
    <select name="day" defaultValue={day ?? ""}>
      <option value="">All</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
  </label>{" "}
  <button>Show</button>
</Form>

Form navigates to / with each field as a search param, so the page code doesn't change. All sends ?day= with an empty value, and the page treats "" like no day, because "" is falsy. defaultValue sets which option the select starts on; value would lock it to the URL's day unless you also kept state and an onChange.

Going further: a key given twice

Nothing stops a reader typing /?day=1&day=2. When a key is repeated, its value is an array of strings, ["1", "2"], instead of one string. Here Number(["1", "2"]) is NaN, so the page shows no topics, which is harmless.

It matters as soon as you call a string method. A search page that runs q.toLowerCase() crashes on /?q=a&q=b with q.toLowerCase is not a function, because arrays don't have toLowerCase. Pick one value first:

JavaScript
const { q } = await searchParams;
// ?q=a&q=b gives ["a", "b"]: use the first. No q at all gives "".
const query = Array.isArray(q) ? q[0] : (q ?? "");

The next lesson's search page does exactly this.

Was this article helpful?

Your response is saved on this device.