Skip to content

Pagination: data source recipes

The core pagination package is data-source agnostic. Use a first-party adapter when it materially improves type safety or builder ergonomics; otherwise use the raw SQL helpers or plain fetcher examples directly.

Data source Recommended path
In-memory arrays createMemoryPaginator (filters/memory)
Raw SQL drivers (pg, mysql2, etc) toKeysetWhereSql + toKeysetOrderBySql
Prisma Client @xtandard/lib/pagination/prisma or Prisma raw SQL
Drizzle ORM (db.select) @xtandard/lib/pagination/drizzle
Drizzle RQB v2 (db.query) @xtandard/lib/pagination/drizzle-rqb
Kysely @xtandard/lib/pagination/kysely
MikroORM QueryBuilder + raw SQL fragments
TypeORM QueryBuilder + Brackets + raw SQL fragments
Sequelize Op.or / Op.and objects or raw SQL fragments
Knex.js @xtandard/lib/pagination/knex
Objection.js Knex adapter through query()
AdonisJS Lucid Knex-style whereRaw / orderByRaw
Slonik raw SQL helper params passed through sql.array-style
Postgres.js @xtandard/lib/pagination/sql-tag
Bun.sql (Postgres, MySQL, SQLite) @xtandard/lib/pagination/sql-tag
PgTyped generated SQL with explicit cursor params
Zapatos raw SQL helper fragments or conditions objects
@databases raw SQL helper params with tagged SQL
ts-sql-query native dynamic boolean expressions
SafeQL raw SQL recipe; SafeQL validates it
@effect/sql raw SQL helper params inside Effect queries
Bookshelf.js Knex adapter via query((qb) => ...)
Waterline offset pagination; cursor recipe when datastore allows
MassiveJS raw SQL helper params
MongoDB / Mongoose @xtandard/lib/pagination/mongo
Firestore native ordered cursors (startAfter, endBefore)
DynamoDB LastEvaluatedKey / ExclusiveStartKey
Redis sorted sets ZRANGE/ZREVRANGE by score + member
PostgREST / Supabase @xtandard/lib/filters/postgrest keyset
Elasticsearch / OpenSearch @xtandard/lib/filters/elasticsearch keyset
Meilisearch / Typesense offset by default; cursor only if using stable filters
ClickHouse raw SQL helper params
BigQuery / Snowflake raw SQL helper params for stable export pagination

For every recipe, keep the same safety boundary: request data may become bound values, never identifiers or expression strings. Column maps, field maps, index names, and computed expressions must be server-owned constants.

createMemoryPaginator from @xtandard/lib/filters/memory is createPaginator with array fetchers: it sorts the rows once, slices them for page/offset requests (with totalItems), and seeks with a keyset for cursor requests, forward or backward. Every fetcher is synchronous, so paginate returns plain values:

import { applyFiltersToArray, createMemoryPaginator } from "@xtandard/lib/filters/memory";
const paginator = createMemoryPaginator({
rows: applyFiltersToArray(rows, { spec, filters }), // optional: filter first
sort: [{ key: "createdAt", order: "desc" }, { key: "id" }], // unique tiebreaker last
maxLimit: 100,
});
// all-sync tier: plain values, no await, usable in a render path
const { items, pageInfo } = paginator.paginate({ type: "page", page: 1, pageSize: 10 });
const next = paginator.paginate({ type: "cursor", limit: 10, cursor: pageInfo.endCursor });

Sort keys read paths[key] (a key, dot path or getter) or the key itself. NULL sort keys sort like Postgres (dialect: "sqlite" or nulls: "first" | "last" to change it) and page correctly. For offset only, a plain slice fetcher is enough:

const paginator = createPaginator({
fetchOffset: ({ limit, offset }) => ({
items: rows.slice(offset, offset + limit),
totalItems: rows.length,
}),
});

For ORDER BY created_at ASC, id ASC forward pagination after cursor { createdAt, id }:

SELECT *
FROM posts
WHERE (created_at, id) > ($1::timestamptz, $2::bigint)
ORDER BY created_at ASC, id ASC
LIMIT $3;

Backward flips the comparator and sort:

SELECT *
FROM posts
WHERE (created_at, id) < ($1::timestamptz, $2::bigint)
ORDER BY created_at DESC, id DESC
LIMIT $3;

First page: omit the WHERE (cursor is null). The paginator reverses backward results back to natural order.

