Pagination: reference
Sync/async tiers
Section titled “Sync/async tiers”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.
TypeScript: which paginator type?
Section titled “TypeScript: which paginator type?”| 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.
Performance
Section titled “Performance”- Skip
totalItemswhenCOUNT(*)is expensive — lookahead still gives correcthasNextPage; you losetotalPages(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.
Migration
Section titled “Migration”From hand-rolled ?page=&limit=
Section titled “From hand-rolled ?page=&limit=”- Move slice/query logic into
fetchOffset - Replace manual offset math with
parsePaginationParams+toRestEnvelope - Add
cursor.fromItemwhen you wantmeta.endCursorwithout cursor fetch yet
From Relay / graphql-relay
Section titled “From Relay / graphql-relay”- Replace
connectionFromArray(in-memory) withcreatePaginator+ DB fetcher - Swap arg parsing for
fromRelayArgs, response shaping fortoRelayConnection - Pass
paginator.cursorForas the edge cursor function
From Prisma cursor + skip: 1 only
Section titled “From Prisma cursor + skip: 1 only”Add fetchOffset for admin pages; keep your existing findMany as
fetchCursor. One paginator, both styles.
Testing
Section titled “Testing”Executable specs live in:
test/pagination.test.ts— paginator, lookahead, backward,pages()/items(), sync tier,maxLimittest/pagination-params.test.ts—parsePaginationParams,fromRelayArgstest/pagination-output.test.ts— REST/Relay/infinite adapterstest/cursor-codec.test.ts— encode/decode, date revival, custom stages
Fetcher contract checklist (mirror these in your integration tests):
- fetcher returns up to
limitrows (including lookahead row) -
hasNextPagetrue when extra row present, false on last page - backward fetcher returns flipped order; consumer sees natural order
- composite cursor
WHEREmatchesORDER BYcolumns + tiebreaker - malformed
?cursor=→ 400 at boundary, not 500 -
maxPageSize/maxLimitclamp honored
API reference
Section titled “API reference”| 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.
Gotchas & FAQ
Section titled “Gotchas & FAQ”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.