Navigation and Keeping State in the URL
Read search params on the server, build links and pagination that carry state, and wire a filter control that works without JavaScript and gets faster with it — so every view of the catalog has an address you can reload or share.
Contentsand lesson path
On this page
- Why the URL is the state
- Step 1: read search params on the server
- Step 2: links and pagination carry the state
- Step 3: a filter control that degrades gracefully
- What usually goes wrong
- Check your understanding
- Apply it
- Review prompt
Lessons of Next.js App Router & Routing
- Where Routing Happens: Client Routers, File-System Routes and Proxy Concept · 25 min
- Pages, Layouts and Dynamic Segments Worked example · 25 min
- Navigation and Keeping State in the URL Worked example · 20 min
- Loading, Error and Metadata per Route Concept · 20 min
- Lab: A Localized Catalog with Shareable Filters and a Members Area Lab · 30 min
- Check: Draw the Route Map Knowledge check · 10 questions
What you will learn
- Navigate with Link and the router, read route params and search params, and keep filter, sort and pagination state in the URL.
Prerequisites: React Components & State
01. Why the URL is the state
A filtered, sorted, paginated view is a result the learner may want to keep: reload it, send it to a colleague, bookmark it, or go back to it after following a detail link. If that view lives only in component state, the address bar cannot describe it — every one of those actions loses it. If it lives in the query string, the URL is the state, and the page can be rebuilt from the address alone.
That single decision shapes the code: the server reads searchParams to know what to render, links carry the state forward, and controls update the URL instead of updating variables. Navigation in Next.js is built on top of this. Clicking a Link updates the URL in the browser's history (a plain anchor would too, but with a full document load), then asks the server only for the parts of the page that changed, while shared layouts stay mounted and interactive. Get the URL right and both paths — a full reload and an in-app click — lead to the same view.
The app from the previous lesson already links products; this lesson adds sorting, categories and pagination to /catalog, and finishes with a filter control that degrades gracefully. All of it ran on Next.js 16.4.6 with React 19.3.0.
02. Step 1: read search params on the server
export const instant = false;
function first(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value[0] : value;
}
export default async function CatalogPage(props: PageProps<'/catalog'>) {
const params = await props.searchParams;
const category = first(params.category);
const sort = first(params.sort) ?? 'title';
const requested = Number.parseInt(first(params.page) ?? '1', 10);
const products = getProducts(category, sort);
const pageCount = Math.max(1, Math.ceil(products.length / PAGE_SIZE));
const page = Math.min(Math.max(1, requested || 1), pageCount);
const visible = products.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);A page receives searchParams as a prop — a Promise in current Next.js versions, so the server awaits it — and the query string drives every decision: filter, sort, page. The code is defensive on purpose. A parameter can arrive as string, as an array of strings when a name is repeated, or be absent; first() narrows that union. A page number out of range is clamped instead of slicing an empty list. The instant = false export at the top is needed because cacheComponents is on: a page that reads searchParams with no Suspense boundary above it fails the static-shell check that next build runs, and instant = false switches that check off so the route may block until its data is ready. The loading lesson shows the other way out, a loading.tsx fallback that lets the page stream instead.
$ curl -s 'http://localhost:3131/catalog?sort=price-asc' \
| grep -oE '<a href="/catalog/[a-z-]+">[A-Za-z ]*'
$ curl -s 'http://localhost:3131/catalog?category=grinders&sort=price-desc' \
| grep -oE '<a href="/catalog/[a-z-]+">[A-Za-z ]*'<a href="/catalog/french-press">French press
<a href="/catalog/stovetop-espresso">Stovetop espresso maker
<a href="/catalog/workshop-grinder">Workshop grinder
<a href="/catalog/hand-grinder">Hand grinderTwo different query strings, two different lists, straight from the server: £24 before £32, then £129 before £45. Nothing here is client-side — a fresh HTML document answers each address, which is exactly why the address is enough to rebuild the view.
03. Step 2: links and pagination carry the state
function catalogHref(changes: Record<string, string | undefined>): string {
const next = new URLSearchParams();
for (const key of ['category', 'sort', 'page']) {
const value = changes[key];
if (value) next.set(key, value);
}
const query = next.toString();
return query ? `/catalog?${query}` : '/catalog';
}
<nav aria-label="Pages">
{pageCount > 1 &&
Array.from({ length: pageCount }, (_, index) => index + 1).map((n) => (
<Link
key={n}
href={catalogHref({
category,
sort,
page: n === 1 ? undefined : String(n),
})}
aria-current={n === page ? 'page' : undefined}
>
{n}
</Link>
))}
</nav>Every link is built by one helper so the query-string rules live in one place. catalogHref receives the desired parameter values, drops any that are undefined, and URL-encodes the query string cleanly. Page 1 omits page entirely, so the cleanest URL is the one in the address bar. The aria-current="page" attribute tells screen readers which page is current. Sighted users see it only if your CSS styles it (for example with an [aria-current="page"] selector), and that style should not rely on colour alone, as WCAG 2.2 success criterion 1.4.1 (Use of Color) requires.
$ curl -s 'http://localhost:3131/catalog' \
| grep -oE '<a (aria-current="page" )?href="/catalog\?sort[^"]*"'<a aria-current="page" href="/catalog?sort=title"
<a href="/catalog?sort=title&page=2"
<a href="/catalog?sort=title&page=3"04. Step 3: a filter control that degrades gracefully
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
const SORTS = [
{ value: 'title', label: 'Title (A to Z)' },
{ value: 'price-asc', label: 'Price: low to high' },
{ value: 'price-desc', label: 'Price: high to low' },
];
export function FilterBar() {
const router = useRouter();
const searchParams = useSearchParams();
const category = searchParams.get('category');
return (
<form action="/catalog" method="get">
{category && <input type="hidden" name="category" value={category} />}
<label htmlFor="sort">Sort by</label>
<select
id="sort"
name="sort"
defaultValue={searchParams.get('sort') ?? 'title'}
onChange={(event) => {
const next = new URLSearchParams(searchParams.toString());
next.set('sort', event.target.value);
next.delete('page');
router.replace(`/catalog?${next.toString()}`);
}}
>
{SORTS.map((sort) => (
<option key={sort.value} value={sort.value}>
{sort.label}
</option>
))}
</select>
<button type="submit">Apply</button>
</form>
);
}Read the form before the JavaScript. It is a plain HTML form that submits GET to /catalog, so the browser turns the select's name="sort" into a query parameter and navigates — no framework involved. A GET form replaces the whole query string with its own fields, so the hidden category input carries the current filter along; without it, pressing Apply on /catalog?category=grinders with JavaScript off would land on /catalog?sort=… and lose the category. That is the floor every learner gets. The enhancement is the onChange handler: once the component hydrates, changing the option navigates immediately with router.replace, building the next URL from searchParams.toString() so the category survives, and deleting page so a new sort starts from page 1.
Three API details worth remembering. useSearchParams is a Client Component hook — the server reads searchParams from props, as in step 1. The object it returns is read-only: copy it (new URLSearchParams(searchParams.toString())), then set and delete on the copy. And replace rather than push keeps the back button meaningful: choosing three sorts in a row should not cost three back presses to escape.
$ curl -s http://localhost:3131/catalog | grep -oE \
'<form[^>]*>|<option[^>]*>[^<]*</option>|<button[^>]*>[^<]*</button>'<form action="/catalog" method="get">
<option value="title" selected="">Title (A to Z)</option>
<option value="price-asc">Price: low to high</option>
<option value="price-desc">Price: high to low</option>
<button type="submit">Apply</button>Even a Client Component server-renders its first pass: curl sees the full form with defaultValue already reflecting the current URL (selected on the active option). After hydration the same markup also responds to onChange. The address bar, the rendered list and the select stay in step because all three read from the same source — the URL.
05. What usually goes wrong
06. Check your understanding
07. Apply it
Add a price-band filter to the running catalog:
- Accept
?max=(a number) in the page, and filterproductswith it. - Extend
catalogHrefso every link keepsmaxalongsidecategoryandsort. - Add a number input to the FilterBar form. Check both paths: submit the form with JavaScript off, then wire
onChangetorouter.replace, remembering to droppage. - Reload each filtered URL, copy one into a new tab, and confirm the list is identical. If anything differs, the state has leaked out of the URL.
For contrast on where view state belongs, compare with /skills/frontend-state-management: component state for ephemeral UI, the URL for anything shareable.
08. Review prompt
Without looking back: how does a Server Component page read the query string, and what shape can each value take? Why does the pagination helper start from an empty URLSearchParams instead of the current string? What does a GET form give you before any JavaScript loads, and what do useSearchParams, the copy-then-set rule, and router.replace each add after it?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.