The zero-dependency raw SQL helpers produce parameterized fragments from the portable keyset AST. Cursor values are never interpolated into SQL; they are returned in params. Column identifiers come from your hardcoded columns map and are validated with assertSqlIdentifier.

import {
createKeysetSpec,
createPaginator,
keysetSqlExpression,
toKeysetOrderBySql,
toKeysetWhereSql,
} from "@xtandard/lib/pagination";
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "asc" },
{ key: "id", order: "asc" },
],
});
const columns = {
createdAt: "created_at",
id: "id",
};
// `key` is logical cursor data, not necessarily a table column name.
// For computed values, mark server-owned SQL expressions explicitly:
const expressionColumns = {
normalizedName: keysetSqlExpression("upper(first_name || ' ' || last_name)"),
id: "id",
};
const paginator = createPaginator({
fetchCursor: async ({ limit, cursor, direction }) => {
const where = toKeysetWhereSql(keyset.where(cursor, direction), columns);
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), columns);
const sql = `
SELECT *
FROM posts
${where.sql ? `WHERE ${where.sql}` : ""}
ORDER BY ${orderBy}
LIMIT $${where.params.length + 1}
`;
return { items: (await pg.query(sql, [...where.params, limit])).rows };
},
cursor: { fromItem: (post) => ({ createdAt: post.createdAt, id: post.id }) },
});

For a cursor { createdAt: "2024-01-01", id: 42 }, the helper emits:

{
sql: "(created_at > $1) OR (created_at = $2 AND id > $3)",
params: ["2024-01-01", "2024-01-01", 42],
}

That OR of growing prefixes is built by generateSubArrays (also exported, for writing your own adapter): generateSubArrays(["createdAt", "id"]) returns [["createdAt"], ["createdAt", "id"]], one branch per prefix.

Knex whereRaw accepts SQL plus bindings. Use ? placeholders:

import { applyKeysetToKnex } from "@xtandard/lib/pagination/knex";
fetchCursor: async ({ limit, cursor, direction }) => {
const q = applyKeysetToKnex(
knex("posts").select("*"),
keyset.where(cursor, direction),
keyset.orderBy(direction),
{ columns },
);
return { items: await q.limit(limit) };
};

applyKeysetToKnex is zero-dependency: it targets Knex’s structural whereRaw(sql, bindings) / orderByRaw(sql) shape, so knex remains your application dependency rather than a peer dependency of @xtandard/lib.

Prisma cannot parameterize identifiers in $queryRaw, so use $queryRawUnsafe only with SQL you build from server-owned, validated identifiers. Cursor values are still bound parameters:

fetchCursor: async ({ limit, cursor, direction }) => {
const where = toKeysetWhereSql(keyset.where(cursor, direction), columns);
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), columns);
const sql = `
SELECT *
FROM posts
${where.sql ? `WHERE ${where.sql}` : ""}
ORDER BY ${orderBy}
LIMIT $${where.params.length + 1}
`;
return { items: await prisma.$queryRawUnsafe(sql, ...where.params, limit) };
};

This stays injection-safe as long as columns is a hardcoded map and request data only reaches params.

Drizzle and Kysely both support raw SQL, but their safest path is a dedicated adapter that maps KeysetWhere into their expression builders instead of pre-rendering $1 strings. Until those adapters exist, prefer their native builder examples below. The core raw helper is best for drivers and APIs that already accept (sql, params) directly: pg, mysql2, better-sqlite3, Knex, and carefully-used Prisma raw queries.

Use @xtandard/lib/pagination/drizzle to turn the portable keyset AST into Drizzle where and orderBy SQL expressions. The adapter accepts Drizzle columns or sql expressions; cursor keys remain logical names.

import { sql } from "drizzle-orm";
import { createKeysetSpec, createPaginator } from "@xtandard/lib/pagination";
import { toDrizzleKeyset } from "@xtandard/lib/pagination/drizzle";
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "asc" },
{ key: "id", order: "asc" },
],
});
const drizzleKeyset = toDrizzleKeyset({
createdAt: users.createdAt,
id: users.id,
});
const expressionKeyset = toDrizzleKeyset({
normalizedName: sql<string>`upper(${users.firstName} || ' ' || ${users.lastName})`,
id: users.id,
});
const paginator = createPaginator({
fetchOffset: async ({ limit, offset }) => ({
items: await db
.select()
.from(users)
.orderBy(asc(users.createdAt), asc(users.id))
.limit(limit)
.offset(offset),
}),
fetchCursor: async ({ limit, cursor, direction }) => ({
items: await db
.select()
.from(users)
.where(drizzleKeyset.where(keyset.where(cursor, direction)))
.orderBy(...drizzleKeyset.orderBy(keyset.orderBy(direction)))
.limit(limit),
}),
cursor: { fromItem: (u) => ({ createdAt: u.createdAt, id: u.id }) },
});

