Thuta Learning
API Tutorial
IntermediateWeb DevelopmentIntermediate

Pagination/Filtering/Sorting

API TutorialLesson 1335 min

What you'll walk away with

  • Explain why list endpoints return one page at a time and what limit, offset and cursor mean
  • Show how offset pagination repeats or skips rows when the data changes, and why cursor (keyset) pagination does not
  • Write a loop that follows next_cursor until it is null and stops when the server misbehaves
  • Accept filter and sort parameters safely with an allowlist, a stable tie-breaker and a maximum page size

Explain it simply

Pagination in plain language

Behind a list endpoint such as GET /v1/users there may be fifty thousand rows. Sending all of them in one response would be slow for the server, heavy for the network and useless for a screen that shows twenty at a time. So the API hands you the list one page at a time.

Think of library search results. You see the first ten matches and a "next" button. Every response carries one page plus whatever you need to ask for the following one, either an offset or a bookmark called a cursor. A filter (?role=admin) chooses which rows belong in the list, a sort (?sort=-id) decides their order, and pagination cuts that ordered list into pages.

Problem → Why → Solution

The problem: reading a changing list by page number

The client below loops until a page comes back empty. On a quiet test database it works. In production, new users sign up while you are paging: a row inserted at the top pushes every later row down by one, so the first row of page 2 is the last row of page 1 again. You process a user twice, and with deletions you skip users instead. The loop also has no stop condition except an empty page, so a server that keeps returning the same data would keep it spinning forever.

offset-loop.js
// Looks fine, but assumes the data never changes while we read it
const all = [];
let offset = 0;
while (true) {
  const res = await fetch("/v1/users?limit=50&offset=" + offset);
  const { items } = await res.json();
  if (items.length === 0) break; // the only stop condition
  all.push(...items);            // may contain duplicates
  offset += 50;
}

Why page numbers are fragile

An offset means "skip the first N rows of the list as it looks right now". It does not point at a particular row, so any insert or delete before that position changes what the number means. A cursor points at a row ("everything after u_5"), so the answer stays correct even when rows appear or disappear elsewhere.

Core concept: filter, sort, page and the bookmark

A paginated list answers three questions in a fixed order. Filtering decides which rows qualify, including which rows this caller may see. Sorting puts those rows in one order. Pagination then cuts the ordered list into pages. The server must filter by permission before it paginates, otherwise a page can contain rows the caller may not read, or a total count can leak how many hidden rows exist.

Offset pagination sends ?limit=20&offset=40, meaning skip forty rows and return the next twenty. It is easy to build and lets a user jump straight to page seven. Its weakness is that an offset is a count, not a position: if a row is inserted or deleted before that count, every later page shifts and a row is repeated or skipped. It is also slow on deep pages, because the database still walks past all the skipped rows before it can return one.

Cursor (keyset) pagination sends ?limit=20&cursor=abc. The cursor encodes the last row you saw, and the server answers "the rows after this one", usually as WHERE id < 5 ORDER BY id DESC LIMIT 20, which an index serves in the same time on page one and page ten thousand. Because it points at a row instead of counting rows, inserts elsewhere cannot move your place. The price is that you cannot jump to page seven, and the sort must be total: add a unique column such as id as the last tie-breaker, or rows with equal sort values may be skipped.

Questionoffset / limitcursor / keyset
Jump straight to page 7?Yes, offset=120No, only the next page
Rows inserted while readingRepeats or skips rowsStable, no repeats
Cost of a deep pageGrows with the offsetSame as page one
Natural fitAdmin tables, small dataFeeds, exports, big data

Treat the cursor as an opaque string. Today it may be the base64 of {"id":5}; tomorrow the server may add the sort field or sign it. A client that builds or edits cursors breaks the day that changes. The response should also say plainly where the list ends: a next_cursor that becomes null, a has_more flag, or a Link header with rel="next". A total count is optional, because counting a large filtered table is expensive and the number is already out of date when it arrives. The server may also clamp limit to a maximum page size, so read what came back instead of assuming you received the number you asked for.

A bookmark, not a page number
  1. Ask for one page: GET ?limit=20
  2. Server returns items + next_cursor
  3. Send next_cursor back as ?cursor=
  4. Stop when next_cursor is null

A cursor remembers where you stopped, not how many rows you skipped, so rows added or removed elsewhere cannot shift your place.

General pattern

text
# offset style
GET /v1/users?limit=<n>&offset=<rows to skip>
200 OK  { "items": [ ... ], "total": <count> }

