Skip to content

Pagination

Source-agnostic, type-safe pagination for @xtandard/lib/pagination (zero dependencies). One paginator handles every input style, every data source, and every output shape:

flowchart LR
  subgraph inputs
    direction TB
    I1["?#8288;page=2&per_page=20"]
    I2["?#8288;limit=20&offset=40"]
    I3["?cursor=abc"]
    I4["{ first, after }"]
    I1 ~~~ I2 ~~~ I3 ~~~ I4
  end
  subgraph core
    CORE["createPaginator(<br/>your fetchers<br/>)"]
  end
  subgraph outputs
    direction TB
    O1["{ data, meta } (REST)"]
    O2["{ edges, pageInfo } (Relay)"]
    O3["useInfiniteQuery config"]
    O4["paginator.pages/items()"]
    O1 ~~~ O2 ~~~ O3 ~~~ O4
  end
  inputs --> core --> outputs

The design splits pagination into three concerns:

  1. Input contracts — what the caller asks for (page/pageSize, limit/offset, or an opaque cursor, forward or backward).
  2. Fetching — a function you provide. The library never touches your data source, which is why it works equally for SQL, Drizzle, Prisma, Mongoose, an upstream HTTP API, or a plain array.
  3. Output contracts — one uniform Paginated<T> envelope, with adapters to REST and Relay shapes and to TanStack Query.

Import pagination APIs from the sub-entry:

import { createPaginator, parsePaginationParams } from "@xtandard/lib/pagination";

Everything is sync/async adaptive: pass all-sync fetchers (an in-memory array) and results come back as plain values with no await; anything async makes them Promises — reflected in the types.


import { createPaginator, parsePaginationParams, toRestEnvelope } from "@xtandard/lib/pagination";
const userPaginator = createPaginator({
// offset-capable source (SQL OFFSET, Mongo .skip(), array.slice...)
fetchOffset: async ({ limit, offset }) => ({
items: await db.query(`SELECT * FROM users ORDER BY id LIMIT $1 OFFSET $2`, [limit, offset]),
}),
// cursor-capable source (keyset / seek pagination)
fetchCursor: async ({ limit, cursor, direction }) => ({
items: await db.query(
direction === "backward"
? `SELECT * FROM users WHERE id < $1 ORDER BY id DESC LIMIT $2`
: `SELECT * FROM users WHERE id > $1 ORDER BY id ASC LIMIT $2`,
[cursor?.id ?? (direction === "backward" ? Infinity : 0), limit],
),
}),
cursor: { fromItem: (u) => ({ id: u.id }) },
});
// any input style works against the same paginator
const a = await userPaginator.paginate({ type: "page", page: 2, pageSize: 20 });
const b = await userPaginator.paginate({ type: "offset", limit: 20, offset: 40 });
const c = await userPaginator.paginate({ type: "cursor", limit: 20, cursor: a.pageInfo.endCursor });

Every call returns the same envelope:

type Paginated<T> = {
items: T[];
pageInfo: {
hasNextPage: boolean;
hasPreviousPage: boolean;
startCursor?: string | null; // present when cursors are configured
endCursor?: string | null;
page?: number; // present for page/offset requests
pageSize?: number;
totalItems?: number; // present when your fetcher reports it
totalPages?: number;
};
};

flowchart TD
  Q1{"Need #quot;jump to page N#quot;<br/>or total page count?"}
  Q1 -->|yes| A1["offset/page<br/>(provide fetchOffset, optionally totalItems)"]
  Q1 -->|no| Q2{"data changes while user paginates<br/>(feeds, live tables)?"}
  Q2 -->|yes| A2["cursor<br/>(provide fetchCursor + cursor.fromItem)"]
  Q2 -->|no| Q3{"small/static dataset,<br/>in-memory only?"}
  Q3 -->|yes| A3["offset/page with sync fetchOffset is enough"]

Support both when you have mixed clients: admin UIs on ?page= and mobile feeds on ?cursor=. One paginator, two fetchers.


type PaginationInput =
| { type: "page"; page: number; pageSize: number } // 1-based
| { type: "offset"; limit: number; offset: number }
| { type: "cursor"; limit: number; cursor?: string | null; direction?: "forward" | "backward" };

page and offset are interconvertible (offset = (page - 1) * pageSize — see toOffsetWindow), so they share one fetcher. Cursor pagination is fundamentally different (it seeks by value, not by position) and gets its own fetcher. A paginator supports whichever styles you give it fetchers for; asking for an unsupported style throws immediately with a clear message.

When to use which:

Style Pros Cons Typical use
page/pageSize familiar, jump to page N, total pages drifts when rows are inserted/deleted; OFFSET is slow deep in large tables admin tables, search results
limit/offset same as page, more direct same as page APIs mirroring SQL
cursor stable under writes, fast at any depth, bidirectional no “jump to page 7”, needs a deterministic unique sort feeds, infinite scroll, public APIs

Your fetchers receive a normalized window:

// fetchOffset receives:
{
limit: number;
offset: number;
}
// fetchCursor receives:
{
limit: number;
cursor: TCursor | null;
direction: "forward" | "backward";
}

Three rules:

  1. Fetch up to window.limit rows — do not cap it yourself. The limit already includes a one-row lookahead the paginator uses to compute hasNextPage without a COUNT(*). If you fetch fewer rows than asked, hasNextPage will be wrong.
  2. cursor is already decoded. You receive the plain object your fromItem produced (e.g. { id: 42 }), never the opaque token. null means “first page”.
  3. When direction is "backward", flip your sort order (ORDER BY id DESC instead of ASC) and return rows in that flipped order. The paginator reverses them back, so consumers always see natural order.

Optionally return totalItems alongside items (run a count when it’s cheap) and the envelope gains totalItems/totalPages.

Two strategies, chosen automatically:

totalItems from fetcher How hasNextPage is computed
not provided lookahead: fetched.length > requestedLimit
provided offset + items.length < totalItems (exact)

hasPreviousPage is always offset > 0. When totalItems is present, totalPages = ceil(totalItems / pageSize) is added to pageInfo.

Separate from parsePaginationParams’s maxPageSize (transport clamp). createPaginator({ maxLimit: 100 }) caps any requested limit/pageSize before the +1 lookahead is applied — so a client asking for 500 gets limit: 100 in the window and limit: 101 handed to the fetcher.

Use both: maxPageSize at the HTTP boundary, maxLimit as defense-in-depth inside the paginator.

If you configure cursor.fromItem (even without fetchCursor), page and offset responses still get pageInfo.startCursor/endCursor encoding the first and last item on the page. This lets REST clients upgrade to cursor pagination without a second endpoint:

// page 2 of an admin table — meta still carries cursors for deep-linking
const result = await paginator.paginate({ type: "page", page: 2, pageSize: 20 });
// result.pageInfo.endCursor → opaque token for "continue after last row here"

Cursor requests still require fetchCursor.

toOffsetWindow normalizes invalid transport input before it reaches your fetcher:

  • page floors to 1, pageSize/limit floors to 1
  • offset floors to 0
  • page input: offset = (page - 1) * pageSize
  • offset input passes through after clamping

The paginator also computes a synthetic page in pageInfo for offset requests: floor(offset / limit) + 1.

A cursor is the data needed to find an item again: typically the values of your ORDER BY columns, always ending in something unique.

cursor: {
// extract cursor data from an item — MUST match your sort columns
fromItem: (post) => ({ createdAt: post.createdAt, id: post.id }),
// optional: how cursor data becomes an opaque token (see "Cursor codecs")
codec: createCursorCodec(),
}

Rule of thumb: if you sort by createdAt, the cursor must contain createdAt and a tiebreaker (id), and your keyset WHERE must compare the tuple: (created_at, id) < ($1, $2). A non-unique sort produces skipped or duplicated rows at page boundaries.

paginator.cursorFor(item) encodes the token for any item — useful for per-edge cursors in GraphQL or for “start reading from this row” links.

One cursor request, end to end (forward, limit: 20):

sequenceDiagram
  participant C as Client
  participant H as Endpoint
  participant P as Paginator
  participant K as Cursor codec
  participant F as fetchCursor
  C->>H: GET /posts?cursor=token&limit=20
  H->>P: paginate(parsePaginationParams(...))
  P->>K: decode(token)
  K-->>P: { createdAt, id }
  P->>F: { limit: 21, cursor: { createdAt, id }, direction }
  Note over F: keyset WHERE (created_at, id) > cursor<br/>ORDER BY created_at, id LIMIT 21
  F-->>P: up to 21 rows
  Note over P: a 21st row means hasNextPage<br/>keep 20, reverse if backward
  P->>K: encode(fromItem(first)), encode(fromItem(last))
  K-->>P: startCursor, endCursor
  P-->>H: { items, pageInfo }
  H-->>C: toRestEnvelope: { data, meta: { endCursor } }
  Note over C: next request sends ?cursor=endCursor

When a fetcher returns zero rows:

  • items is []
  • hasNextPage / hasPreviousPage reflect position (offset > 0 ⇒ hasPreviousPage: true; cursor with a token ⇒ opposite-direction flag)
  • startCursor/endCursor stay null/undefined (nothing to encode)
  • pages() / items() stop immediately on an empty page

Backward pagination (the Twitter-feed case)

Section titled “Backward pagination (the Twitter-feed case)”

Forward walks the natural order; backward walks against it — “scroll up for newer posts”. Request it with direction: "backward":

// user is positioned at `token`, scrolls up:
const newer = await feedPaginator.paginate({
type: "cursor",
limit: 20,
cursor: token,
direction: "backward",
});
// newer.items are in natural order; newer.pageInfo.startCursor continues upward

Semantics follow the Relay convention: in the direction you’re walking, the has*Page flag comes from the lookahead row; in the opposite direction it’s inferred from “you came from somewhere” (a cursor was provided).