drizzle-cursor remains useful for existing Drizzle-only projects. The lower-level codec pipeline is signature-compatible (see Cursor codecs), so custom cursor encoders/decoders can be shared.

For drizzle v1’s relational query builder (db.query.<table>.findMany), where/orderBy are plain OBJECTS, not SQL. Use @xtandard/lib/pagination/drizzle-rqb to render the keyset AST to those objects. It emits plain objects — no drizzle-orm import, no peer. Column keys are the RQBv2 schema PROPERTY keys.

import { createKeysetSpec, createPaginator } from "@xtandard/lib/pagination";
import { toDrizzleRqbKeyset } from "@xtandard/lib/pagination/drizzle-rqb";
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "desc" },
{ key: "id", order: "asc" },
],
});
const rqb = toDrizzleRqbKeyset({ createdAt: "createdAt", id: "id" });
const paginator = createPaginator({
fetchCursor: async ({ limit, cursor, direction }) => ({
items: await db.query.users.findMany({
where: rqb.where(keyset.where(cursor, direction)), // undefined = first page
orderBy: rqb.orderBy(keyset.orderBy(direction)), // { createdAt: "desc", id: "asc" }
limit,
}),
}),
cursor: { fromItem: (u) => ({ createdAt: u.createdAt, id: u.id }) },
});

Use the db.select() adapter (toDrizzleKeyset, above) for the core query builder; use this one when you want the RQB (relations, nested with). To filter the same RQB query, pair it with @xtandard/lib/filters/drizzle-rqb.

For the legacy RQB v1 (callback where/orderBy, e.g. db._query), toDrizzleRqbV1Keyset (same subpath) returns where(...)/orderBy(...) that yield those callbacks ((fields, operators) => …), building via the provided operators/fields:

import { toDrizzleRqbV1Keyset } from "@xtandard/lib/pagination/drizzle-rqb";
const rqbV1 = toDrizzleRqbV1Keyset({ createdAt: "createdAt", id: "id" });
const rows = await db._query.users.findMany({
where: rqbV1.where(keyset.where(cursor, direction)), // (fields, ops) => SQL | undefined
orderBy: rqbV1.orderBy(keyset.orderBy(direction)), // (fields, { asc, desc }) => SQL[]
limit,
});
import { sql } from "kysely";
import { createKeysetSpec, createPaginator } from "@xtandard/lib/pagination";
import { toKyselyKeyset } from "@xtandard/lib/pagination/kysely";
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "asc" },
{ key: "id", order: "asc" },
],
});
const kyselyKeyset = toKyselyKeyset({
createdAt: "users.created_at",
id: "users.id",
});
const expressionKeyset = toKyselyKeyset({
normalizedName: sql<string>`upper(first_name || ' ' || last_name)`,
id: "users.id",
});
const paginator = createPaginator({
fetchOffset: async ({ limit, offset }) => ({
items: await db
.selectFrom("users")
.selectAll()
.orderBy("created_at")
.orderBy("id")
.limit(limit)
.offset(offset)
.execute(),
}),
fetchCursor: async ({ limit, cursor, direction }) => {
let q = db.selectFrom("users").selectAll();
const where = kyselyKeyset.where(keyset.where(cursor, direction));
if (where) {
q = q.where(where);
}
for (const order of kyselyKeyset.orderBy(keyset.orderBy(direction))) {
q = q.orderBy(order);
}
return {
items: await q.limit(limit).execute(),
};
},
cursor: { fromItem: (u) => ({ createdAt: u.created_at, id: u.id }) },
});
import { createKeysetSpec, createPaginator } from "@xtandard/lib/pagination";
import { toPrismaKeyset } from "@xtandard/lib/pagination/prisma";
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "asc" },
{ key: "id", order: "asc" },
],
});
const prismaKeyset = toPrismaKeyset({
createdAt: "createdAt",
id: "id",
});
const paginator = createPaginator({
fetchOffset: async ({ limit, offset }) => ({
items: await prisma.user.findMany({
take: limit,
skip: offset,
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
}),
}),
fetchCursor: async ({ limit, cursor, direction }) => ({
items: await prisma.user.findMany({
take: limit,
where: prismaKeyset.where(keyset.where(cursor, direction)),
orderBy: prismaKeyset.orderBy(keyset.orderBy(direction)),
}),
}),
cursor: { fromItem: (u) => ({ createdAt: u.createdAt, id: u.id }) },
});