# cursor style (omit cursor on the first request)
GET /v1/users?limit=<n>&cursor=<opaque string>&role=<filter>
200 OK  { "items": [ ... ], "next_cursor": "<opaque string>" | null }

Offset style sends a number of rows to skip, cursor style sends back the opaque string the server gave you. Either way the response must carry what you need to continue, a total or a next_cursor.

Worked example: offset drift versus a cursor walk

The sample starts a tiny API on a random local port (no network and no keys needed). It serves six users, newest first, and speaks both styles so you can compare them. A client reads page 1 with offset, a new user signs up, then it reads page 2 and u_4 shows up twice. After that fetchAll walks the list with a cursor, another user signs up in the middle of the walk, and the result still contains no duplicates.

pagination.mjs
import http from "node:http";

// A stand-in for https://api.example.com, newest users first.
const users = ["Ana", "Ben", "Cho", "Dev", "Eli", "Fay"].map((name, i) => ({
  id: "u_" + (i + 1),
  name,
}));
const seq = (user) => Number(user.id.slice(2)); // "u_5" -> 5
const signUp = (name) => users.push({ id: "u_" + (users.length + 1), name });

// A cursor is opaque to clients. Here it is base64 of {"id": <last id seen>}.
const encode = (id) => Buffer.from(JSON.stringify({ id })).toString("base64url");
const decode = (cursor) => JSON.parse(Buffer.from(cursor, "base64url").toString()).id;

const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  const limit = Math.min(Number(url.searchParams.get("limit") ?? 3), 5); // max page size
  const rows = [...users].reverse();
  let body;
  if (url.searchParams.has("offset")) {
    const offset = Number(url.searchParams.get("offset"));
    body = { items: rows.slice(offset, offset + limit), total: rows.length };
  } else {
    const cursor = url.searchParams.get("cursor");
    const rest = cursor ? rows.filter((u) => seq(u) < decode(cursor)) : rows;
    const items = rest.slice(0, limit);
    const next = rest.length > limit ? encode(seq(items.at(-1))) : null;
    body = { items, next_cursor: next };
    const target = "/v1/users?limit=" + limit + "&cursor=" + next;
    if (next) res.setHeader("Link", "<" + target + '>; rel="next"');
  }
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify(body));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;
const ids = (items) => items.map((u) => u.id).join(" ");

// 1. Offset paging while the data changes
const getJson = async (path) => (await fetch(base + path)).json();
const page1 = await getJson("/v1/users?limit=3&offset=0");
console.log("offset page 1:", ids(page1.items), "(total " + page1.total + ")");
signUp("Gus"); // someone registers between our two requests
const page2 = await getJson("/v1/users?limit=3&offset=3");
const repeated = page2.items.filter((u) => page1.items.some((p) => p.id === u.id));
console.log("offset page 2:", ids(page2.items), "| seen twice:", ids(repeated));

// 2. Cursor paging: follow next_cursor until it is null, with safety guards
async function fetchAll(maxPages = 10) {
  const all = [];
  const usedCursors = new Set();
  let cursor = null;
  for (let page = 1; page <= maxPages; page++) {
    const query = "?limit=3" + (cursor ? "&cursor=" + cursor : "");
    const res = await fetch(base + "/v1/users" + query);
    const body = await res.json();
    const link = res.headers.get("link");
    console.log("cursor page " + page + ":", ids(body.items), "| link:", link);
    all.push(...body.items);
    cursor = body.next_cursor;
    if (cursor === null) return all; // the server says there is nothing more
    if (usedCursors.has(cursor)) throw new Error("server repeated a cursor");
    usedCursors.add(cursor);
    if (page === 1) signUp("Hal"); // new data arrives in the middle of the walk
  }
  throw new Error("stopped after " + maxPages + " pages");
}
const all = await fetchAll();
const duplicates = all.length - new Set(all.map((u) => u.id)).size;
console.log("collected:", ids(all), "| duplicates:", duplicates);
server.close();

