Skip to content

Pagination: serving endpoints

REST — parsePaginationParams + toRestEnvelope

Section titled “REST — parsePaginationParams + toRestEnvelope”

parsePaginationParams turns untrusted transport params into a PaginationInput, with defaults, clamping (maxPageSize: 100 by default — nobody gets to ask for ?page_size=99999), and alias support.

import { tryCatch } from "@xtandard/lib";
import { parsePaginationParams, toRestEnvelope } from "@xtandard/lib/pagination";
Bun.serve({
routes: {
"/api/users": async (req) => {
const input = parsePaginationParams(new URL(req.url).searchParams, {
defaultPageSize: 20,
maxPageSize: 100,
});
// tryCatch guards malformed cursor tokens (they throw on decode)
const [result, error] = await tryCatch(async () => userPaginator.paginate(input));
if (error) return new Response("Invalid pagination params", { status: 400 });
return Response.json(toRestEnvelope(result));
// → { data: [...], meta: { hasNextPage, endCursor, page, totalItems, ... } }
},
},
});
import { tryCatch } from "@xtandard/lib";
import { parsePaginationParams, toRestEnvelope } from "@xtandard/lib/pagination";
export async function GET(req: Request) {
const input = parsePaginationParams(new URL(req.url).searchParams);
const [result, error] = await tryCatch(() => userPaginator.paginate(input));
if (error) return Response.json({ error: "Invalid pagination" }, { status: 400 });
return Response.json(toRestEnvelope(result));
}
import { Hono } from "hono";
import { tryCatch } from "@xtandard/lib";
import { parsePaginationParams, toRestEnvelope } from "@xtandard/lib/pagination";
const app = new Hono();
app.get("/api/users", async (c) => {
const input = parsePaginationParams(c.req.query());
const [result, error] = await tryCatch(() => userPaginator.paginate(input));
if (error) return c.json({ error: "Invalid pagination" }, 400);
return c.json(toRestEnvelope(result));
});
import { z } from "zod";
import { parsePaginationParams, toRestEnvelope } from "@xtandard/lib/pagination";
listUsers: publicProcedure
.input(
z.object({
page: z.coerce.number().optional(),
page_size: z.coerce.number().optional(),
cursor: z.string().optional(),
limit: z.coerce.number().optional(),
}),
)
.query(async ({ input }) => {
const paginated = await userPaginator.paginate(parsePaginationParams(input));
return toRestEnvelope(paginated);
}),

It also accepts plain records (e.g. an already-parsed body): parsePaginationParams({ page: "2", per_page: "10" }).

Style detection (first match wins):

  1. cursor — cursor, after, or before present (before ⇒ backward)
  2. offset — offset or skip present
  3. page — page present
  4. fallback — options.fallback ("page" default) with defaults

Param aliases:

Role Accepted keys
page number page
page size page_size, pageSize, per_page, perPage, size
limit limit, take, first, last
offset offset, skip
cursor token cursor, after (forward), before (backward)
direction direction=backward (with cursor/after)

Options (ParsePaginationParamsOptions):

Option Default Notes
defaultPageSize 20 when no size param present
maxPageSize 100 pass Infinity to disable clamping
fallback "page" "offset" or "cursor" when no style params

Behavior notes:

  • Never throws — malformed values (page=abc, empty strings) fall back to defaults (page: 1, pageSize: defaultPageSize)
  • page floors to 1; offset floors to 0; sizes floor to 1 then clamp
  • Record sources accept string | number | string[] per key; arrays use the first element ({ page: ["4"], size: ["5", "9"] } → page 4, size 5)
  • cursor wins over offset and page when multiple style params appear
  • before alone ⇒ backward cursor with default size; after alone ⇒ forward
  • first/last double as size params for Relay-style query strings

GraphQL / Relay — fromRelayArgs + toRelayConnection

Section titled “GraphQL / Relay — fromRelayArgs + toRelayConnection”

fromRelayArgs maps connection args to a cursor input (first/after → forward, last/before → backward). toRelayConnection emits a spec-compliant connection; pass paginator.cursorFor so every edge gets its own cursor:

import { fromRelayArgs, toRelayConnection } from "@xtandard/lib/pagination";
const resolvers = {
Query: {
users: async (_parent, args /* { first, after, last, before } */) => {
const result = await userPaginator.paginate(fromRelayArgs(args, { maxPageSize: 100 }));
return toRelayConnection(result, paginator.cursorFor);
// → { edges: [{ node, cursor }], pageInfo: { hasNextPage, ..., endCursor } }
},
},
};
Args Result
{ first: 10, after: "x" } forward, limit 10, cursor "x"
{ last: 5, before: "y" } backward, limit 5, cursor "y"
{ before: "y" } backward, default limit (20), cursor "y"
{ last: 5 } backward from end, no cursor
{} forward first page, default limit
both last and first last/before wins (backward branch checked first)

