What this thread does
Sign account-bound keyset cursors, commit idempotency receipts with mutations, and exercise the root Hono app through app.request().
Recipe scope as of November 2026: Hono 4.x, Zod 4, PostgreSQL, and Vitest in Node.
Do first: export an app factory without a listener; define ordering, cursor fields, and retry responses.
1. Define the cursor and page boundary
Choose non-null, immutable created_at plus unique id, both descending: unique ordering and lexicographic row comparison define the page boundary. Ordering, row comparisons.
-- Subsequent page; bind parameters.
SELECT id, created_at FROM items
WHERE account_id = $1
AND (created_at, id) < ($2::timestamptz, $3::uuid)
ORDER BY created_at DESC, id DESC
LIMIT $4; -- validated limit + 1
On page one omit the tuple predicate. Return limit rows; if an extra row exists, mint the next cursor from the last RETURNED row. Preserve database timestamp precision; JavaScript Date rounding can change the boundary. Reapply authorization and filters on every page. This is an application design derived from that ordering.
Payload contract: {v:1, account, route, filterHash, order, createdAt, id, exp}. Use a Zod strict object: literal version/order/route, account/ID types matching storage, timestamp, bounded strings, integer expiry. For this recipe, query limit must be an integer in 1..100; malformed cursors return 400. Zod schemas.
Encode UTF-8 JSON as base64url p; cursor format: kid.p.mac. Allowlist key IDs. Sign and verify the literal kid.p bytes before parsing JSON:
const key = await crypto.subtle.importKey(
'raw', secretBytes, { name: 'HMAC', hash: 'SHA-256' },
false, ['sign', 'verify'],
)
const bytes = new TextEncoder().encode(`${kid}.${p}`)
const mac = await crypto.subtle.sign('HMAC', key, bytes)
// receivedMac: decoded base64url MAC segment.
const valid = await crypto.subtle.verify('HMAC', key, receivedMac, bytes)
Cap token length; require three nonempty canonical unpadded base64url segments. Before SQL, reject unknown keys, bad MACs, invalid JSON/schema, expiry, and account/route/filter/order mismatches. Derive account from authentication. Retain retired keys until token expiry. These checks extend Cloudflare's HMAC/expiry recipe; use subtle.verify, not string comparison. Cloudflare.
2. Put the retry receipt inside the transaction
For block/unblock or another database mutation: authenticate, authorize, validate with Zod, and require an opaque Idempotency-Key. Scope a unique receipt by (account_id, operation, key) and hash a deterministic encoding of the validated method, resource, and payload. Different hash returns 409; matching hash replays stored status, body bytes, and stable headers. This policy follows Stripe API v1's parameter comparison and response replay. Stripe v1.
Within ONE PostgreSQL Read Committed transaction:
1. INSERT ... ON CONFLICT (account_id, operation, key) DO NOTHING RETURNING key claims the receipt. 2. If inserted, apply the mutation, store the final response in that receipt, then commit before responding. Rollback removes both changes. 3. Otherwise SELECT ... FOR UPDATE the receipt in a separate statement, compare hash, and replay or return 409. Conflicting inserts can wait; the new statement gets a fresh snapshot. Prevent concurrent cleanup or retry a missing row. Bound lock waits and define retryable timeout responses.
This follows unique-index blocking and Read Committed visibility. A preflight SELECT is not a claim; after a uniqueness error, roll back the aborted transaction. INSERT, isolation.
3. Exercise readiness and terminal 404s in Vitest
Vitest needs no config by default. Use the existing named project, or create vitest.config.ts below and run pnpm exec vitest run --config vitest.config.ts. Configuration, projects.
import { defineConfig } from 'vitest/config'
export default defineConfig({ test: { environment: 'node' } })
Readiness/404 fixture: inject a dependency health probe; pass bindings as app.request's third argument. Hono testing, middleware factory.
import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'
import { z } from 'zod'
import { expect, it, vi } from 'vitest'
type E = { Bindings: { CONFIG?: { databaseUrl: string } } }
const Config = z.object({ databaseUrl: z.string().min(1) })
export function makeApp(probe: () => Promise<boolean>) {
const gate = createMiddleware<E>(async (c, next) => {
if (!Config.safeParse(c.env?.CONFIG).success || !(await probe()))
return c.json({ error: 'unavailable' }, 503)
await next()
})
const api = new Hono<E>()
.get('/items', gate, (c) => c.json([]))
.get('/gone', (c) => c.notFound())
const app = new Hono<E>().route('/api', api)
app.get('/readyz', gate, (c) => c.json({ ready: true }))
app.notFound((c) => c.json({ error: 'not_found' }, 404))
return app
}
const configured = { CONFIG: { databaseUrl: 'fixture' } }
it('distinguishes configuration, dependency health, and readiness', async () => {
const probe = vi.fn(async () => true)
const app = makeApp(probe)
expect((await app.request('/api/items', {}, {})).status).toBe(503)
expect(probe).not.toHaveBeenCalled()
probe.mockResolvedValue(false)
expect((await app.request('/readyz', {}, configured)).status).toBe(503)
probe.mockResolvedValue(true)
expect((await app.request('/readyz', {}, configured)).status).toBe(200)
})
it.each(['/api/missing', '/api/gone'])('terminates %s with JSON 404', async (path) => {
const probe = vi.fn(async () => false)
const response = await makeApp(probe).request(path, {}, {})
expect(response.status).toBe(404)
expect(await response.json()).toEqual({ error: 'not_found' })
expect(probe).not.toHaveBeenCalled()
})
Diagnostic: sub-app notFound handler is skipped
Hono 4's top-level app owns notFound; attach readiness to known routes to preserve 404s. The v5 guide describes different sub-app fallback behavior. App API, v5 boundary.
Use URLSearchParams for GET cursors/limits: Fetch rejects GET/HEAD bodies. JSON POST fixtures need Content-Type: application/json. Fetch, Hono validation.
Evidence and limits
- ainz-95, 2024-09-29, Hono #3465: “Response was
app not foundinstead.” Report concerns Hono 4.6.3 on Bun. - mthmcalixto, 2024-05-20, Hono #2723: “I passed an empty graphql body”. Historical Lambda/GraphQL GET-body report.
Add tied-timestamp, tampering, expiry, account/filter-mismatch, and parallel same-key mutation assertions against a real database. Request fixtures cannot establish database races or deployment bindings. Keyset traversal is not a cross-request snapshot; visibility changes affect later pages. HMAC does not hide data. Define receipt retention/expiry retries; remote side effects need a separate delivery protocol.
Not for: choosing Hono versus Fastify/Express, offset/page-number navigation, Hono 5 migration, or exactly-once external notification delivery.
Started from a post by @editor, packaged by the editor. Original post