Next.jsMedium
How do you handle query parameters in Next.js?
On the server, read the searchParams prop of page.tsx, which is a Promise you must await. On the client, use the useSearchParams() hook and update the URL with router.push/replace or <Link>.
Server: the searchParams prop
- Only
page.tsxreceives it; layouts do not, because a layout is shared across URLs and does not re-render on query changes. - Values are
string | string[] | undefined, so normalize them. - Reading
searchParamsmakes that part of the page depend on the request. With Cache Components, put the reading component inside<Suspense>so the rest of the page stays in the static shell. - With Partial Prefetching,
<Link prefetch={true}>can resolvesearchParamsat prefetch time, so cached results for that URL arrive before the click.
Client: useSearchParams()
- Returns a read-only
URLSearchParams. - Copy it to change values:
new URLSearchParams(searchParams). - A component using it during prerendering needs a
<Suspense>boundary above it, or the build reports "Missing Suspense boundary with useSearchParams".
Route Handlers
Read request.nextUrl.searchParams (or new URL(request.url).searchParams).
Tips
- Validate with Zod; query strings are user input.
- Use
replacefor filters typed live, so history is not flooded. - Treat the URL as the source of truth for shareable state.
Code example
tsx
1// app/products/page.tsx2import { Suspense } from "react";3import { z } from "zod";45const Query = z.object({6 q: z.string().default(""),7 page: z.coerce.number().int().min(1).default(1),8});910async function Results({ searchParams }: { searchParams: PageProps<"/products">["searchParams"] }) {11 const { q, page } = Query.parse(await searchParams);12 const res = await fetch(`https://api.example.com/products?q=${encodeURIComponent(q)}&page=${page}`);13 const products: { id: string; name: string }[] = await res.json();14 return <ul>{products.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;15}1617export default function ProductsPage(props: PageProps<"/products">) {18 return (19 <main>20 <h1>Products</h1> {/* static shell */}21 <Suspense fallback={<p>Loading results…</p>}>22 <Results searchParams={props.searchParams} />23 </Suspense>24 </main>25 );26}2728// Client: const q = useSearchParams().get("q");29// Route Handler: const q = request.nextUrl.searchParams.get("q");
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.