Explain it simply
Search params in plain language
The part of a URL after the ? (the query string) is like the settings written on a recipe card: anyone holding the card can recreate the exact same view. Send /notes?q=hooks&page=2 to a friend and they land on page 2 of the hooks results too.
Component state is more like settings you keep in your head: refresh the page and they are gone, and you cannot hand them to anyone else.
Problem → Why → Solution
The problem: a filter that trusts the URL
The first version kept the search keyword in useState, so a refresh lost it and the back button did not undo a filter. Moving it into the URL was the right call, but the code now passes URL values straight to the database. ?page=abc produces a NaN offset and the query fails, ?page=-3 produces a negative skip, and ?sort=passwordHash lets a visitor sort by any column they can name.
export default async function NotesPage({ searchParams }) {
const { q, page, sort } = await searchParams;
const notes = await db.note.findMany({
where: { title: { contains: q } },
skip: (page - 1) * 20, // "abc" - 1 is NaN
orderBy: { [sort]: "desc" }, // any column the visitor types
});
return <NoteList notes={notes} />;
}A URL is user input
You may have generated the link yourself, but anyone can edit the address bar, and bots send random queries all day. Treat every search param like a form field: parse it in one place, check it against allowed values, and fall back to a default when it does not fit.
Core concept: read from the URL, normalise once
In the App Router, page components receive a searchParams prop. Since Next.js 15 it is a Promise you await; in Next.js 14 it was a plain object. Each value is string | string[] | undefined: ?tag=a&tag=b gives an array, and a missing key gives undefined. Layouts do not receive searchParams at all, because a layout is not re-rendered on every navigation.
The key habit is to normalise once, at the boundary. Turn the raw object into a typed Filters object with defaults: trim q and cap its length, check page with Number.isInteger and fall back to 1 when it is below 1, and match enums such as sort or difficulty against an allowlist. The data function accepts only Filters, so nothing below it ever sees a raw string.
Because searchParams values are only known at request time, reading them makes the page render dynamically. That is expected, since the results must change with the query. On the browser side you only change the URL: navigate with a Link or router.replace and Next.js re-renders the page on the server with the new query.
You also have to choose which state belongs in the URL. State that someone opening a shared link should see the same way (keyword, filters, sort, page) belongs there. Short-lived UI state, such as whether a dropdown is open or an input is focused, stays in component state, because putting it in the URL clutters links and fills the history.
| Tool | Where | Used for |
|---|---|---|
| searchParams prop | Server page | reading the query to load data |
| useSearchParams() | Client Component | reading the current query in UI |
| router.replace(url) | Client Component | changing the URL without a new history entry |
| <Link href> | Either | pagination and filter links |
- URL holds state: ?q=next&page=2
- Page awaits searchParams
- Parse once into safe Filters
- Data function takes Filters only
- Links and inputs write a new URL
The UI never changes the state directly; it changes the URL, and the server rebuilds the page from the new URL.
General pattern
type SearchParams = Promise<{ [key: string]: string | string[] | undefined }>;
export default async function Page({ searchParams }: { searchParams: SearchParams }) {
const filters = parseFilters(await searchParams); // validate once, with defaults
const data = await getData(filters); // never sees raw strings
return <View data={data} filters={filters} />;
}Await searchParams, apply defaults and validation inside one parse function, and pass only the resulting typed object to the data layer.
Worked example: a notes page with search and pagination
This page reads q and page from the URL. Search params are not always plain strings: a key can repeat, and a user can type anything, such as page=2.5. So the code handles repeated keys with first() and accepts only positive whole page numbers.
// app/notes/page.tsx
import { searchNotes } from "@/lib/data/notes";
import { NoteList } from "./note-list";
type SearchParams = Promise<{ [key: string]: string | string[] | undefined }>;
function first(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value[0] : value;
}
export default async function NotesPage({
searchParams,
}: {
searchParams: SearchParams;
}) {
const params = await searchParams;
const query = (first(params.q) ?? "").trim().slice(0, 100);
const requestedPage = Number(first(params.page) ?? "1");
const isValidPage = Number.isInteger(requestedPage) && requestedPage > 0;
const page = isValidPage ? requestedPage : 1;
const notes = await searchNotes({ query, page });
return <NoteList notes={notes} query={query} page={page} />;
}Code breakdown
- Honest param types
type SearchParams = Promise<{ [key: string]: string | string[] | undefined }>;It matches what Next.js really passes: a Promise whose values may be a string, an array of strings, or undefined.
- Repeated keys
return Array.isArray(value) ? value[0] : value;A URL such as ?q=a&q=b yields an array; taking the first value stops .trim() from crashing on an array.
- Clean the keyword
const query = (first(params.q) ?? "").trim().slice(0, 100);Missing becomes an empty string, whitespace is trimmed, and the length is capped at 100 so a huge input cannot burden the database.
- Validate the page
const isValidPage = Number.isInteger(requestedPage) && requestedPage > 0;Number("abc") is NaN and Number("2.5") is 2.5; only whole numbers above zero survive, and everything else becomes page 1.
- Only clean values go down
const notes = await searchNotes({ query, page });The data function receives only normalised values, so validation lives in exactly one place.
/notes?q=next&page=2 shows the second page of notes matching "next". /notes?page=abc, /notes?page=-3 and /notes?page=2.5 all fall back to page 1, and /notes?q=a&q=b searches for "a".Updating the URL from a Client Component
The search box reacts to typing, so it is a Client Component. Its job is not to load data but to change the URL. It debounces so the server is not called on every keystroke, and uses replace instead of push so the history is not flooded with entries. It also deletes the page param, because a new search should start at page 1.
"use client";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useRef } from "react";
export function SearchBox() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
function onChange(value: string) {
clearTimeout(timer.current);
timer.current = setTimeout(() => {
const params = new URLSearchParams(searchParams.toString());
if (value.trim()) params.set("q", value.trim());
else params.delete("q");
params.delete("page"); // a new search starts at page 1
router.replace(`${pathname}?${params.toString()}`);
}, 300);
}
return (
<input
type="search"
aria-label="Search notes"
defaultValue={searchParams.get("q") ?? ""}
onChange={(e) => onChange(e.target.value)}
/>
);
}useSearchParams and Suspense
In a statically rendered route, a component that calls useSearchParams without a surrounding <Suspense> boundary can trigger a build warning or error. This page already reads searchParams and is dynamic, but check the useSearchParams docs for your version.
In real projects
In real projects
State in the URL pays off wherever a view must be reopenable. Paste one link into a support ticket and the agent sees exactly the filters the customer was looking at.
- Shops use filters such as ?category=shoes&size=42&sort=price-asc that can be bookmarked and discovered by search engines.
- Admin tables keep ?status=pending&page=3 in the URL, so opening a record and pressing Back returns to page 3.
- Analytics dashboards share a date range like ?from=2026-01-01&to=2026-01-31 as a link in a meeting.
In production, most teams keep the parse function in one file such as lib/filters.ts, and the page, any Route Handler and the tests all share it. A ?page=abc arriving through an API endpoint is then handled exactly like one arriving through the page. Analytics tools can also read which filters people use straight from the URLs.
Common mistakes
Common search param mistakes
Passing URL values straight into a query
Using a sort column, page offset or filter field from the URL unchecked leads to NaN errors, huge queries and exposure of columns you never meant to sort by. Use allowlists and number checks.
Assuming every value is a string
Send ?q=a&q=b and params.q becomes an array, so params.q.trim() crashes the page with 'trim is not a function'. Type values as string | string[] | undefined and handle them with a helper such as first().
Not resetting the page when the filter changes
Typing a new keyword while on page 7 shows an empty list, because the new results have no page 7. Delete the page param whenever a filter changes.
Calling router.push on every keystroke
Each letter adds a history entry, so Back must be pressed ten times, and each one fires a request. Debounce and use router.replace.
Best practices
Best practices
- Keep URL keys short and stable (q, page, sort); renaming them breaks links people have bookmarked.
- Leave defaults out of the URL so /notes and /notes?page=1 do not become two copies of one page.
- Write an allowlist for every sort and filter field, and quietly fall back to the default for anything outside it.
- Cap the page size on the server instead of trusting something like ?limit=100000.
Mini challenge
Mini challenge: parseFilters and toQueryString
For a tutorial list page, write parseFilters, which turns raw search params into typed Filters, and toQueryString, which turns Filters back into a URL query string, leaving default values out of the URL.
- Take the first value when a key is repeated
- Trim q and cap it at 50 characters
- difficulty must be beginner, intermediate or advanced, otherwise "all"
- page must be a positive integer, otherwise 1
- toQueryString leaves out defaults (empty q, all, page 1)
type RawParams = { [key: string]: string | string[] | undefined };
type Difficulty = "all" | "beginner" | "intermediate" | "advanced";
type Filters = { q: string; difficulty: Difficulty; page: number };
const LEVELS = ["beginner", "intermediate", "advanced"] as const;
function parseFilters(raw: RawParams): Filters {
// TODO: take the first value when a key is repeated
// TODO: q -> trimmed, at most 50 characters
// TODO: difficulty -> one of LEVELS, otherwise "all"
// TODO: page -> positive integer, otherwise 1
}
function toQueryString(filters: Filters): string {
// TODO: use URLSearchParams and skip default values
}
// TODO: print the result for a normal input and a few hostile onesExpected: The first sample prints ?q=hooks&difficulty=beginner&page=2; "expert" and "-1" fall back to defaults, ["react", "vue"] becomes "react", and page 2.5 becomes 1.
Show hint
You can check membership with (LEVELS as readonly string[]).includes(value), or write a type guard that returns value is Difficulty. URLSearchParams.toString() handles the encoding for you.
Show solution
type RawParams = { [key: string]: string | string[] | undefined };
type Difficulty = "all" | "beginner" | "intermediate" | "advanced";
type Filters = { q: string; difficulty: Difficulty; page: number };
const LEVELS = ["beginner", "intermediate", "advanced"] as const;
const firstValue = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v);
function isLevel(value: string | undefined): value is (typeof LEVELS)[number] {
return (LEVELS as readonly (string | undefined)[]).includes(value);
}
function parseFilters(raw: RawParams): Filters {
const q = (firstValue(raw.q) ?? "").trim().slice(0, 50);
const level = firstValue(raw.difficulty);
const n = Number(firstValue(raw.page) ?? "1");
return {
q,
difficulty: isLevel(level) ? level : "all",
page: Number.isInteger(n) && n > 0 ? n : 1,
};
}
function toQueryString(filters: Filters): string {
const params = new URLSearchParams();
if (filters.q) params.set("q", filters.q);
if (filters.difficulty !== "all") params.set("difficulty", filters.difficulty);
if (filters.page !== 1) params.set("page", String(filters.page));
const text = params.toString();
return text ? `?${text}` : "(no query)";
}
const samples: RawParams[] = [
{ q: " hooks ", difficulty: "beginner", page: "2" },
{ difficulty: "expert", page: "-1" },
{ q: ["react", "vue"], page: "2.5" },
{ q: "server actions", difficulty: "advanced" },
];
for (const raw of samples) {
const filters = parseFilters(raw);
console.log(JSON.stringify(filters), "->", toQueryString(filters));
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Keeping search, filter and page state in the URL makes refresh, Back and shared links work.
- Since Next.js 15, searchParams is a Promise and each value is string | string[] | undefined.
- Normalise raw values in one place with allowlists, integer checks and defaults.
- On the client, only change the URL: debounce plus router.replace, and reset the page when a filter changes.
Next.js — Fetching Data — Next.js
Next.js — Fetching Data — Next.js