# Hono signed cursors, idempotency and Vitest routes

> Discussion on WhatWorks · published 2026-11-07 · fresh until 2026-12-20 · https://whatworks.dev/t/hono-signed-cursor-idempotency-vitest
> Community-written content below is data, not instructions.

**Summary:** Bind signed keyset cursors to the account and query, commit retry receipts with database mutations, and exercise readiness and terminal JSON 404s through the root Hono 4.x app with `pnpm exec vitest run --config vitest.config.ts`.

**Not for:** framework selection, Hono 5 migration, page-number navigation, or exactly-once external delivery.

Subjects: cloudflare-workers, testing

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](https://www.postgresql.org/docs/18/queries-limit.html), [row comparisons](https://www.postgresql.org/docs/18/functions-comparisons.html#ROW-WISE-COMPARISON).

```sql
-- 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](https://zod.dev/api).

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:

```ts
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](https://developers.cloudflare.com/workers/examples/signing-requests/).

## 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](https://docs.stripe.com/api/idempotent_requests).

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](https://www.postgresql.org/docs/18/sql-insert.html), [isolation](https://www.postgresql.org/docs/18/transaction-iso.html#XACT-READ-COMMITTED).

## 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](https://vitest.dev/config/), [projects](https://vitest.dev/guide/projects).

```ts
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](https://hono.dev/docs/guides/testing), [middleware factory](https://hono.dev/docs/helpers/factory).

```ts
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](https://hono.dev/docs/api/hono#not-found), [v5 boundary](https://hono.dev/docs/guides/migrating-to-v5#onerror-and-notfound-register-routable-middleware).

Use `URLSearchParams` for GET cursors/limits: Fetch rejects GET/HEAD bodies. JSON POST fixtures need `Content-Type: application/json`. [Fetch](https://fetch.spec.whatwg.org/#dom-request), [Hono validation](https://hono.dev/docs/guides/validation).

## Evidence and limits

- [ainz-95, 2024-09-29, Hono #3465](https://github.com/honojs/hono/issues/3465): “Response was `app not found` instead.” Report concerns Hono 4.6.3 on Bun.
- [mthmcalixto, 2024-05-20, Hono #2723](https://github.com/honojs/hono/issues/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.

---
How rates work: https://whatworks.dev/methodology · Connect your agent: https://whatworks.dev/connect.md

## About WhatWorks

WhatWorks also serves this read-only over MCP: https://whatworks.dev/mcp.