The Prisma adapter targets scalar fields. Prisma’s typed client cannot express arbitrary computed SQL keysets; use the raw SQL helpers (toKeysetWhereSql / toKeysetOrderBySql) with Prisma raw queries for computed expressions.

Every mapped field passes through assertPrismaField (exported from @xtandard/lib/pagination/prisma), which accepts a single identifier and throws on anything else, including dotted relation paths like author.name.

import { createKeysetSpec, createPaginator } from "@xtandard/lib/pagination";
import { toMongoKeyset } from "@xtandard/lib/pagination/mongo";
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "asc" },
{ key: "id", order: "asc" },
],
});
const mongoKeyset = toMongoKeyset({
createdAt: "createdAt",
id: "_id",
});
const paginator = createPaginator({
fetchOffset: async ({ limit, offset }) => ({
items: await Post.find().sort({ _id: 1 }).skip(offset).limit(limit),
}),
fetchCursor: async ({ limit, cursor, direction }) => ({
items: await Post.find(mongoKeyset.filter(keyset.where(cursor, direction)) ?? {})
.sort(mongoKeyset.sort(keyset.orderBy(direction)))
.limit(limit),
}),
cursor: { fromItem: (p) => ({ createdAt: p.createdAt, id: p._id.toString() }) },
});

The Mongo adapter accepts dotted field paths such as author.name, rejects operator-like field strings such as $where, and works with both the MongoDB driver and Mongoose’s find(filter).sort(sort) API. That check is exported as assertMongoFieldPath (it returns the path or throws), handy when you build other filters from configurable field names.

TypeORM’s query builder accepts grouped raw predicates via Brackets. Render the portable keyset AST with named placeholders and bind cursor values through .setParameters().

import { Brackets } from "typeorm";
import {
createKeysetSpec,
keysetSqlExpression,
toKeysetOrderBySql,
toKeysetWhereSql,
} from "@xtandard/lib/pagination";
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "asc" },
{ key: "id", order: "asc" },
],
});
const columns = {
createdAt: keysetSqlExpression("post.created_at"),
id: keysetSqlExpression("post.id"),
};
fetchCursor: async ({ limit, cursor, direction }) => {
const where = toKeysetWhereSql(keyset.where(cursor, direction), columns, {
placeholder: (index) => `:p${index}`,
});
const params = Object.fromEntries(where.params.map((value, index) => [`p${index + 1}`, value]));
const qb = repo.createQueryBuilder("post");
if (where.sql) qb.andWhere(new Brackets((q) => q.where(where.sql)), params);
return {
items: await qb
.orderBy(toKeysetOrderBySql(keyset.orderBy(direction), columns))
.limit(limit)
.getMany(),
};
};

MikroORM’s QueryBuilder can consume raw fragments through .where() and .orderBy(). Use a hardcoded SQL column map for the keyset predicate, and map natural offset ordering to entity property names when using object orderBy.

const columns = {
createdAt: keysetSqlExpression("p.created_at"),
id: keysetSqlExpression("p.id"),
};
fetchCursor: async ({ limit, cursor, direction }) => {
const where = toKeysetWhereSql(keyset.where(cursor, direction), columns, {
placeholder: "?",
});
const qb = em.createQueryBuilder(Post, "p").select("*");
if (where.sql) qb.where(where.sql, where.params);
return {
items: await qb
.orderBy(Object.fromEntries(keyset.orderBy(direction).map((o) => [o.key, o.order])))
.limit(limit)
.execute(),
};
};

Sequelize can express lexicographic keyset predicates as Op.or / Op.and objects. For simple scalar fields, build the filter from the keyset AST; for computed SQL expressions, use Sequelize.literal only with server-owned expressions and keep cursor values bound.

