Skip to content

Pagination with a Defined Boundary

The Course
•
18 min study

The decision

Pagination is more than slicing an array. A URL can request page zero, a fractional page or a page beyond the end. Choose a policy once and keep navigation, counts and API responses consistent.

Read, predict, run

The input contains page, total and size. The function clamps a whole-number page to the available range, then derives its offset. An empty collection still has a first page whose list is empty; this avoids a confusing page zero:

JavaScript
export function run({ page, total, size }) {
  const pages = Math.max(1, Math.ceil(total / size));
  const n = Number(page);
  const current = Number.isInteger(n) ? Math.min(pages, Math.max(1, n)) : 1;
  return { current, pages, offset: (current - 1) * size };
}

Before pressing Run, predict what run returns for {"page": "2", "total": 12, "size": 5} and {"page": "99", "total": 0, "size": 5}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Pagination with a Defined Boundary Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Pagination with a Defined Boundary</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ page, total, size }) { const pages = Math.max(1, Math.ceil(total / size)); const n = Number(page); const current = Number.isInteger(n) ? Math.min(pages, Math.max(1, n)) : 1; return { current, pages, offset: (current - 1) * size }; } export const examples = [ [ { page: "2", total: 12, size: 5 }, { current: 2, pages: 3, offset: 5 }, ], [ { page: "99", total: 0, size: 5 }, { current: 1, pages: 1, offset: 0 }, ], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"page": "2", "total": 12, "size": 5} → {"current": 2, "pages": 3, "offset": 5}.
  • Input {"page": "99", "total": 0, "size": 5} → {"current": 1, "pages": 1, "offset": 0}.

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The failure to avoid

Using parseInt silently accepts 2garbage. Computing an offset before clamping can show an empty page while the navigation claims items exist.

Trace {"page": "9", "total": 12, "size": 5}: write pages, current and offset. Then trace it with the clamp removed, and say which items that page would show.

Exercise

Extend the contract

Add a hasNext boolean to the result. It must be false on the last page and for an empty collection.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"page": "1", "total": 12, "size": 5} must return {"current": 1, "pages": 3, "offset": 0, "hasNext": true}.
Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>Pagination with a Defined Boundary</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ page, total, size }) { const pages = Math.max(1, Math.ceil(total / size)); const n = Number(page); const current = Number.isInteger(n) ? Math.min(pages, Math.max(1, n)) : 1; return { current, pages, offset: (current - 1) * size }; } export const examples = [ [ { page: "2", total: 12, size: 5 }, { current: 2, pages: 3, offset: 5 }, ], [ { page: "99", total: 0, size: 5 }, { current: 1, pages: 1, offset: 0 }, ], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

hasNext isn't new information. It follows from the page you're on and how many pages there are, once the page has been clamped.

Hint 2: a first step

Derive it from the clamped current page and pages; it is not new state.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ page, total, size }) {
  const pages = Math.max(1, Math.ceil(total / size));
  const n = Number(page);
  const current = Number.isInteger(n) ? Math.min(pages, Math.max(1, n)) : 1;
  return {
    current,
    pages,
    offset: (current - 1) * size,
    hasNext: current < pages,
  };
}

Comparing the clamped current with pages means a request for page 9 of 3 says hasNext: false, and so does an empty collection, which still has one page. Deriving it from the same two numbers the navigation shows keeps the Next link and the page count from ever disagreeing.

Explain it without the code

Write the result for page: "2.5" with 12 items of size 5, and say which line decided it.

Going further

Read the Next.js guide for the framework boundary around this rule. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.