toRelayConnection(result, cursorFor?) — cursorFor signature is (item: T, index: number) => string. Without it, edges[].cursor is null but pageInfo.startCursor/endCursor from the paginator are still copied.

Paginated<T> results compose with createLoader (from @xtandard/lib/dataloader) — paginate the page of IDs, batch-load the rows:

const idPaginator = createPaginator({
fetchCursor: async ({ limit, cursor }) => ({ items: await fetchIdsAfter(cursor?.id, limit) }),
cursor: { fromItem: (row) => ({ id: row.id }) },
});
const page = await idPaginator.paginate(input);
const users = await Promise.all(page.items.map((row) => userLoader.load(row.id)));

Tokens are produced by a two-stage pipeline, every stage replaceable (signature-compatible with drizzle-cursor, so custom stages can be shared):

flowchart TB
  subgraph encode["encode (default: JSON → base64url)"]
    direction LR
    D1["data"] -->|serializer| S1["string"] -->|encoder| T1["token"]
  end
  subgraph decode["decode"]
    direction RL
    T2["token"] -->|decoder| S2["string"] -->|parser| D2["data"]
  end
  encode ~~~ decode
import { createCursorCodec } from "@xtandard/lib/pagination";
createCursorCodec(); // JSON + base64url (sync)
createCursorCodec({ reviveDates: false }); // skip ISO-string → Date revival on decode
createCursorCodec({ serializer: superjson.stringify, parser: superjson.parse });
createCursorCodec({
// encrypted cursors — async codec
encoder: (s) => encryptWithSubtleCrypto(s), // returns Promise<string>
decoder: (t) => decryptWithSubtleCrypto(t),
});
const codec = createCursorCodec<{ id: number }>();
const token = codec.encode({ id: 42 });
const data = codec.decode(token); // { id: 42 }

Useful for signing bookmark links, WebSocket resume tokens, or sharing codecs with drizzle-cursor.

Notes:

  • Dates round-trip by default: JSON.stringify emits ISO strings, decode revives top-level ISO-looking strings back into Dates (matching drizzle-cursor). If a cursor field is a string that merely looks like a date (a "2024-06-11" SKU), pass reviveDates: false.
  • isIsoDateString — helper used by the default parser to detect ISO-shaped strings for date revival. It checks the pattern, the calendar and Date.parse: "2024-02-30" fails (and stays a string) instead of reviving as a rolled-over March 1.
  • encodeBase64Url / decodeBase64Url — the default encoder/decoder stages, exported for reuse (encodeBase64Url('{"id":7}') → "eyJpZCI6N30"). Both handle non-Latin1 text and run in browsers and edge runtimes.
  • Opaque ≠ secret. base64url hides structure from casual eyes but anyone can decode it. Don’t put sensitive values in cursors, or use an encrypting/signing encoder.
  • Malformed tokens throw on decode (bad base64, garbage JSON). Treat cursor params as untrusted input — wrap paginate in try/catch / tryCatch at the API boundary and answer 400 (see the REST example).
  • An async stage (WebCrypto) makes the codec — and cursorFor — Promise -returning, tracked in the types (see tiers below).

Threat Mitigation
huge ?page_size= / ?limit= parsePaginationParams({ maxPageSize }) + maxLimit on paginator
cursor tampering treat as untrusted; HMAC/sign in encoder/decoder, or encrypt
sensitive data in cursors never — cursors round-trip to clients; use opaque IDs only
deep OFFSET scans prefer cursor for public/large tables; cap page number if needed

Signing pattern (sketch):

createCursorCodec({
encoder: (payload) => sign(payload, SECRET),
decoder: (token) => {
const payload = verify(token, SECRET); // throws if tampered
return JSON.parse(payload);
},
});

Layer Throws? When
parsePaginationParams never malformed input → sane defaults
fromRelayArgs never missing args → defaults
toOffsetWindow never clamps invalid numbers
createPaginator config sync missing fetchOffset/fetchCursor for requested style
cursorFor sync no cursor.fromItem configured
codec.decode sync malformed token (bad base64, invalid JSON)
fetchers your DB connection errors, syntax errors — propagate as you prefer

Wrap paginate at HTTP boundaries; let parsePaginationParams handle garbage query strings silently.