import { Op } from "sequelize";
import { createKeysetSpec } from "@xtandard/lib/pagination";
const sequelizeOps = { ">": Op.gt, ">=": Op.gte, "<": Op.lt, "<=": Op.lte, "=": Op.eq };
function toSequelizeWhere(where) {
if (!where) return undefined;
return {
[Op.or]: where.clauses.map((clause) => ({
[Op.and]: clause.predicates.map((predicate) => ({
[predicate.key]: { [sequelizeOps[predicate.op]]: predicate.value },
})),
})),
};
}
fetchCursor: async ({ limit, cursor, direction }) => ({
items: await User.findAll({
where: toSequelizeWhere(keyset.where(cursor, direction)),
order: keyset.orderBy(direction).map((o) => [o.key, o.order.toUpperCase()]),
limit,
}),
});

Objection is Knex-backed, so use the Knex adapter against Model.query().

import { applyKeysetToKnex } from "@xtandard/lib/pagination/knex";
fetchCursor: async ({ limit, cursor, direction }) => {
const q = applyKeysetToKnex(
Person.query(),
keyset.where(cursor, direction),
keyset.orderBy(direction),
{ columns: { createdAt: "created_at", id: "id" } },
);
return { items: await q.limit(limit) };
};

Lucid’s query builder has Knex-compatible raw methods, so the Knex adapter is usually enough.

fetchCursor: async ({ limit, cursor, direction }) => {
const q = applyKeysetToKnex(
Post.query(),
keyset.where(cursor, direction),
keyset.orderBy(direction),
{ columns: { createdAt: "created_at", id: "id" } },
);
return { items: await q.limit(limit) };
};

Slonik’s tagged SQL API should own SQL composition. Use the raw helper for the predicate shape and pass cursor values as bound values. Keep columns server-owned.

const where = toKeysetWhereSql(keyset.where(cursor, direction), columns, {
placeholder: (index) => `$${index}`,
});
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), columns);
const result = await pool.query(
sql.unsafe`
SELECT * FROM posts
${where.sql ? sql.unsafe`WHERE ${sql.unsafe([where.sql])}` : sql.fragment``}
ORDER BY ${sql.unsafe([orderBy])}
LIMIT ${limit}
`,
where.params,
);

If your Slonik policy disallows unsafe fragments, write the few supported keyset predicates manually with sql.identifier for each server-owned column.

@xtandard/lib/pagination/sql-tag renders the keyset as fragments of your own sql tag, so the query stays one tagged template: cursor values are parameters, column strings are validated and quoted by sql(identifier), and a computed sort key is just another fragment of your sql. Works with postgres.js v3 and v4, including the sql of a transaction.

import postgres from "postgres";
import { createKeysetSpec, createPaginator } from "@xtandard/lib/pagination";
import { toSqlTagKeyset } from "@xtandard/lib/pagination/sql-tag";
const sql = postgres(process.env.DATABASE_URL);
const keyset = createKeysetSpec({
sort: [
{ key: "createdAt", order: "desc" },
{ key: "id", order: "desc" },
],
});
const posts = toSqlTagKeyset(sql, {
createdAt: "posts.created_at",
id: "posts.id",
// computed key: normalizedTitle: sql`lower(${sql("posts.title")})`,
});
const paginator = createPaginator({
fetchCursor: async ({ limit, cursor, direction }) => {
const where = posts.where(keyset.where(cursor, direction)); // undefined on the first page
const items = await sql`
select * from posts
${where ? sql`where ${where}` : sql``}
order by ${posts.orderBy(keyset.orderBy(direction))}
limit ${limit}
`;
return { items: [...items] };
},
cursor: { fromItem: (p) => ({ createdAt: p.created_at, id: p.id }) },
});
// where (("posts"."created_at" < $1) OR ("posts"."created_at" = $2 AND "posts"."id" < $3))
// order by "posts"."created_at" DESC, "posts"."id" DESC limit $4

posts.orderBy(…) is one comma-joined fragment (both clients join an array of fragments with spaces). The fragments are lazy queries: embed them, don’t await them on their own. To filter the same query, @xtandard/lib/filters/sql-tag renders filters the same way (see the filters guide).

Bun.sql uses the same adapter and the same code: pass Bun’s sql (or a new SQL(…)) instead. It works on all three of Bun’s adapters, since the client numbers the placeholders and quotes identifiers itself (backticks on MySQL).

PgTyped works best when the SQL is static. Write the supported keyset shape in SQL and let PgTyped generate types for the cursor params.

