Last updated:
.paginate(options) is the terminal that turns any ctx.db.query(table) chain
into a keyset-paginated read. Unlike .collect() (every row) or .take(n)
(the first n), it returns one page plus an opaque cursor you pass back to
fetch the next. Cursors are keyset, not offset, so paging stays stable as rows
are inserted or deleted ahead of the cursor.
import { query, v } from "@/lunora/_generated/server";
const cursor = v.optional(v.union(v.string(), v.null()));
export const list = query
.input({ channelId: v.id("channels"), paginationOpts: v.object({ cursor, endCursor: cursor, numItems: v.number() }) })
.query(async ({ ctx, args: { channelId, paginationOpts } }) => {
return ctx.db
.query("messages")
.withIndex("by_channel", (q) => q.eq("channelId", channelId))
.order("desc")
.paginate(paginationOpts);
});Declare paginationOpts with a real validator: v.any() types it unknown,
which .paginate() rejects, and usePaginatedQuery also sends endCursor,
which input validation strips unless it is declared.
.paginate() composes with .withIndex(), .filter(), and .order(): it pages
within the active index in the chosen direction.
PaginationOptions
The argument to .paginate():
| Field | Type | Meaning |
|---|---|---|
numItems | number | Maximum rows to return for this page. |
cursor | string | null | Cursor from the prior page's continueCursor; null/omitted starts at the first page. |
PaginationResult
What .paginate() resolves to:
| Field | Type | Meaning |
|---|---|---|
page | T[] | The rows for this page. |
isDone | boolean | true when this is the last page. |
continueCursor | string | null | Cursor to pass back as the next cursor; null once isDone. |
Paging through a query
Drive it from the first page (cursor: null) and feed continueCursor back in
until isDone:
let cursor: string | null = null;
do {
const { page, isDone, continueCursor } = await ctx.runQuery(api.messages.list, {
channelId,
paginationOpts: { numItems: 50, cursor },
});
for (const message of page) {
// … handle each row
}
cursor = continueCursor;
if (isDone) break;
} while (cursor !== null);Ordering rows that hold NULL
orderBy puts rows whose column is empty (null or absent) first when ascending and last when
descending. To put them somewhere else, give the entry a sort and a nulls:
await ctx.db.tasks.findMany({
orderBy: [{ dueAt: { sort: "asc", nulls: "last" } }], // dated tasks first, undated at the end
limit: 20,
});Paging works with any placement: the cursor seeks past the NULL group the same way it seeks past any
other value, including when a page boundary falls inside it. Use the same orderBy for every page,
as a cursor is only valid against the ordering that minted it. The placement has no effect on a
column that cannot hold NULL.
Whether a non-default placement is still answered from an index depends on the database, so measure a hot read before relying on it:
- SQLite and D1 walk the index for the first page. Later pages carry an extra
OR col IS NULLarm in the seek, which drops to a scan, the same cost the defaultdescorder already pays. - Postgres is always given the placement explicitly. A plain btree index is
ASC NULLS LAST(read backwards,DESC NULLS FIRST), so those two placements are served from it and the default ones are sorted. - MySQL has no
NULLS FIRST/LAST, so a non-default placement adds anIS NULLsort key that an index on the column alone cannot serve.
Paging a findMany
ctx.db.<table>.findMany takes the same cursors, so a where/orderBy read can serve
usePaginatedQuery without the fluent builder:
export const list = query
.input({ channelId: v.id("channels"), paginationOpts: v.object({ cursor, endCursor: cursor, numItems: v.number() }) })
.query(async ({ ctx, args: { channelId, paginationOpts } }) => {
const { endCursor, numItems } = paginationOpts;
return ctx.db.messages.findMany({
where: { channelId },
orderBy: [{ _creationTime: "desc" }],
cursor: paginationOpts.cursor,
endCursor,
// An open page is `numItems` long. A pinned page may grow past that before the client splits it.
limit: endCursor ? numItems * 4 : numItems,
});
});Without endCursor, findMany returns up to limit rows after cursor, and continueCursor is
null once isDone. With endCursor (a cursor an earlier page returned as continueCursor), the
page is the fixed range (cursor, endCursor] under the call's orderBy:
isDoneistrueandcontinueCursorisendCursorunchanged, so the next page still starts where this one ends. A row inserted inside the range grows this page and leaves the next one alone.splitCursoris the cursor of the range's midpoint row (nullunder two rows). The client splits a page holding more than twice itsnumItemsinto(cursor, splitCursor]and(splitCursor, endCursor].limitstill caps the read. A range it cuts short answerssplitRequired: true, and the client splits it atsplitCursorwhatever its size, so the rows past the cap come back in the second half.- On a
.global()table, a pinned page with nolimitis capped at 4096 rows the same way. - A pinned page binds a second cursor seek, so an
orderBytoo wide for both to fit in one statement is refused withBAD_REQUEST; order by fewer fields.
Load more / infinite lists on the client
On the client a paginated list is the same query re-run with the next
cursor. The framework adapters wrap this for you (usePaginatedQuery in
@lunora/react and @lunora/vue, createPaginatedQuery in @lunora/solid,
paginatedQuery in @lunora/svelte): you hold the
accumulated page arrays, track the latest continueCursor, and call "load
more" to re-run the query with cursor set to it. When isDone is true, hide
the button.
// Framework-neutral sketch of the "load more" loop the adapter hooks implement.
const pages: Message[] = [];
let cursor: string | null = null;
let isDone = false;
async function loadMore() {
if (isDone) return;
const result = await client.query(api.messages.list, {
channelId,
paginationOpts: { numItems: 50, cursor },
});
pages.push(...result.page);
cursor = result.continueCursor;
isDone = result.isDone;
}Because queries are reactive, each loaded page stays live. A mutation that touches a row already on screen re-runs the query and pushes the delta to the client without re-fetching the whole list.
A cursor a client still holds can be refused with INVALID_CURSOR after a
deploy: the engine bumps its cursor format whenever a change would otherwise
read old cursors as the wrong rows, and a query that now orders by more keys
than the cursor carries refuses it too. The adapters restart the feed from
its first page on that code, without reporting it through onError, and ask the
server for a fresh snapshot of that page with client.resnapshot(fn, args):
another feed over the same query may still hold it, with a continueCursor from
the build that minted the refused one. A second refusal before any page past
the first has loaded is reported, because then the server is refusing the
cursors it has just minted. A hand-written loop like the one above should do the
same: reset pages and cursor and load again, rather than retrying the cursor.
Total count ("42 of 1,203")
A page knows how to fetch the next page, not how many rows exist — paginate()
never counts the tail, which is what keeps it O(page) instead of O(table). Ask
for the total with a separate query and subscribe to it like any other:
// lunora/messages.ts
export const total = query.input({ channelId: v.id("channels") }).query(async ({ ctx, args: { channelId } }) => ctx.db.messages.count({ channelId }));const { results, status, loadMore } = usePaginatedQuery(api.messages.list, { channelId }, { initialNumItems: 50 });
const total = useQuery(api.messages.total, { channelId });
return (
<p>
Showing {results.length} of {total ?? "…"}
</p>
);It is a live query, so an insert or delete updates the count the same tick it
updates the list — no invalidation to wire up. Pass the count query the same
filter args as the list query, minus paginationOpts; a count over a different
where is the classic way to print a total that disagrees with the rows on
screen.
count() scans the index, so on a large table prefer counting a filtered subset
(an index-backed where) over the whole table on every keystroke.