Skip to content

Pagination: reference

The paginator is as synchronous as what you pass, per the sync/async-adaptive pattern:

Config paginate() cursorFor()
sync fetchers + sync codec Paginated<T> — no await string
async fetchers + sync codec (common) MaybePromise<Paginated<T>> string
async codec anywhere MaybePromise<Paginated<T>> MaybePromise<string>

await works on every tier, so when in doubt, await it. Misconfiguration (asking for a style with no fetcher) throws synchronously in all tiers — prefer await/try-catch over .then().catch() chains.

You passed Type paginate return
all-sync fetchers, sync codec PaginatorSync<T> Paginated<T>
async fetchers (or mixed), sync codec Paginator<T> MaybePromise<...>
async codec stage PaginatorMaybeAsync<T> MaybePromise<...>

TCursor is inferred from cursor.fromItem’s return type — your fetcher receives CursorWindow<TCursor> with the right shape.


  • Skip totalItems when COUNT(*) is expensive — lookahead still gives correct hasNextPage; you lose totalPages (fine for infinite scroll).
  • Deep OFFSET degrades on large tables — expose cursor pagination for feeds; keep offset for shallow admin pages.
  • One-row lookahead avoids an extra round-trip per page vs COUNT + SELECT.
  • pages() / items() fetch lazily — one query per loop iteration; safe to break early.

  1. Move slice/query logic into fetchOffset
  2. Replace manual offset math with parsePaginationParams + toRestEnvelope
  3. Add cursor.fromItem when you want meta.endCursor without cursor fetch yet
  1. Replace connectionFromArray (in-memory) with createPaginator + DB fetcher
  2. Swap arg parsing for fromRelayArgs, response shaping for toRelayConnection
  3. Pass paginator.cursorFor as the edge cursor function

Add fetchOffset for admin pages; keep your existing findMany as fetchCursor. One paginator, both styles.


Executable specs live in:

Fetcher contract checklist (mirror these in your integration tests):

  • fetcher returns up to limit rows (including lookahead row)
  • hasNextPage true when extra row present, false on last page
  • backward fetcher returns flipped order; consumer sees natural order
  • composite cursor WHERE matches ORDER BY columns + tiebreaker
  • malformed ?cursor= → 400 at boundary, not 500
  • maxPageSize / maxLimit clamp honored

Export What it does
createPaginator(options) Build a paginator from fetchOffset/fetchCursor + optional cursor config and maxLimit
paginator.paginate(input) Run any PaginationInput → Paginated<T>
paginator.cursorFor(item) Encode an item’s opaque cursor token
paginator.pages(input) / paginator.items(input) Lazy AsyncGenerators walking all pages / items
toOffsetWindow(input) Page/offset input → { limit, offset } (clamps invalid values)
createCursorCodec(options?) Pluggable token codec (serializer/parser + encoder/decoder, reviveDates)
encodeBase64Url / decodeBase64Url The default isomorphic encoder stages
isIsoDateString ISO date string detector for default codec date revival
parsePaginationParams(source, options?) Untrusted query params / records → PaginationInput (never throws)
fromRelayArgs(args, options?) first/after/last/before → cursor input
toRestEnvelope(result) → { data, meta }
toRelayConnection(result, cursorFor?) → Relay connection; cursorFor(item, index) per edge
infinitePaginationOptions(paginator, options?) → TanStack useInfiniteQuery config fragment (cursor paginator required)
createKeysetSpec(options) Portable keyset where() / orderBy() AST for ORM adapters
toKeysetWhereSql(where, columns, options?) Render keyset WHERE as parameterized SQL + params
toKeysetOrderBySql(order, columns) Render keyset ORDER BY from validated column identifiers
assertSqlIdentifier(identifier) Validate unquoted SQL identifiers used by raw SQL helpers

Key types: PaginationInput, Paginated<T>, PageInfo, OffsetWindow, CursorWindow<TCursor>, PaginationFetchResult<T>, Paginator<T> / PaginatorSync<T> / PaginatorMaybeAsync<T>, CursorCodec<T> / CursorCodecMaybeAsync<T>, RelayArgs, RelayConnection<T>, RestEnvelope<T>, InfinitePaginationOptions<T>, ParsePaginationParamsOptions, PaginationParamsSource, KeysetSpec, KeysetWhere, KeysetSortKey, KeysetSqlFragment, ToKeysetSqlOptions.


Why can’t I use a cursor with fetchOffset? A cursor identifies a value, not a position — there is no general conversion. Provide fetchCursor for cursor traffic (you can support both styles on one paginator).

My pages skip/duplicate rows near boundaries. Your sort isn’t deterministic. Cursor keys must mirror the full ORDER BY including a unique tiebreaker, and the keyset WHERE must compare the whole tuple.

Why does my fetcher get limit: 21 when I asked for 20? The one-row lookahead. Return up to that many rows; the paginator slices to 20 and uses row 21’s existence as hasNextPage.

Backward pages look reversed in my fetcher but correct outside. By design: backward fetchers flip the sort, the paginator restores natural order, so consumers never branch on direction.

A bad ?cursor= crashes my route. Decoding malformed tokens throws — that’s your 400. Wrap the paginate call in tryCatch/try-catch at the boundary (example in the REST section).

Do clients need this library to consume my API? No. Tokens are plain strings; clients just echo meta.endCursor back as ?cursor=. The library is useful client-side only when the client owns pagination state (TanStack infinite queries, local data).

Where’s the React entry? Not needed — infinitePaginationOptions is a plain object factory in the zero-dep core, compatible with every TanStack Query adapter.

Why does parsePaginationParams not throw on page=abc? Transport params are untrusted and often partial — silent defaults are safer than 400s for missing/malformed page numbers. Cursor decode errors happen later in paginate where you control the response.

Can I paginate with only fetchCursor? Yes for cursor requests. Page/ offset requests still need fetchOffset.