Pagination
A list with thousands of rows cannot go to the browser in one answer. A page is one slice of the list. There are two kinds of page, and hamur server has a helper for each step: read and check the query, write the SQL, shape the answer, and describe it in OpenAPI.
| Cursor page | Offset page | |
|---|---|---|
| The reader sees | a "Next page" link; going back is the browser's Back button | page numbers and a total |
| Good for | feeds, long lists, data that changes while people read | admin tables where people jump to page 7 |
| Queries per page | one | two: the rows and a count |
| A row is added while the reader pages | no row is repeated or skipped | a row can appear twice or be missed |
| The answer | items and nextCursor | items, page, perPage, total and pages |
If you are not sure, use a cursor page.
The samples use the todos table of Database and a small hand-written schema for one todo. In your app write that schema with valibot, zod or arktype, or any other library with Standard Schema and JSON Schema support.
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "hamur/server"
import type { Row } from "@hamur/db/server"
type Todo = Row<"todos">
const row = () => ({
type: "object",
properties: {
id: { type: "integer" },
title: { type: "string" },
done: { type: "integer" },
created_at: { type: "string" },
},
required: ["id", "title", "done", "created_at"],
})
export const todo: StandardSchemaV1<unknown, Todo> & StandardJSONSchemaV1<unknown, Todo> = {
"~standard": {
version: 1,
vendor: "docs",
validate: (value) => ({ value: value as Todo }),
jsonSchema: { input: row, output: row },
},
}
Cursor pages
A route that returns a cursor page has three parts:
import { cursorInput, cursorPage, defineHandler } from "hamur/server"
import { cursorQuery, useDatabase, type Row } from "@hamur/db/server"
import { todo } from "./pagination-todo.ts"
export const listTodos = defineHandler({
route: "/api/todos",
method: "GET",
input: cursorInput(),
output: cursorPage(todo),
async handler(input) {
const page = cursorQuery<Row<"todos">>(input, {
orderBy: [
["created_at", "desc"],
["id", "asc"],
],
})
const rows = await useDatabase().sql<Row<"todos">>`
select * from todos
where ${page.where}
order by ${page.orderBy}
limit ${page.limit}`
return page.page(rows)
},
})
cursorInput()is theinput. It readscursorandlimitfrom the query.limitis 20 when it is missing and at most 100.cursorQuery(input, { orderBy })gives the pieces of the SQL:where,orderByandlimit. Put them in the query as they are.whereandorderByare SQL fragments that hamur server made, so nothing from the request becomes SQL text.limitis one more than the one asked for: the extra row tellspagethat another page exists, andpagedrops it.page(rows)turns the rows into{ items, nextCursor }.
A client asks for the first page, then sends back the nextCursor it got:
curl "http://localhost:3000/api/todos?limit=2"
# {"items":[{"id":7,"title":"Buy milk","done":0,"created_at":"2026-12-03 09:12:44"},
# {"id":6,"title":"Call Ada","done":1,"created_at":"2026-12-03 08:50:02"}],
# "nextCursor":"WyIyMDI2LTEyLTAzIDA4OjUwOjAyIiw2XQ"}
curl "http://localhost:3000/api/todos?limit=2&cursor=WyIyMDI2LTEyLTAzIDA4OjUwOjAyIiw2XQ"
# {"items":[{"id":3,"title":"Pay rent","done":0,"created_at":"2026-12-02 18:30:00"}],"nextCursor":null}
nextCursor is null on the last page. A cursor is a string that this API made. It holds the sort values of the last row of the page, so the next request means "the rows after these values". The database does not read and skip the earlier rows. Do not build or change a cursor in the client.
What cursorQuery asks of you
- End
orderBywith a unique column, usually the id. Two rows with the same sort values cannot be told apart by a cursor, and the second one is skipped. Inhamur deva page that holds two such rows warnscursorQuery: two rows share the key [3, 3]; end orderBy with a unique column. - Select every
orderBycolumn. The cursor is read from the rows you pass topage. A row without one throwscursorQuery: the row has no "created_at"; select every orderBy column. A column can be writtent.created_at, and the cursor readscreated_atfrom the row. - Send the same filter with every page. A cursor remembers the sort values and nothing else. Put your own conditions next to
page.where, and keep them the same from one request to the next (see the sample below). - Do not sort by a
Date. A JavaScriptDatekeeps milliseconds, andtimestamptzandDATETIME(6)keep microseconds, so a cursor made from aDatecould skip rows.pagerefuses it with aTypeErrorthat says"created_at" is a Date, which keeps milliseconds only. Select the timestamp as text, as the sample does with SQLite'stextcolumn, orcreated_at::texton Postgres. - Order by
NULLknowingly. ANULLsorts where the database puts it: first when ascending on SQLite and MySQL, last on Postgres. The condition follows the same order. - Big integers. A
bigintkey goes into the cursor and comes back as abigint. The Postgres and MySQL connectors return an integer above 2^53 as text, so convert such a key withBigInt(row.id)beforepage.
This route lists the open todos, newest id first, and shows the filter:
import { cursorInput, cursorPage, defineHandler } from "hamur/server"
import { cursorQuery, useDatabase, type Row } from "@hamur/db/server"
import { todo } from "./pagination-todo.ts"
export const openTodos = defineHandler({
route: "/api/todos/open",
method: "GET",
input: cursorInput({ limit: { default: 10, max: 50 } }),
output: cursorPage(todo),
async handler(input) {
const page = cursorQuery<Row<"todos">>(input, { orderBy: [["id", "desc"]] })
const rows = await useDatabase().sql<Row<"todos">>`
select * from todos
where done = ${0} and ${page.where}
order by ${page.orderBy}
limit ${page.limit}`
return page.page(rows)
},
})
A column is name or table.name: letters, digits and _. Anything else throws TypeError: cursorQuery orderBy column "a b" is not an identifier. An empty orderBy throws cursorQuery orderBy needs at least one column, and a direction other than "asc" or "desc" throws cursorQuery orderBy direction of "id" must be "asc" or "desc".
Set the limits
cursorInput takes the default and the largest limit:
cursorInput({ limit: { default: 10, max: 50 } })
A max below 20 lowers the default to max.
Offset pages
An offset page counts pages from 1 and says how many rows there are. Use it where people pick a page number:
import { defineHandler, offsetInput, offsetPage } from "hamur/server"
import { offsetQuery, useDatabase, type Row } from "@hamur/db/server"
import { todo } from "./pagination-todo.ts"
export const pagedTodos = defineHandler({
route: "/api/todos/paged",
method: "GET",
input: offsetInput(),
output: offsetPage(todo),
async handler(input) {
const db = useDatabase()
const page = offsetQuery<Row<"todos">>(input)
const [rows, count] = await db.batch([
db.sql<Row<"todos">>`select * from todos order by id limit ${page.limit} offset ${page.offset}`,
db.first<{ n: number }>`select count(*) as n from todos`,
])
return page.page(rows, count?.n ?? 0)
},
})
offsetInput() reads page (from 1, default 1) and perPage (default 20, at most 100; offsetInput({ perPage: { default, max } }) changes both). offsetQuery(input) gives the limit and the offset for the SQL, and page(rows, total) makes { items, page, perPage, total, pages }, with pages rounded up. A page past the end is an empty items, not an error.
total must be a whole number. Postgres returns count(*) as a string, so write count(*)::int there, or the output check refuses the answer (total must be an integer from 0) and the call is a masked 500.
The database still reads the rows it skips, and the rows move when others are added or removed. For a long list that changes, use a cursor page.
Errors
A bad query is a 400 before your handler runs. limit, perPage and page take a number or a decimal integer string, since a query string is text.
| The request | The issue |
|---|---|
limit that is not a whole number from 1 to the maximum | limit must be an integer from 1 to 100 |
perPage the same | perPage must be an integer from 1 to 100 |
page below 1 or not a whole number | page must be an integer from 1 |
cursor over 1024 characters, or not base64url | cursor must be a cursor this API returned |
cursor this API did not make: the wrong number of values, or a value of the wrong kind | the same issue, from cursorQuery |
The answer is the usual 400 of a validated route, here with in: "query" and path: ["limit"]. The number in the first two messages is the max you set.
What OpenAPI shows
With server.openapi on, a route with these schemas documents itself. cursorInput() becomes two optional query parameters with their limits and default. cursorPage(todo) becomes the 200 answer, with the item schema of your own schema in items. The offset pair is the same, with page and perPage as parameters and the five fields in the answer. This is the operation for the cursor route above:
{
"tags": ["todos"],
"operationId": "getApiTodos",
"parameters": [
{
"name": "cursor",
"in": "query",
"required": false,
"schema": {
"type": "string",
"maxLength": 1024
}
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"default": 20
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": ["items", "nextCursor"],
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "string"
},
"done": {
"type": "integer"
},
"created_at": {
"type": "string"
}
},
"required": ["id", "title", "done", "created_at"]
}
},
"nextCursor": {
"type": ["string", "null"]
}
}
}
}
}
},
"400": {
"description": "Validation failed",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HamurValidationError"
}
}
}
}
}
}
The page schemas also run on every answer, because output does. Each item goes through your item schema, so a row it refuses fails the call with a masked 500. If your schema library cannot give a JSON Schema, items is described as any value.
Show a page in a component
Make each page a URL. The page's load reads the cursor from the query and asks the route for that page:
import type { Load } from "hamur/app"
interface TodoPage {
items: Array<{ id: number; title: string }>
nextCursor: string | null
}
export const load = (async ({ query, fetch }) => {
const cursor = typeof query.cursor === "string" ? query.cursor : undefined
return fetch<TodoPage>("/api/todos", { query: { cursor, limit: 10 } })
}) satisfies Load
A load runs again when the query changes (Data), so /todos?cursor=… shows the next page. The component lists items and links to the next page while nextCursor is set. Cursor pages go forward only. The browser's Back button is the way to go back, and every page has its own address that can be shared. Every library reads the same data; only its syntax differs.
React:
import { Link, useData } from "@hamur/adapter-react"
interface TodoPage {
items: Array<{ id: number; title: string }>
nextCursor: string | null
}
export default function Todos() {
const { items, nextCursor } = useData<TodoPage>()
return (
<main>
<ul>
{items.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
{nextCursor ? <Link to={`/todos?cursor=${nextCursor}`}>Next page</Link> : <p>That is every todo.</p>}
</main>
)
}
Preact:
import { Link, useData } from "@hamur/adapter-preact"
interface TodoPage {
items: Array<{ id: number; title: string }>
nextCursor: string | null
}
export default function Todos() {
const { items, nextCursor } = useData<TodoPage>()
return (
<main>
<ul>
{items.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
{nextCursor ? <Link to={`/todos?cursor=${nextCursor}`}>Next page</Link> : <p>That is every todo.</p>}
</main>
)
}
Solid:
import { For, Show } from "solid-js"
import { Link, useData } from "@hamur/adapter-solid"
interface TodoPage {
items: Array<{ id: number; title: string }>
nextCursor: string | null
}
export default function Todos() {
const data = useData<TodoPage>()
return (
<main>
<ul>
<For each={data().items}>{(todo) => <li>{todo.title}</li>}</For>
</ul>
<Show when={data().nextCursor} fallback={<p>That is every todo.</p>}>
<Link to={`/todos?cursor=${data().nextCursor}`}>Next page</Link>
</Show>
</main>
)
}
Vue:
<script setup lang="ts">
import { Link, useData } from "@hamur/adapter-vue"
interface TodoPage {
items: Array<{ id: number; title: string }>
nextCursor: string | null
}
const data = useData<TodoPage>()
</script>
<template>
<main>
<ul>
<li v-for="todo in data.items" :key="todo.id">{{ todo.title }}</li>
</ul>
<Link v-if="data.nextCursor" :to="`/todos?cursor=${data.nextCursor}`">Next page</Link>
<p v-else>That is every todo.</p>
</main>
</template>
Svelte:
<script lang="ts">
import { Link, useData } from "@hamur/adapter-svelte"
interface TodoPage {
items: Array<{ id: number; title: string }>
nextCursor: string | null
}
const data = useData<TodoPage>()
</script>
<main>
<ul>
{#each data.value.items as todo (todo.id)}
<li>{todo.title}</li>
{/each}
</ul>
{#if data.value.nextCursor}
<Link to={`/todos?cursor=${data.value.nextCursor}`}>Next page</Link>
{:else}
<p>That is every todo.</p>
{/if}
</main>
Angular:
import { Component } from "@angular/core"
import { Link, injectData } from "@hamur/adapter-angular"
interface TodoPage {
items: Array<{ id: number; title: string }>
nextCursor: string | null
}
@Component({
imports: [Link],
template: `<main>
<ul>
@for (todo of data().items; track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
@if (data().nextCursor; as cursor) {
<a [hamurLink]="'/todos?cursor=' + cursor">Next page</a>
} @else {
<p>That is every todo.</p>
}
</main>`,
})
export default class Todos {
readonly data = injectData<TodoPage>()
}
html returns a string, so it escapes each title itself:
import { Link, useData } from "@hamur/adapter-html"
interface TodoPage {
items: Array<{ id: number; title: string }>
nextCursor: string | null
}
const escape = (value: unknown) => String(value).replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`)
export default function Todos(): string {
const { items, nextCursor } = useData<TodoPage>()
const rows = items.map((todo) => `<li>${escape(todo.title)}</li>`).join("")
const more = nextCursor
? Link({ to: `/todos?cursor=${nextCursor}`, children: "Next page" })
: "<p>That is every todo.</p>"
return `<main><ul>${rows}</ul>${more}</main>`
}
For a "load more" button that adds to the list, call the same route with $fetch from the component and keep the items in state.
The signatures are in the server API reference and the @hamur/db API reference.