Lesson 7 of 27Routing in depth
Search Params and URL State
Keep filters, sort, search and pagination in the URL so pages are shareable, survive refresh, and render on the server in Next.js 16.
A product manager filters the orders table to "refunded, last 30 days, sorted by amount", copies the link into Slack, and asks why this customer was refunded twice. Her teammate opens the link and sees the unfiltered table, because the filters lived in useState. Refresh loses them too, and the back button skips right past them. Putting this kind of state in the URL fixes all three problems at once, and in Next.js it also lets the server render the filtered results directly. This lesson covers reading search params on the server and client, writing them without breaking history or performance, validating them like the user input they are, and the patterns that come up in every dashboard you will build.
What belongs in the URL
The URL is a state store with special properties: it is shareable, bookmarkable, survives refresh, works with back and forward, and is visible to the server on the first request. That makes it the right home for state that describes what the user is looking at:
- search queries, filters, sort order, page number or cursor
- the selected tab, the open item in a master-detail view
- date ranges, map position and zoom
It is the wrong home for state that describes what the user is doing right now: whether a dropdown is open, a half-typed comment, hover state, a drag in progress. It is also wrong for anything secret (URLs end up in logs, browser history and Referer headers) and for large blobs. Keep URLs short and readable.
A useful test: "If I sent this link to a colleague, should they see this?" If yes, it goes in the URL.
Reading search params on the server
A page receives searchParams as a prop. Like params, it is a Promise, and each value is string | string[] | undefined: a key that appears once is a string, a repeated key is an array, a missing key is undefined. It is a plain object, not a URLSearchParams.
Only pages get it. Layouts do not, because a layout stays mounted across navigations and would show stale values. If a layout needs the query, read it in a Client Component with useSearchParams().
With Cache Components, searchParams is runtime data: it cannot be known at build time. So the read must sit inside a <Suspense> boundary, and the trick from the dynamic routes lesson applies again: pass the Promise down, await it deep.
import { Suspense } from "react";
import { OrdersTable } from "./_components/OrdersTable";
import { Filters } from "./_components/Filters";
export default function OrdersPage(props: PageProps<"/orders">) {
return (
<main>
<h1>Orders</h1> {/* static shell */}
<Filters /> {/* client component, reads useSearchParams */}
<Suspense fallback={<TableSkeleton />}>
<OrdersTable searchParams={props.searchParams} />
</Suspense>
</main>
);
}The heading and filter bar are in the prerendered shell. Only the table waits for the URL.
Parse at the edge, then trust the type
Search params are user input. Anyone can visit /orders?page=-3&sort=DROP TABLE&status=refunded&status=pending. Do not scatter Number(sp.page) through your components. Parse once, at the top of the server component that reads them, into a typed object with safe defaults. Zod is the common choice:
import { z } from "zod";
const one = (v: unknown) => (Array.isArray(v) ? v[0] : v);
const many = (v: unknown) => (v === undefined ? [] : Array.isArray(v) ? v : [v]);
export const filtersSchema = z.object({
q: z.preprocess(one, z.string().trim().max(100)).catch(""),
page: z.preprocess(one, z.coerce.number().int().min(1)).catch(1),
sort: z.preprocess(one, z.enum(["date", "amount"])).catch("date"),
status: z.preprocess(many, z.array(z.enum(["paid", "refunded", "pending"]))).catch([]),
});
export type Filters = z.infer<typeof filtersSchema>;.catch() means a bad value falls back to the default instead of throwing. For a filter page that is usually right: a mangled link should still show a sensible page, not an error. For a param that identifies a resource, prefer notFound().
The same logic without the library, so you can run it and see each rule fire:
Press Run (⌘ Enter) to see what happens.Note page: ["2", "9"]: someone added ?page=2&page=9. Taking the first value is a decision you make once, here, rather than a crash somewhere deep in the table.
Writing search params from the client
Reading in the browser uses useSearchParams(), which you met in Layouts and Navigation. It returns a read-only URLSearchParams. To change the URL, copy it, edit the copy, and navigate:
"use client";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
export function SortSelect() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
function onChange(sort: string) {
const next = new URLSearchParams(searchParams.toString());
next.set("sort", sort);
next.delete("page"); // a new sort starts at page 1
router.push(`${pathname}?${next.toString()}`, { scroll: false });
}
return (
<select value={searchParams.get("sort") ?? "date"} onChange={(e) => onChange(e.target.value)}>
<option value="date">Newest</option>
<option value="amount">Amount</option>
</select>
);
}Three details carry most of the weight:
next.delete("page"). Changing a filter or sort while on page 7 and landing on an empty page 7 is one of the most common bugs in list UIs. Any change that alters the result set resets pagination.scroll: false. By default navigation scrolls to the top. For a filter change on the same page, that is jarring.pushorreplace.pushadds a history entry, so back undoes the change.replaceoverwrites the current entry. Usepushfor deliberate, discrete choices (a sort, a filter chip, the next page) andreplacefor continuous input (each keystroke in a search box, a slider). Nobody wants to press back fourteen times to undo a search for "refunded".
What a navigation actually costs
router.push("/orders?sort=amount") is a real navigation. The page's searchParams changed, so Next.js requests a new RSC payload from the server, the page re-renders there, and the result streams in. Shared layouts stay mounted and client state in them is kept. That round trip is what you want when the server does the filtering.
If the data is already in the browser (a small list you filter client-side), you can skip the server entirely. window.history.pushState and replaceState are integrated with the Next.js router: they update the URL, and useSearchParams() and usePathname() re-render with the new values, but no server request is made. This is what people mean by a shallow update.
The Suspense rule for useSearchParams
On a prerendered route, the URL query is not known at build time. A Client Component calling useSearchParams() will render on the client only, up to the nearest <Suspense> boundary. If there is no boundary, next build fails with a missing Suspense error. In next dev everything renders on demand, so this often only appears in CI. Wrap the component that reads the query in <Suspense>, with a fallback the same size as the real control.
A search box that does not hammer the server
Typing "refunded" fires eight change events. Navigating on each one means eight server renders, and results that flicker through "r", "re", "ref". Debounce the URL update and show a pending state with a transition:
"use client";
import { useEffect, useRef, useTransition } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
export function SearchBox() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
function onInput(value: string) {
clearTimeout(timer.current);
timer.current = setTimeout(() => {
const next = new URLSearchParams(searchParams.toString());
if (value) next.set("q", value);
else next.delete("q");
next.delete("page");
startTransition(() => router.replace(`${pathname}?${next}`, { scroll: false }));
}, 300);
}
return (
<label>
Search
<input
type="search"
defaultValue={searchParams.get("q") ?? ""}
onChange={(e) => onInput(e.target.value)}
aria-busy={isPending}
/>
</label>
);
}The input is uncontrolled (defaultValue). If you control it from the URL, every keystroke waits for the debounced navigation before the letter appears. Local typing stays instant; the URL catches up 300 ms after the last key.
Navigations run inside a transition, so React keeps showing the old results while the new ones load, instead of flashing the Suspense fallback. If you want the skeleton on each new query, give the boundary a key: <Suspense key={filters.q} fallback={...}>. A new key is a new boundary, which shows its fallback again.
Each keystroke updates the input instantly (uncontrolled) and restarts the 300 ms timer.
next/form: search without client code
For a plain search form, you may not need any of the above. <Form> from next/form with a string action behaves like an HTML GET form: inputs become search params on the target URL. On top of that, Next.js prefetches the target route's shared UI when the form is visible, and submits with a client-side navigation instead of a full reload.
import Form from "next/form";
export function HeaderSearch() {
return (
<Form action="/search">
<input name="q" aria-label="Search" />
<button type="submit">Search</button>
</Form>
);
}Submitting navigates to /search?q=.... It works before JavaScript loads (progressive enhancement), and it can be a Server Component. action="" submits to the current route. Use it for header searches and simple filter forms; reach for the hook-based approach when you need live updates while typing.
nuqs: typed URL state
On a dashboard with eight filters, the copy-edit-push dance gets repetitive and stringly typed. Many teams use nuqs, a small library that gives you a useState-like hook backed by the URL:
"use client";
import { parseAsInteger, useQueryState } from "nuqs";
export function Pager() {
const [page, setPage] = useQueryState(
"page",
parseAsInteger.withDefault(1).withOptions({ history: "push", shallow: false }),
);
return <button onClick={() => setPage(page + 1)}>Next page ({page + 1})</button>;
}page is a number, never a string. The parser handles bad input, and setting the default value removes the key from the URL, keeping links clean. Two options matter: by default nuqs updates are shallow (client only, no server render), so set shallow: false when a Server Component reads that param; and history chooses push or replace. nuqs also ships server-side helpers that parse searchParams with the same parsers, so client and server agree on types. You add an adapter (NuqsAdapter) in the root layout. Check the nuqs docs for the current helper names and rate-limiting options, which have changed between versions.
Pagination, canonical URLs and other details
- Offset or cursor.
?page=3is simple and lets users jump to any page, but gets slow on big tables and shifts when rows are inserted.?after=ord_8f2k(a cursor) is stable and fast, but only supports next and previous. Pick per screen, and keep it in the URL either way. - Drop defaults.
/ordersand/orders?page=1&sort=dateshow the same thing. Remove params equal to their default when you write the URL, so there is one link per view. - Keep a stable order.
?a=1&b=2and?b=2&a=1are different cache keys and different URLs to a search engine. Sorting keys before writing helps caches and analytics. - Canonical tags. For public listing pages, set
alternates.canonicalin metadata to the clean URL so crawlers do not index every filter combination. - Encoding.
URLSearchParamsencodes spaces as+and escapes&and=inside values. Never build query strings with string concatenation of raw user input.
Press Run (⌘ Enter) to see what happens.What does this print?
const p = new URLSearchParams("?q=a+b&tag=x");
p.set("tag", "y");
p.append("tag", "z");
console.log(p.get("q"));
console.log(p.toString());router.push on every keystroke (debounced to 300 ms). What do users complain about?searchParams to app/orders/layout.tsx to highlight the active filter in a sidebar. Why does it not work, and what is the fix?Match each situation to the best tool.
- searchParams prop
- A Promise of the query string as a plain object, passed to pages only. Values are
string | string[] | undefined. - useSearchParams
- A Client Component hook that returns a read-only
URLSearchParamsfor the current URL; needs a Suspense boundary on prerendered routes. - router.replace
- Navigates without adding a history entry. Right for continuous input such as typing.
- shallow update
- Changing the URL without a server render, for example with
window.history.replaceStateor a shallow nuqs setter. - next/form
- A
<Form>component that, with a string action, submits as a GET navigation to search params, with prefetching and progressive enhancement. - nuqs
- A library of type-safe URL state hooks and parsers that work like
useStatebut read and write search params. - open redirect
- A bug where a URL param like
?next=lets an attacker send users from your domain to an external site.