/* @name listPostsAfter */
SELECT *
FROM posts
WHERE (:createdAt::timestamptz IS NULL)
OR (created_at > :createdAt::timestamptz)
OR (created_at = :createdAt::timestamptz AND id > :id::bigint)
ORDER BY created_at ASC, id ASC
LIMIT :limit!;

Use createPaginator to normalize inputs and call the generated PgTyped function from fetchCursor.

Zapatos can run SQL fragments directly. Use the raw SQL helper when the query is too dynamic for conditions.

const where = toKeysetWhereSql(keyset.where(cursor, direction), columns);
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), columns);
const rows = await db.sql`
SELECT * FROM ${"posts"}
${db.raw(where.sql ? `WHERE ${where.sql}` : "")}
ORDER BY ${db.raw(orderBy)}
LIMIT ${db.param(limit)}
`.run(pool, where.params);

@databases/pg and @databases/mysql expose tagged SQL APIs. Keep identifier fragments static and bind cursor values.

const where = toKeysetWhereSql(keyset.where(cursor, direction), columns);
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), columns);
const rows = await db.query(
sql`
SELECT * FROM posts
${where.sql ? sql.__dangerous__rawValue(`WHERE ${where.sql}`) : sql``}
ORDER BY ${sql.__dangerous__rawValue(orderBy)}
LIMIT ${limit}
`,
where.params,
);

ts-sql-query can model the predicate in its own expression system. Use the keyset AST as the portable source of truth, then convert each predicate to a builder comparison.

const fields = { createdAt: t.createdAt, id: t.id };
function toTsSqlQueryWhere(where) {
if (!where) return undefined;
return connection.or(
...where.clauses.map((clause) =>
connection.and(
...clause.predicates.map((p) => {
const field = fields[p.key];
if (p.op === ">") return field.greaterThan(p.value);
if (p.op === "<") return field.lessThan(p.value);
return field.equals(p.value);
}),
),
),
);
}

SafeQL is not a query builder; it validates SQL strings. Prefer static SQL for each supported sort shape and call it from fetchCursor. If you use the raw helpers, keep the columns map fixed so the generated SQL shape is still reviewable.

// SafeQL validates the static query; createPaginator supplies typed params.
const posts = await sql`
SELECT * FROM posts
WHERE created_at > ${cursor.createdAt}
OR (created_at = ${cursor.createdAt} AND id > ${cursor.id})
ORDER BY created_at ASC, id ASC
LIMIT ${limit}
`;

Wrap the same fetcher contract in an Effect. createPaginator does not care whether your data source is Effect-powered as long as fetchCursor returns a Promise or a plain value.

fetchCursor: ({ limit, cursor, direction }) =>
Effect.runPromise(
Effect.gen(function* () {
const client = yield* SqlClient.SqlClient;
const where = toKeysetWhereSql(keyset.where(cursor, direction), columns);
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), columns);
const items = yield* client.unsafe(
`SELECT * FROM posts ${where.sql ? `WHERE ${where.sql}` : ""} ORDER BY ${orderBy} LIMIT $${where.params.length + 1}`,
[...where.params, limit],
);
return { items };
}),
);

Bookshelf models expose the underlying Knex query builder through .query().

fetchCursor: async ({ limit, cursor, direction }) => {
const collection = await Post.collection()
.query((qb) => {
applyKeysetToKnex(qb, keyset.where(cursor, direction), keyset.orderBy(direction), {
columns,
});
qb.limit(limit);
})
.fetch();
return { items: collection.toArray() };
};

Waterline is offset-first. Use fetchOffset when you are targeting multiple datastores through the same model API.

const paginator = createPaginator({
fetchOffset: async ({ limit, offset }) => ({
items: await User.find().sort("createdAt ASC").skip(offset).limit(limit),
}),
});

For cursor pagination, drop down to the datastore’s native query API and use that backend’s recipe (sendNativeQuery for SQL, Mongo criteria for MongoDB).

MassiveJS is SQL-centric, so use the raw helper output with parameter arrays.

const where = toKeysetWhereSql(keyset.where(cursor, direction), columns);
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), columns);
const items = await db.query(
`SELECT * FROM posts ${where.sql ? `WHERE ${where.sql}` : ""} ORDER BY ${orderBy} LIMIT $${where.params.length + 1}`,
[...where.params, limit],
);

Firestore has native cursor methods, but the cursor is positional: it must contain values in the same order as the orderBy calls. Include a unique tiebreaker such as FieldPath.documentId().