Code breakdown

  1. Opaque cursorconst encode = (id) => Buffer.from(JSON.stringify({ id })).toString("base64url");

    The cursor is the last id seen, turned into JSON and then base64url. A client never needs to read it; it only sends it back.

  2. Maximum page sizeconst limit = Math.min(Number(url.searchParams.get("limit") ?? 3), 5); // max page size

    Even if a client asks for limit=100, the server never returns more than five. That is why the client reads the items it received instead of trusting the number it asked for.

  3. Offset pagebody = { items: rows.slice(offset, offset + limit), total: rows.length };

    An offset is only a count from the start of the array. This line points at no particular row, so when signUp runs in between, page 2 hands out u_4 again.

  4. Keyset pageconst rest = cursor ? rows.filter((u) => seq(u) < decode(cursor)) : rows;

    Only rows with an id smaller than the one in the cursor are kept, the same idea as WHERE id < last in SQL. A new user arriving at the top does not change this filter's result.

  5. Stop signalif (cursor === null) return all; // the server says there is nothing more

    The server announces the end with next_cursor: null, so the client does not have to guess from a short page.

  6. Loop guardsif (usedCursors.has(cursor)) throw new Error("server repeated a cursor");

    A cursor that shows up twice means the server is misbehaving. This guard and the maxPages limit stop the client from chasing a buggy server forever.

You should see
offset page 1: u_6 u_5 u_4 (total 6)
offset page 2: u_4 u_3 u_2 | seen twice: u_4
cursor page 1: u_7 u_6 u_5 | link: </v1/users?limit=3&cursor=eyJpZCI6NX0>; rel="next"
cursor page 2: u_4 u_3 u_2 | link: </v1/users?limit=3&cursor=eyJpZCI6Mn0>; rel="next"
cursor page 3: u_1 | link: null
collected: u_7 u_6 u_5 u_4 u_3 u_2 u_1 | duplicates: 0
Walking a cursor-paginated list
  1. Request the first page with no cursor
  2. Process the items you received
  3. Check whether next_cursor is null
  4. If not, request again with ?cursor=

next_cursor is null

The walk is complete

Cursor repeats or the page limit is reached

Abort and report a server problem instead of looping forever

Accepting filters and sorting without opening a hole

Query parameters come from the client, so treat them as untrusted input. Never paste a sort or filter value into SQL: besides injection, a client could sort on an unindexed column and put heavy load on the database. Accept sort only from an allowlist (for example id and name), map the column yourself, and always add the unique id as the last tie-breaker. Do not quietly ignore an unknown sort field; answer 422 and list the allowed values, or the client will believe the data is sorted when it is not.

ParameterPurposeServer rule
limitPage sizedefault 20, max 100, reject 0 and negatives
cursorWhere to resumeopaque; 400 invalid_cursor if malformed
sortOrder of rowsallowlist plus unique id tie-breaker
roleNarrow the listexact match on allowed values only

The raw HTTP and the Link header

The Link header gives the URL of the next page outside the body. A client does not have to build the URL; it just follows the link marked rel="next". Look at the response below: the body carries next_cursor and the header carries the same pointer. APIs use one of them, or both, so read the provider's docs first.

text
GET /v1/users?limit=3 HTTP/1.1
Host: api.example.com
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json
Link: </v1/users?limit=3&cursor=eyJpZCI6NH0>; rel="next"

{ "items": [ { "id": "u_6" }, { "id": "u_5" }, { "id": "u_4" } ],
  "next_cursor": "eyJpZCI6NH0" }

In real projects

Pagination in real APIs

Providers use these ideas under different names. The GitHub REST API uses per_page (maximum 100) and the Link header, Stripe uses limit, starting_after and has_more, and Slack uses a cursor parameter and a next_cursor inside response_metadata. Always check the exact parameter names in the provider's docs.

  • Infinite-scroll feeds and activity timelines use cursors, because new rows keep arriving and offset paging would show repeats.
  • Admin tables hold modest data and users want to jump to page seven, so offset with a total is still common there.
  • Export and sync jobs follow next_cursor until null, which can mean hundreds of pages, and every request counts against the rate limit. Use the maximum page size and add the guards.

Common mistakes

Common pagination mistakes

Reading live data with offset

Walking a changing list such as a feed or a user table with an offset loop repeats and skips rows. It rarely shows up in tests and only appears in production, which makes it hard to find. If the provider offers a cursor, use it.

A loop with no guard

Following the next page with while (true) and trusting the server to stop means one server bug (a cursor that never changes, a next_cursor that never becomes null) makes the process spin and burn the rate limit. Add maxPages and a Set of cursors already used.

Building or editing cursors on the client

Do not decode a cursor and bump the id yourself. The format can change between versions, and the server will reject a cursor it did not issue with a 400.

Accepting limit and sort without bounds

A request with limit=1000000 makes the server load every row into memory. Enforce a maximum page size and keep sort behind an allowlist.

