Offset pagination can skip or repeat records when rows are inserted before the current offset. A cursor identifies a position in a stable order instead.
Read, predict, run
This model orders by a unique numeric id and returns rows after the cursor. It uses a copy so callers’ arrays are not sorted in place. A real query must use an indexed matching order and validate the cursor’s shape:
Before pressing Run, predict what run returns for {"rows": [{"id": 3}, {"id": 1}, {"id": 2}], "after": 1, "limit": 1}, from the
code above. Write your answers down first: after Run, the case table shows the
expected values beside the actual ones.
Paginate from a Stable CursorNext.js · 8 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Review Queue · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Cases from "./Cases.jsx";
import PageReader from "./PageReader.jsx";
export default function Page() {
return (
<main>
<h1>Paginate from a Stable Cursor</h1>
<p>
Six reviews, two per page. app/api/items/route.js serves both kinds of
page; the cursor kind calls run from lib/contract.js.
</p>
<PageReader />
<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>
);
}
"use client";
import { useState } from "react";
const ids = (items) => items.map((item) => item.id).join(", ") || "(empty)";
export default function PageReader() {
const [offsetPages, setOffsetPages] = useState([]);
const [cursorPages, setCursorPages] = useState([]);
async function nextByOffset() {
const offset = offsetPages.length * 2;
const body = await (await fetch(`/api/items?offset=${offset}`)).json();
setOffsetPages([...offsetPages, body.items]);
}
async function nextByCursor() {
const last = cursorPages.at(-1)?.at(-1)?.id ?? 0;
const body = await (await fetch(`/api/items?after=${last}`)).json();
setCursorPages([...cursorPages, body.items]);
}
async function deleteFirst() {
await fetch("/api/items?id=1", { method: "DELETE" });
}
async function reset() {
await fetch("/api/items", { method: "POST" });
setOffsetPages([]);
setCursorPages([]);
}
return (
<section>
<p>
<button onClick={nextByOffset}>Next page by offset</button>{" "}
<button onClick={nextByCursor}>Next page by cursor</button>{" "}
<button onClick={deleteFirst}>Delete item 1</button>{" "}
<button onClick={reset}>Start again</button>
</p>
<ol aria-label="Pages by offset">
{offsetPages.map((items, index) => (
<li key={index}>Offset page {index + 1}: {ids(items)}</li>
))}
</ol>
<ol aria-label="Pages by cursor">
{cursorPages.map((items, index) => (
<li key={index}>Cursor page {index + 1}: {ids(items)}</li>
))}
</ol>
</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;
}
import { run } from "@/lib/contract.js";
import { allRows, deleteRow, resetRows } from "@/lib/items.js";
const LIMIT = 2;
// GET /api/items?after=2 pages by cursor; GET /api/items?offset=2 by offset.
export async function GET(request) {
const params = new URL(request.url).searchParams;
if (params.has("offset")) {
const offset = Number(params.get("offset"));
return Response.json({ items: allRows().slice(offset, offset + LIMIT) });
}
const after = Number(params.get("after") ?? 0);
const result = run({ rows: allRows(), after, limit: LIMIT });
// The starter's run returns an array; the exercise makes it an object.
return Response.json(Array.isArray(result) ? { items: result } : result);
}
export async function DELETE(request) {
const id = Number(new URL(request.url).searchParams.get("id"));
deleteRow(id);
return new Response(null, { status: 204 });
}
export async function POST() {
resetRows();
return new Response(null, { status: 204 });
}
export function run({ rows, after, limit }) {
return rows
.toSorted((a, b) => a.id - b.id)
.filter((row) => row.id > after)
.slice(0, limit);
}
export const examples = [
[
{ rows: [{ id: 3 }, { id: 1 }, { id: 2 }], after: 1, limit: 1 },
[{ id: 2 }],
],
];
// An in-memory table, shared by every request while the preview runs.
let rows = [1, 2, 3, 4, 5, 6].map((id) => ({ id, title: `Review ${id}` }));
export function allRows() {
return rows;
}
export function deleteRow(id) {
rows = rows.filter((row) => row.id !== id);
}
export function resetRows() {
rows = [1, 2, 3, 4, 5, 6].map((id) => ({ id, title: `Review ${id}` }));
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
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.
See it skip a record
Offset pagination says "skip the first N rows". If rows before the reader's
position disappear between two requests, everything shifts left, and the row
that slid across the page boundary is never shown. Trace it with six reviews,
two per page:
Page 1, OFFSET 0 LIMIT 2: ids 1 and 2.
Someone deletes id 1. The table is now 2, 3, 4, 5, 6.
Page 2, OFFSET 2 LIMIT 2: skips 2 and 3, returns 4 and 5. Id 3 is lost.
A cursor says "rows after the last one I saw". Page 2 asks for id > 2 and
gets 3 and 4, whatever happened before position 2. An insert at the front
has the mirror effect on offsets: a row is shown twice.
The lab below serves both kinds of page from app/api/items/route.js; the
cursor kind calls run. Predict both columns, then press Next page by
offset, Next page by cursor, Delete item 1, and both Next page
buttons again.
Offset and cursor, side by sideNext.js · 8 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Review Queue · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import Cases from "./Cases.jsx";
import PageReader from "./PageReader.jsx";
export default function Page() {
return (
<main>
<h1>Paginate from a Stable Cursor</h1>
<p>
Six reviews, two per page. app/api/items/route.js serves both kinds of
page; the cursor kind calls run from lib/contract.js.
</p>
<PageReader />
<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>
);
}
"use client";
import { useState } from "react";
const ids = (items) => items.map((item) => item.id).join(", ") || "(empty)";
export default function PageReader() {
const [offsetPages, setOffsetPages] = useState([]);
const [cursorPages, setCursorPages] = useState([]);
async function nextByOffset() {
const offset = offsetPages.length * 2;
const body = await (await fetch(`/api/items?offset=${offset}`)).json();
setOffsetPages([...offsetPages, body.items]);
}
async function nextByCursor() {
const last = cursorPages.at(-1)?.at(-1)?.id ?? 0;
const body = await (await fetch(`/api/items?after=${last}`)).json();
setCursorPages([...cursorPages, body.items]);
}
async function deleteFirst() {
await fetch("/api/items?id=1", { method: "DELETE" });
}
async function reset() {
await fetch("/api/items", { method: "POST" });
setOffsetPages([]);
setCursorPages([]);
}
return (
<section>
<p>
<button onClick={nextByOffset}>Next page by offset</button>{" "}
<button onClick={nextByCursor}>Next page by cursor</button>{" "}
<button onClick={deleteFirst}>Delete item 1</button>{" "}
<button onClick={reset}>Start again</button>
</p>
<ol aria-label="Pages by offset">
{offsetPages.map((items, index) => (
<li key={index}>Offset page {index + 1}: {ids(items)}</li>
))}
</ol>
<ol aria-label="Pages by cursor">
{cursorPages.map((items, index) => (
<li key={index}>Cursor page {index + 1}: {ids(items)}</li>
))}
</ol>
</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;
}
import { run } from "@/lib/contract.js";
import { allRows, deleteRow, resetRows } from "@/lib/items.js";
const LIMIT = 2;
// GET /api/items?after=2 pages by cursor; GET /api/items?offset=2 by offset.
export async function GET(request) {
const params = new URL(request.url).searchParams;
if (params.has("offset")) {
const offset = Number(params.get("offset"));
return Response.json({ items: allRows().slice(offset, offset + LIMIT) });
}
const after = Number(params.get("after") ?? 0);
const result = run({ rows: allRows(), after, limit: LIMIT });
// The starter's run returns an array; the exercise makes it an object.
return Response.json(Array.isArray(result) ? { items: result } : result);
}
export async function DELETE(request) {
const id = Number(new URL(request.url).searchParams.get("id"));
deleteRow(id);
return new Response(null, { status: 204 });
}
export async function POST() {
resetRows();
return new Response(null, { status: 204 });
}
export function run({ rows, after, limit }) {
return rows
.toSorted((a, b) => a.id - b.id)
.filter((row) => row.id > after)
.slice(0, limit);
}
export const examples = [
[
{ rows: [{ id: 3 }, { id: 1 }, { id: 2 }], after: 1, limit: 1 },
[{ id: 2 }],
],
];
// An in-memory table, shared by every request while the preview runs.
let rows = [1, 2, 3, 4, 5, 6].map((id) => ({ id, title: `Review ${id}` }));
export function allRows() {
return rows;
}
export function deleteRow(id) {
rows = rows.filter((row) => row.id !== id);
}
export function resetRows() {
rows = [1, 2, 3, 4, 5, 6].map((id) => ({ id, title: `Review ${id}` }));
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
The offset reader never sees review 3. Nothing errored, which is what makes
this failure hard to spot in production.
The failure to avoid
Ordering only by a non-unique timestamp leaves ties ambiguous, and rows with
the same timestamp can be skipped or repeated at a page boundary. A cursor
needs a deterministic tie-breaker, such as (createdAt, id), and the query
must use that same order with an index. The cursor is also user input: check
its shape, and let authorization restrict the rows as it does without paging.
Exercise
Extend the contract
Return nextCursor with items: use the last returned id, or null when no rows remain in this page.
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.
items.at(-1)?.id is the last id on this page, and ?? null covers an empty
page. But this contract can't tell a full last page from one with more after
it: a client that receives exactly limit rows asks once more and gets an
empty page. The Going further section removes that wasted request.
Explain it without the code
Write the requests a client makes to read all of [1, 2, 3, 4] with
limit: 2 under this contract, and under the limit + 1 version.
Going further: knowing there's no next page
The exercise's contract can't tell a full last page from one with more rows
after it. Ask for one row more than you show:
With [1, 2, 3, 4] and limit: 2, the second page is [3, 4] with
nextCursor: null, so the client knows to stop and shows "End of list"
without asking again. In SQL this is WHERE id > ? ORDER BY id LIMIT ? + 1.
Limits of this model: keyset pages can't jump to "page 7", and the order must
be one the database can serve from an index. The preview's table lives in
memory, so a reload of the lab starts it again.
Completion is saved in this browser only. It does not measure mastery.