Skip to article content
LESSON 05 / 28

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.

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

app/catalog/page.tsx
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>;
}

PAUSE AND PREDICT

The URL contains page=2x. Your contract accepts only positive decimal integers. Which parser behavior is correct?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Update query state without losing unrelated filters

A client control can read search parameters and navigate to an updated URL. Clone the existing parameter collection, change the relevant key, and preserve unrelated supported keys. When the search query changes, reset page to one; otherwise a narrowed result set can leave the user on an empty page that no longer exists. For page navigation, preserve the current filter and sort order.

Choose push or replace based on the intended history. Replacing every debounced keystroke avoids filling Back history with partial search text. An explicit page selection can reasonably create a history entry. Either choice is acceptable when the behavior is deliberate and tested. Avoid two-way synchronization Effects where URL changes update local state and local changes immediately rewrite the URL without a clear source of truth.

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.

PAUSE AND PREDICT

A user is on page 8, then applies a filter with only two pages of results. What update best preserves a useful view?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

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.

  1. 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.
  2. 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.
  3. 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.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 5 test cases
  1. Defaults

    Input

    {
      "params": {}
    }

    Expected

    {
      "q": "",
      "page": 1,
      "sort": "name"
    }
  2. Valid shared query

    Input

    {
      "params": {
        "q": "  keyboard  ",
        "page": "03",
        "sort": "price"
      }
    }

    Expected

    {
      "q": "keyboard",
      "page": 3,
      "sort": "price"
    }
  3. Reject numeric prefixes

    Input

    {
      "params": {
        "q": "x",
        "page": "2x",
        "sort": "random"
      }
    }

    Expected

    {
      "q": "x",
      "page": 1,
      "sort": "name"
    }
  4. Repeated key uses first value

    Input

    {
      "params": {
        "q": [
          "  first  ",
          "second"
        ],
        "page": [
          "-2",
          "5"
        ],
        "sort": [
          "price",
          "name"
        ]
      }
    }

    Expected

    {
      "q": "first",
      "page": 1,
      "sort": "price"
    }
  5. Cap the contract

    Input

    {
      "params": {
        "q": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        "page": "99999"
      }
    }

    Expected

    {
      "q": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      "page": 1000,
      "sort": "name"
    }
Reveal the worked solution and reasoning
solution.js
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

  1. 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.
  2. 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.
  3. 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.
  4. 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.

Terminal
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:e2e

Open 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.

  1. 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?
  2. 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?
  3. 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?
  4. 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?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

Typing into search uses router.replace, while clicking page 2 uses a normal navigation entry. What is the best justification?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.