Best practices

Best practices

  • Prefer cursor pagination for changing or large lists, and use offset only when the data is small and users must jump between pages.
  • Give every list a default and a maximum limit, and have clients trust what came back when they receive fewer rows than they asked for.
  • Offer a total count only when it is really needed, and document that it is approximate.

Mini challenge

Build a cursor pager

Write pageAfter(rows, limit, cursor) for rows already sorted by id, largest first. It returns { items, next_cursor }, throws on an invalid limit or cursor, and clamps limit to at most 5. Then write collectAll(), which follows next_cursor with a page guard.

  • Clamp limit to the range 1 to 5 and reject anything that is not an integer
  • Decode the cursor to find where to resume, and throw Error("invalid cursor") for garbage
  • next_cursor must be null on the last page
  • collectAll must throw when it exceeds maxPages
pager.js
const MAX_LIMIT = 5;
const rows = [8, 7, 6, 5, 4, 3, 2, 1].map((n) => ({ id: n }));

// A cursor is an opaque string. You choose how to encode it.
function encodeCursor(id) {
  // TODO: turn the last id on this page into an opaque string
}

function decodeCursor(cursor) {
  // TODO: turn it back into an id, or throw new Error("invalid cursor")
}

function pageAfter(rows, limit, cursor = null) {
  // TODO: validate limit and clamp it to MAX_LIMIT
  // TODO: keep only the rows after the cursor (rows are newest first)
  // TODO: return { items, next_cursor }, with next_cursor null on the last page
}

function collectAll(maxPages) {
  // TODO: call pageAfter(rows, 3, cursor) until next_cursor is null
  // TODO: throw an Error if maxPages is exceeded
}

Expected: Four lines print: 8 7 6 5 4 3 2 1, then 5 (limit 100 was clamped), then too many pages, then invalid cursor.

Show hint

Decide whether to emit next_cursor by asking whether rows remain after this page: rest.length > size. Keep only rows with an id smaller than the one in the cursor. Note that Buffer.from("!!!", "base64url") does not throw, it gives an empty string, so check that the decoded text is really a number.

Show solution
pager-solution.js
const MAX_LIMIT = 5;
const rows = [8, 7, 6, 5, 4, 3, 2, 1].map((n) => ({ id: n }));

const encodeCursor = (id) => Buffer.from(String(id)).toString("base64url");

function decodeCursor(cursor) {
  const text = Buffer.from(cursor, "base64url").toString();
  if (!/^[0-9]+$/.test(text)) throw new Error("invalid cursor");
  return Number(text);
}

function pageAfter(rows, limit, cursor = null) {
  if (!Number.isInteger(limit) || limit < 1) throw new Error("invalid limit");
  const size = Math.min(limit, MAX_LIMIT);
  const rest = cursor === null ? rows : rows.filter((r) => r.id < decodeCursor(cursor));
  const items = rest.slice(0, size);
  const hasMore = rest.length > size;
  return { items, next_cursor: hasMore ? encodeCursor(items.at(-1).id) : null };
}

function collectAll(maxPages) {
  const ids = [];
  let cursor = null;
  for (let page = 0; page < maxPages; page++) {
    const body = pageAfter(rows, 3, cursor);
    ids.push(...body.items.map((r) => r.id));
    if (body.next_cursor === null) return ids;
    cursor = body.next_cursor;
  }
  throw new Error("too many pages");
}

console.log(collectAll(10).join(" "));
console.log(pageAfter(rows, 100).items.length);
try {
  collectAll(2);
} catch (err) {
  console.log(err.message);
}
try {
  pageAfter(rows, 3, "!!!");
} catch (err) {
  console.log(err.message);
}

Quick quiz 1 / 3

A client reads page 1 of a newest-first list with limit=3&offset=0. A new row is then inserted at the top and the client requests offset=3. What happens?

Quick quiz 2 / 3

Which loop condition is the safest way to read a cursor-paginated list to the end?

Quick quiz 3 / 3

Why add the unique id as the last sort key?

What to remember

  • Lists come one page at a time: filter by permission first, then sort, then cut the page.
  • Offset is only a count, so it repeats or skips rows when data changes and is slow when deep; a cursor points at a row and stays stable.
  • Follow next_cursor until null, add guards for maxPages and repeated cursors, and keep cursors opaque.
  • Bound limit, put sort and filter behind an allowlist, and add the unique id as the tie-breaker.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Pagination/Filtering/Sorting | Thuta Learning