The moment you expose ?after=482910 on a public list endpoint, you have published a fact about your database: the sort key is a monotonic integer, and consumers will build against it. Change the ordering later and every saved cursor breaks silently.
Offset pagination (LIMIT 20 OFFSET 4000) is the first thing most teams reach for and the first thing that falls over at scale: Postgres still walks and discards every skipped row, so page 200 is measurably slower than page 2, and rows shift under the reader whenever a new record lands. Keyset pagination fixes the performance problem by seeking on the sort key instead of counting past it. But raw keyset values leak your schema and couple the client to your ordering. The fix is to keep keyset pagination underneath and wrap the key in an opaque, signed cursor the consumer treats as a blob. This is how to build that on Express 5, PostgreSQL 17 and Node 22.
Stable ordering is the whole game
Keyset pagination only works if the ordering is a total order — every row has a unique, deterministic position. The mistake is paginating on a column that is not unique. Order by created_at alone and two rows sharing a timestamp have no defined relative order; the database is free to return them in either sequence, so a row can appear on two consecutive pages or on none. The remedy is to tie-break on something guaranteed unique, which is almost always the primary key.
So the contract for a newest-first feed is ORDER BY created_at DESC, id DESC, and the cursor has to carry both values. PostgreSQL lets you express the seek as a single row-value comparison, which reads cleanly and, crucially, matches the composite index the query needs:
-- One index backs the whole ordering; the planner can walk it in reverse.
CREATE INDEX articles_feed_idx ON articles (created_at DESC, id DESC);
-- "Give me the page after (t, k)" becomes a single tuple comparison.
SELECT id, title, created_at
FROM articles
WHERE (created_at, id) < ($1, $2) -- DESC: next rows are "less than" the cursor
ORDER BY created_at DESC, id DESC
LIMIT $3;
Two things to hold onto. Row-value comparison compares lexicographically, so it only lines up with the ORDER BY when every column sorts in the same direction. Mixed directions — created_at DESC, id ASC — break the tuple trick and force you to expand the predicate by hand. And the sort columns should be NOT NULL; NULLs make row comparison return results you did not intend. Pick a non-null column, or handle NULLS LAST explicitly.
Make the cursor opaque and tamper-resistant
An opaque cursor is one the client cannot read or forge. That matters for two reasons. First, it stops consumers hard-coding against your internal keys, so you keep the freedom to change the ordering later. Second, the cursor is untrusted input that flows straight into a WHERE clause; if a caller can hand-craft one, they can probe your data. Base64url-encode the payload so it is opaque to a casual reader, and sign it with an HMAC so tampering is detectable. Signing is cheap and it means decodeCursor can reject anything you did not issue before it ever touches the database.
// cursor.js — opaque, signed cursors for keyset pagination (Node 22)
import { createHmac, timingSafeEqual } from 'node:crypto';
const SECRET = process.env.CURSOR_SECRET; // 32+ random bytes from your secrets store
if (!SECRET) throw new Error('CURSOR_SECRET is not set');
// Sign a payload and return a base64url token: <body>.<sig>
export function encodeCursor(payload) {
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const sig = createHmac('sha256', SECRET).update(body).digest('base64url');
return `${body}.${sig}`;
}
// Verify the signature in constant time, then decode. Throws on tampering.
export function decodeCursor(token) {
const [body, sig] = String(token).split('.');
if (!body || !sig) throw Object.assign(new Error('malformed cursor'), { status: 400 });
const expected = createHmac('sha256', SECRET).update(body).digest();
const given = Buffer.from(sig, 'base64url');
if (expected.length !== given.length || !timingSafeEqual(expected, given)) {
throw Object.assign(new Error('invalid cursor signature'), { status: 400 });
}
return JSON.parse(Buffer.from(body, 'base64url').toString());
}
Use timingSafeEqual, not ===, for the signature check — a byte-by-byte early return leaks timing that helps forge signatures. Note the payload also carries an ordering tag (below). Bump that tag whenever you change the sort contract, and old cursors fail cleanly with a 400 rather than returning quietly wrong pages.
The endpoint: page-info, backward paging, hasNextPage
A public list endpoint should return the data plus a pageInfo object — the Relay convention — with endCursor and hasNextPage so the client never constructs cursors itself. The trick for hasNextPage is to fetch one row more than you return: if the extra row exists, there is a next page. Backward paging (a before cursor) flips both the comparison operator and the ORDER BY, then re-reverses the slice so the client always sees newest-first.
// articles.js — a keyset-paginated public list endpoint (Express 5)
import express from 'express';
import { pool } from './db.js';
import { encodeCursor, decodeCursor } from './cursor.js';
const router = express.Router();
const MAX_LIMIT = 100;
const ORDER = 'created_at_desc_v1'; // bump when the sort contract changes
// Express 5 forwards rejected promises to the error handler, so no try/catch here.
router.get('/articles', async (req, res) => {
const limit = Math.min(Number(req.query.limit) || 20, MAX_LIMIT);
const backward = req.query.before !== undefined;
const raw = backward ? req.query.before : req.query.after;
let keyset = null;
if (raw !== undefined) {
const c = decodeCursor(raw); // throws -> 400 via error handler
if (c.o !== ORDER) throw Object.assign(new Error('stale cursor'), { status: 400 });
keyset = c.k; // [created_at, id]
}
const cmp = backward ? '>' : '<'; // flip the seek for backward paging
const dir = backward ? 'ASC' : 'DESC';
const params = [limit + 1]; // fetch one extra to compute the has-more flag
let where = '';
if (keyset) {
where = `WHERE (created_at, id) ${cmp} ($2, $3)`;
params.push(keyset[0], keyset[1]);
}
const { rows } = await pool.query(
`SELECT id, title, created_at FROM articles
${where}
ORDER BY created_at ${dir}, id ${dir}
LIMIT $1`,
params
);
const hasMore = rows.length > limit;
const page = rows.slice(0, limit);
if (backward) page.reverse(); // restore newest-first for the client
const toCursor = (r) => encodeCursor({ o: ORDER, k: [r.created_at, r.id] });
res.json({
data: page,
pageInfo: {
startCursor: page.length ? toCursor(page[0]) : null,
endCursor: page.length ? toCursor(page[page.length - 1]) : null,
hasNextPage: backward ? Boolean(keyset) : hasMore,
hasPreviousPage: backward ? hasMore : Boolean(keyset),
},
});
});
export default router;
The direction-dependent flags are where people trip. Paging forward, an extra row means there is a next page, and you know there is a previous page only because you arrived on a cursor. Paging backward, the extra row means there is a previous page, and the next page exists because you came from a before cursor. Get that mapping wrong and your “Load more” button lies at the boundaries.
Because decodeCursor throws on anything malformed or forged, one terse error handler turns every bad cursor into a clean 400 instead of a 500 or a silently empty page:
app.use((err, req, res, next) => {
if (err.status === 400) return res.status(400).json({ error: 'invalid pagination cursor' });
next(err); // let genuine 500s fall through to the real handler
});
Relying on Express 5 to forward the rejection is deliberate: in Express 4 an async handler that threw would hang the request, which is exactly the class of bug covered in unhandled promise rejections crashing your Express API. On 5, the throw lands in the handler above without a wrapper.
What this buys you, and what to document
The payoff is concrete. Query cost is flat — page 5,000 costs the same as page 1 because the index seek jumps straight to the cursor. The ordering is stable under concurrent inserts, so readers never see a row twice or miss one. And because the cursor is opaque and signed, you can change the underlying sort key without breaking any client that respects the rule of “pass the cursor back verbatim, never construct it.”
Two things belong in your API contract, not just the code. State plainly that cursors are opaque and non-durable — a cursor may stop working after a deploy that changes ordering — so nobody stores them for weeks and files a bug when they expire. And describe the pageInfo shape in the spec itself; if you are working spec-first with OpenAPI 3.1, the cursor is an opaque string and pageInfo is a named schema. The same discipline applies as with choosing a versioning scheme for a public API: the decisions you make visible in the contract are the ones you can change later without breaking your consumers.
Ship the opaque cursor from day one. Retrofitting opacity onto an endpoint whose consumers already parse your raw IDs is a breaking change nobody thanks you for.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.