import { FieldPath } from "firebase-admin/firestore";
const paginator = createPaginator({
fetchCursor: async ({ limit, cursor, direction }) => {
const descending = direction === "backward";
let q = db
.collection("posts")
.orderBy("createdAt", descending ? "desc" : "asc")
.orderBy(FieldPath.documentId(), descending ? "desc" : "asc")
.limit(limit);
if (cursor) {
q = q.startAfter(cursor.createdAt, cursor.id);
}
const snap = await q.get();
return { items: snap.docs.map((doc) => ({ id: doc.id, ...doc.data() })) };
},
cursor: { fromItem: (p) => ({ createdAt: p.createdAt, id: p.id }) },
});

Firestore requires composite indexes for multi-field ordering. Backward pagination flips the ordering; the paginator reverses rows back to natural order.

DynamoDB is not general keyset pagination over arbitrary fields. Its native pagination token is LastEvaluatedKey, which must be passed back as ExclusiveStartKey. Derive that key from the last item on the page when querying one partition or a single index.

const paginator = createPaginator({
fetchCursor: async ({ limit, cursor }) => {
const result = await client.send(
new QueryCommand({
TableName: "Posts",
KeyConditionExpression: "tenantId = :tenantId",
ExpressionAttributeValues: { ":tenantId": { S: tenantId } },
ExclusiveStartKey: cursor?.exclusiveStartKey,
Limit: limit,
ScanIndexForward: true,
}),
);
return { items: result.Items ?? [] };
},
cursor: {
fromItem: (item) => ({
exclusiveStartKey: { tenantId: item.tenantId, sk: item.sk },
}),
},
});

