Shareable URL state and pagination
Turn filters, sorting and pagination into validated state that survives refresh, sharing and browser history.
What you will be able to do
- Define a canonical query contract and reject malformed values.
- Keep server queries and client controls aligned with the URL.
- Explain pagination resets, history behavior and stable ordering.
Before this lesson
Choose state that should survive a shared link
A search term, sort order and page number describe which slice of a catalogue the user is viewing. If a teammate opens the same URL, showing the same slice is usually useful. Those values belong naturally in the URL. Whether a small help tooltip is open usually does not. This ownership decision prevents a common bug: local filter state says one thing while the address bar and server query say another.
The URL is untrusted input. A user can edit it, paste a stale link or repeat a key. Define a contract for allowed sort values, duplicate parameters, whitespace and page bounds. Parse once at the boundary and pass the normalized model onward. Do not sprinkle Number(value) and default expressions throughout components; different fallbacks can make the pagination indicator disagree with the server result.
Normalize before querying or caching
For this lesson, q is a trimmed string capped at forty characters, page is a positive decimal integer capped at one thousand, and sort is name or price. Repeated keys use the first value. Missing or invalid page values become one. This is an explicit teaching contract, not a Next.js default. Choosing a policy is part of application design, and tests should document it.
Normalization also affects cache identity. Two inputs that mean the same query should not create unnecessarily different keys. Conversely, different tenants, locales or sort orders must not accidentally share results. The kata handles one small public catalogue query. Production code should validate authorization separately and use bound query parameters or a typed query builder rather than concatenate user input into SQL.
Server execution
type Query = Record<string, string | string[] | undefined>;
function first(value: string | string[] | undefined) {
return Array.isArray(value) ? value[0] ?? '' : value ?? '';
}
export default async function Page({ searchParams }: { searchParams: Promise<Query> }) {
const raw = await searchParams;
const q = first(raw.q).trim().slice(0, 40);
const text = first(raw.page);
const page = /^\d+$/.test(text) && Number(text) >= 1
? Math.min(1000, Number(text)) : 1;
return <main><h1>Catalogue query</h1><p>{q || 'All products'}, page {page}</p></main>;
}Make page boundaries and ordering stable
Pagination needs an ordered dataset. Sorting only by a nonunique timestamp can move equal-valued records between pages as queries run. Add a stable tie-breaker such as the unique ID. Offset pagination is straightforward for a small table but can shift under concurrent inserts. Cursor pagination expresses a position in an ordering and is often more suitable for continuously changing feeds. Explain the tradeoff rather than claiming one technique is universally better.
Test refresh, copied links, browser Back, malformed queries and a search that reduces the number of pages. The pure kata validates the parsing contract. The real lab connects parsing to server data and client navigation, where a production build may expose Suspense requirements that development hides. Completing one layer does not prove the other. In a machine-coding round, a bookmarked, reloadable filter is stronger evidence than a screenshot of a working dropdown.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEEvery kind of UI state should live in the URL.
- A more accurate model
Use the URL for meaningful shareable view state; transient menus and private secrets generally do not belong there.
- How to check it
The URL lesson distinguishes query ownership from temporary local interaction; N04 documents navigation behavior.
- CLAIM TO CHALLENGEA page number alone defines stable pagination.
- A more accurate model
The dataset needs a stable ordering and a contract for filtering, bounds and concurrent changes. Tie-breakers prevent ambiguous ordering.
- How to check it
The url-state lesson’s pagination section derives page behavior from ordered data and explicit query contracts.
Mistakes to catch in your own code
- Do not treat search parameters as trusted typed values.
- Do not leave the page number unchanged when a filter invalidates it.
- Do not let local state and the URL compete as independent authorities.
Write it by hand
JavaScript logic playground
Normalize catalogue query input
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Implement solve({params}). params can contain q, page and sort as a string or an array of strings. Repeated values use the first item; missing values use an empty string.
- Return {q,page,sort}. Trim q and keep its first 40 characters. Accept page only when it consists entirely of decimal digits and is at least one, then cap at 1000; otherwise use 1.
- Accept sort=name or sort=price; otherwise use name. This pure parsing exercise does not navigate the browser.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 5 test cases
- Defaults
Input
{ "params": {} }Expected
{ "q": "", "page": 1, "sort": "name" } - Valid shared query
Input
{ "params": { "q": " keyboard ", "page": "03", "sort": "price" } }Expected
{ "q": "keyboard", "page": 3, "sort": "price" } - Reject numeric prefixes
Input
{ "params": { "q": "x", "page": "2x", "sort": "random" } }Expected
{ "q": "x", "page": 1, "sort": "name" } - Repeated key uses first value
Input
{ "params": { "q": [ " first ", "second" ], "page": [ "-2", "5" ], "sort": [ "price", "name" ] } }Expected
{ "q": "first", "page": 1, "sort": "price" } - Cap the contract
Input
{ "params": { "q": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "page": "99999" } }Expected
{ "q": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "page": 1000, "sort": "name" }
Reveal the worked solution and reasoning
function solve(input) {
const first = value => Array.isArray(value) ? value[0] ?? '' : value ?? '';
const q = first(input.params.q).trim().slice(0, 40);
const rawPage = first(input.params.page);
const page = /^\d+$/.test(rawPage) && Number(rawPage) >= 1
? Math.min(1000, Number(rawPage)) : 1;
const rawSort = first(input.params.sort);
const sort = rawSort === 'price' ? 'price' : 'name';
return { q, page, sort };
}Validation checks the entire page representation rather than accepting a numeric prefix.
The normalized object is a useful boundary between URL parsing and query execution; it is not proof of authorization.
Verify it in a real Next.js application
Next.js application lab
Share and debug the shipped catalogue URL state
Open the local application route /catalog after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Inspect queryCatalog in lib/domain.ts and both callers: app/catalog/page.tsx and app/api/catalog/route.ts. Search, name/price sorting and four-item pagination are already implemented.
- Open /catalog?sort=price&page=2, copy it into a fresh tab, refresh and use Previous page and browser Back. Then submit a narrower filter from the later page.
- Try page=oops, page=-4, a page beyond the last result, an unsupported sort and a query with no matches. Explain the actual normalization and empty-state policy.
- As an extension, define one policy for duplicate query keys and apply it consistently at the page and API boundary. Add a regression case that starts on page two and changes the filter.
Check the behavior
- A supported shared URL restores the same query, sort and page after a direct visit.
- Submitting a changed filter omits the old page and starts at page one.
- Invalid page values follow the helper's fallback or clamping policy instead of throwing.
- If duplicate-key support is added, the page and JSON endpoint use the same documented interpretation.
Review the application reasoning
The shipped form makes full URL navigation. A router-based or debounced update is a separate interaction enhancement with its own pending and history decisions.
The lesson kata and lab helper expose explicit normalization contracts. Compare them before reusing code; neither should silently invent an unstated rule for every possible URL.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01Why put filters in the URL?
It makes the view shareable, reloadable and navigable with history, and lets a Server Component read the same query. I keep transient presentation state local. I also define parsing and serialization rules so the server and controls agree on defaults and invalid input.
Follow-up questions
- Which state should stay out of the URL?
- How would you avoid storing sensitive data there?
- Layouts and pagesOfficial documentation
- Linking and navigatingOfficial documentation
- Full-stack task-management challengePublic coding challenge
02How do you handle page=-2 or page=2x?
I validate the entire representation against the application contract, then choose a documented fallback or error. parseInt alone accepts a valid prefix from malformed text. For this catalogue I use a positive decimal pattern, cap the supported range and reset invalid values to one.
Follow-up questions
- What should duplicate page parameters mean?
- Should an out-of-range page return empty data or redirect?
- Data securityOfficial documentation
03When would you replace instead of push?
For debounced typing, replacing the current URL can avoid dozens of intermediate history entries. A deliberate page selection often deserves a new history entry. I test Back behavior as part of the feature because navigation history is a user-facing contract, not merely a router implementation detail.
Follow-up questions
- How does the input stay aligned after Back?
- What if a user submits an explicit search form?
- Linking and navigatingOfficial documentation
04How do server and client code read query state?
An App Router page can await its searchParams prop and validate it on the server. Client controls can use navigation hooks to inspect and update the URL. I avoid a second independently authoritative filter model. Modern examples need the current asynchronous page-prop shape rather than assuming older synchronous access.
Follow-up questions
- Why can a client search hook need a Suspense boundary?
- Which values become cache-key inputs?
- Upgrade to Next.js 16Official documentation
- Layouts and pagesOfficial documentation
- Fetching dataOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Upgrade to Next.js 16Official documentation
- Layouts and pagesOfficial documentation
- Linking and navigatingOfficial documentation
- Fetching dataOfficial documentation
- Data securityOfficial documentation
- Full-stack task-management challengePublic coding challenge
- ModernVivo Paper Explorer take-homeEmployer assignment