Pagination & cursor helpers
List endpoints need a way to page through results that is stable under concurrent writes, cheap on the database, and self-describing in the contract. DaloyJS ships built-in, dependency-free cursor-pagination helpers that cover all three concerns: an opaque cursor codec, an RFC 8288 Link header builder, and a paginationQuery() Standard Schema that validates the cursor / limit query parameters and wires them into the generated OpenAPI document and typed client.
Everything is built on Web-standard URL, btoa / atob, and JSON, so it runs unchanged on Node, Bun, Deno, and Cloudflare Workers.
- 01validatepaginationQuery()typed { limit, cursor }
- 02decodedecodeCursor()opaque token to sort key
- 03queryFetch limit + 1 rowsone extra row reveals next page
- 04encodeencodeCursor(last row)next cursor or null
- 05advertisebuildPageLinks() Link headerrel=next · prev · first
Quick start
Mount paginationQuery() as the route's request.query. The handler receives a fully typed, validated { limit, cursor }. Build the next cursor from the last row and advertise it with a Link header.
Opaque cursors
encodeCursor() serializes any JSON-serializable value (typically the sort key of the last row) into a compact, URL-safe base64url token. decodeCursor() reverses it.
Decoding is hardened: the input is capped at MAX_CURSOR_LENGTH (4 KiB), malformed base64url and invalid JSON are rejected, and any __proto__ / constructor / prototype keys in the decoded graph are stripped (prototype-pollution defense). A tampered cursor surfaces as a 400 Bad Request, not a 500.
The token is opaque, not secret: anyone can base64url-decode it, change { offset: 20 } to { offset: 0 }, and re-encode it. That is fine while the handler re-scopes the query by the authenticated principal and treats the cursor as a resume hint. When the cursor carries anything the query relies on, sign it.
Signed cursors
createCursorCodec() (since 1.16.0) returns an encode/decode pair whose tokens carry an HMAC-SHA256 signature, so a decoded payload is known to be the server's own. Use it when the cursor embeds a tenant id, a filter, or a sort boundary that must not be skipped.
- Format is
<base64url(json)>.<base64url(hmac)>, with the expiry folded into the signed bytes whenttlSecondsis set, so it cannot be extended. decode()applies the same 4 KiB cap, strict base64url, and prototype-pollution stripping asdecodeCursor(), and verifies the MAC in constant time before the JSON is parsed.- Every failure — a tampered payload, a signature from another key, a truncated or flipped MAC, an expired or unsigned token — is one
400 Invalid pagination cursor., so the response never says which check failed. secretmay be a list for rotation: the first entry signs, every entry verifies, so outstanding cursors stay valid until they age out.- Runs on Web Crypto (
crypto.subtle), so it works on every supported runtime.
RFC 8288 Link header
buildPageLinks() clones the current request URL and swaps its cursor query parameter to produce next, prev, and first page URLs, preserving every other query parameter (filters, limit, ...), then serializes them into a single Link header.
Need lower-level control? buildLinkHeader() serializes an explicit list of { url, rel, title? } entries. Both builders reject control characters, </> in URLs, and "/\\ in rel/title values: a structural defense against Link-header / response-splitting injection.
OpenAPI parameter wiring
Because paginationQuery() exposes a toJSONSchema() method, the OpenAPI generator emits the cursor and limit query parameters into the contract automatically, with no duplicate parameter declarations, and the typed client picks them up on the next pnpm gen.
At runtime the same schema coerces limit from its string query value to an integer and rejects out-of-range or non-integer values at the request boundary with a 422. Customize the parameter names and bounds:
Security notes
- Cursors are opaque. They are encoded without encryption or a signature. Never trust a decoded cursor for authorization. Always re-scope the underlying query by the authenticated principal on the server.
decodeCursor()caps input length, rejects malformed tokens, and strips prototype-pollution keys, so a hostile cursor cannot crash the handler or poison object prototypes.- The
Linkbuilders reject CRLF, angle brackets, and quote characters, preventing header-injection through computed URLs or titles. maxLimitbounds the page size a client can request, protecting the database from unbounded scans.