If you need stable ordering by createdAt, model it as the table or GSI sort key (PK = tenant, SK = createdAt#id). Avoid Scan for cursor pagination.

Redis cursor pagination is practical for sorted sets. Use score plus member as the stable cursor; the member acts as the tiebreaker when multiple items share the same score.

const paginator = createPaginator({
fetchCursor: async ({ limit, cursor, direction }) => {
const reverse = direction === "backward";
const command = reverse ? "ZREVRANGEBYSCORE" : "ZRANGEBYSCORE";
const min = cursor && !reverse ? `(${cursor.score}` : "-inf";
const max = cursor && reverse ? `(${cursor.score}` : "+inf";
const rows = await redis.send(command, ["feed", min, max, "WITHSCORES", "LIMIT", 0, limit]);
return { items: pairsToItems(rows) };
},
cursor: { fromItem: (item) => ({ score: item.score, member: item.id }) },
});

For strict no-duplicate behavior when scores collide, encode the tiebreaker in the score or use lexicographic sorted-set commands with a composite member.

createPostgrestKeyset from @xtandard/lib/filters/postgrest renders the lexicographic seek as an or=(…) param and the sort as order terms; offset requests use PostgREST’s limit/offset (.range() in supabase-js). Combine with buildParams filters: PostgREST ANDs every param.

import { createPaginator } from "@xtandard/lib/pagination";
import {
applyParamsToPostgrest,
buildParams,
createPostgrestKeyset,
} from "@xtandard/lib/filters/postgrest";
const keyset = createPostgrestKeyset({
sort: [
{ key: "createdAt", order: "desc" },
{ key: "id", order: "desc" },
],
columns: { createdAt: "created_at", id: "id" },
});
const { params: filterParams } = buildParams({ spec, filters, resolveDate });
const paginator = createPaginator({
fetchOffset: async ({ limit, offset }) => {
const { data } = await applyParamsToPostgrest(supabase.from("posts").select("*"), filterParams)
.order("created_at", { ascending: false })
.order("id", { ascending: false })
.range(offset, offset + limit - 1);
return { items: data ?? [] };
},
fetchCursor: async ({ limit, cursor, direction }) => {
let query = applyParamsToPostgrest(supabase.from("posts").select("*"), [
...filterParams,
...keyset.where(cursor, direction),
]);
for (const t of keyset.orderBy(direction)) query = query.order(t.column, t);
const { data } = await query.limit(limit);
return { items: data ?? [] };
},
cursor: { fromItem: (p) => ({ createdAt: p.created_at, id: p.id }) },
});

Without supabase-js, send the same params with fetch: new URLSearchParams([...filterParams, ...keyset.where(cursor, direction), ["order", formatOrder(keyset.orderBy(direction))!], ["limit", String(limit)]]).

Use search_after with a deterministic sort. Always include a unique tiebreaker field; Elasticsearch often uses a doc-values (keyword) copy of _id. createElasticsearchKeyset from @xtandard/lib/filters/elasticsearch gives the sort for a direction ("backward" flips it; the paginator restores the order) and the matching search_after values, and buildQuery renders the filters.

import { createPaginator } from "@xtandard/lib/pagination";
import { buildQuery, createElasticsearchKeyset } from "@xtandard/lib/filters/elasticsearch";
const keyset = createElasticsearchKeyset({
sort: [
{ key: "createdAt", order: "desc" },
{ key: "id", order: "desc" },
],
fields: { createdAt: "createdAt", id: "idKeyword" },
});
const { query } = buildQuery({ spec, filters, resolveDate });
const filter = [{ term: { tenantId } }, ...(query ? [query] : [])];
const paginator = createPaginator({
fetchCursor: async ({ limit, cursor, direction }) => {
const response = await elastic.search({
index: "posts",
size: limit,
query: { bool: { filter } },
sort: keyset.sort(direction),
search_after: keyset.searchAfter(cursor),
});
return { items: response.hits.hits.map((hit) => hit._source!) };
},
cursor: { fromItem: (p) => ({ createdAt: Date.parse(p.createdAt), id: p.id }) }, // epoch ms, like hit.sort
});

searchAfter(cursor) returns the cursor values in sort order (a Date becomes epoch milliseconds, which is what a date field’s hit.sort holds; keep date cursors as numbers so they survive the cursor codec’s JSON). Keep fields complete: search_after must have one value per sort entry. For deep exports, pair search_after with a point in time (pit) so the snapshot stays consistent between pages.

These search engines are usually offset-first for public search result pages. Use fetchOffset unless you have a stable sortable field and the engine/API supports search-after-style pagination for your query.

const paginator = createPaginator({
fetchOffset: async ({ limit, offset }) => {
const result = await index.search(query, { limit, offset });
return { items: result.hits, totalItems: result.estimatedTotalHits };
},
});

For live feeds or audit logs, prefer the database/index behind the search engine for cursor pagination and use search only for relevance-ranked pages.

ClickHouse supports normal SQL keyset pagination. Prefer keyset pagination for append-only analytics tables; OFFSET can be expensive on large result sets.

const where = toKeysetWhereSql(
keyset.where(cursor, direction),
{
eventTime: "event_time",
id: "event_id",
},
{
placeholder: (index) => `{p${index}:String}`,
},
);
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), {
eventTime: "event_time",
id: "event_id",
});
const rows = await clickhouse.query({
query: `
SELECT * FROM events
${where.sql ? `WHERE ${where.sql}` : ""}
ORDER BY ${orderBy}
LIMIT {limit:UInt32}
`,
query_params: { ...Object.fromEntries(where.params.map((v, i) => [`p${i + 1}`, v])), limit },
});

Use a sort that matches the table’s primary/order key when possible.

Warehouse pagination is usually for exports, not interactive feeds. Use a stable keyset over materialized results or an ordered table, and bind cursor values through query parameters.

const where = toKeysetWhereSql(keyset.where(cursor, direction), columns, {
placeholder: (index) => `@p${index}`,
});
const orderBy = toKeysetOrderBySql(keyset.orderBy(direction), columns);
const [rows] = await bigquery.query({
query: `
SELECT * FROM dataset.events
${where.sql ? `WHERE ${where.sql}` : ""}
ORDER BY ${orderBy}
LIMIT @limit
`,
params: { ...Object.fromEntries(where.params.map((v, i) => [`p${i + 1}`, v])), limit },
});

Avoid paginating relevance-ranked or non-deterministically ordered warehouse queries; materialize the result first and paginate by stable columns.

The fetcher is just a function — it can call fetch. Useful for normalizing a third-party API’s pagination into your own:

const paginator = createPaginator({
fetchCursor: async ({ limit, cursor }) => {
const url = new URL("https://api.example.com/items");
url.searchParams.set("limit", String(limit));
if (cursor) url.searchParams.set("starting_after", cursor.id);
const { data } = await (await fetch(url)).json();
return { items: data };
},
cursor: { fromItem: (item) => ({ id: item.id }) },
});

Common third-party param names (map in your fetcher, not in parsePaginationParams):

Provider style forward param backward param
Stripe-like starting_after ending_before
This library REST cursor / after before
Relay after + first before + last