monorepo-template / backend
Cursor rule18 starsChanged 2 months agoApache-2.0View on GitHub
Hono gateway Worker rules - middleware order, shared @repo/hono-middleware exports, CORS/CSRF, errors, observability, validation, typing.
- Reads credentials
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,527 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository60 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .agents/skills/vercel-react-best-practices/AGENTS.mdAGENTS.md
- hooks/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- hooks/CLAUDE.mdCLAUDE.md
- .cursor/rules/backend/ports.mdcCursor rule
- .cursor/rules/backend/service-bindings.mdcCursor rule
- .cursor/rules/backend/workers-cache.mdcCursor rule
- .cursor/rules/backend/workers-config.mdcCursor rule
- .cursor/rules/contracts/contracts.mdcCursor rule
- .cursor/rules/core/agent-instructions.mdcCursor rule
- .cursor/rules/core/boundaries.mdcCursor rule
- .cursor/rules/core/guardrails.mdcCursor rule
- .cursor/rules/core/turborepo.mdcCursor rule
- .cursor/rules/core/worktrees.mdcCursor rule
- .cursor/rules/frontend/react.mdcCursor rule
- .cursor/rules/frontend/tailwind.mdcCursor rule
- .cursor/rules/frontend/tanstack-query.mdcCursor rule
- .cursor/rules/frontend/tanstack-router.mdcCursor rule
- .cursor/rules/frontend/vite-config.mdcCursor rule
- .cursor/rules/ops/cd.mdcCursor rule
- .cursor/rules/ops/changesets.mdcCursor rule
- .cursor/rules/ops/ci.mdcCursor rule
- .cursor/rules/ops/previews.mdcCursor rule
- .cursor/rules/ops/quality-report.mdcCursor rule
- .cursor/rules/ops/release.mdcCursor rule
- .cursor/rules/quality/code-style.mdcCursor rule
- .cursor/rules/quality/comments.mdcCursor rule
- .cursor/rules/quality/knip.mdcCursor rule
- .cursor/rules/quality/lint-config.mdcCursor rule
- .cursor/rules/quality/markdown-style.mdcCursor rule
- .cursor/rules/quality/naming.mdcCursor rule
- .cursor/rules/quality/simplicity.mdcCursor rule
- .cursor/rules/quality/testing.mdcCursor rule
- .cursor/rules/quality/typescript-config.mdcCursor rule
- .cursor/rules/tests/front-react.mdcCursor rule
- .cursor/rules/tests/hono-workers.mdcCursor rule
- cfSkill
- changesetSkill
- front-vitestSkill
- git-commitSkill
- honoSkill
- monorepo-agent-setupSkill
- playwright-cliSkill
- pnpmSkill
- react-doctorSkill
- reviewSkill
- review-stackSkill
- run-appSkill
- security-auditSkill
- skills-updateSkill
- tanstack-configSkill
- tanstack-devtoolsSkill
- tanstack-querySkill
- tanstack-routerSkill
- turborepoSkill
- ui-ux-design-best-practicesSkill
- vercel-react-best-practicesSkill
- workers-best-practicesSkill
- skills-updateSkill
The file
We split this hono-gateway.mdc into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 29
timeout(ms, () => new HTTPException(504, …)): - always pass the exception factory: Hono's default is one shared HTTPException, and Sentry … - Very specific: line 43
Never log, return, or hardcode a secret (bindings.secret()) value.
- Very specific: line 54
Never log validation failures: the body carries every issue and the invocation log records the 400.
- Very specific: line 72
No global mutable state for per-request data: use c.get / c.set.
≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: "Hono gateway Worker rules - middleware order, shared @repo/hono-middleware exports, CORS/CSRF, errors, observability, validation, typing."
alwaysApply: false
globs: apps/worker-*/src/**/*.ts,apps/webhook-*/src/**/*.ts,packages/hono-middleware/src/**/*.ts
---
# Hono Gateway (Workers) Rules
`worker-api` and sibling `worker-*` / `webhook-*` apps run Hono on Cloudflare Workers. Depth: skills `hono`, `workers-best-practices`.
## Middleware order (`src/index.ts`)
Register in this order; "before" logic runs top-down, response mutation bottom-up. Steps 1-4 and the error handlers are individual exports of `@repo/hono-middleware` ([AGENTS.md](../../../packages/hono-middleware/AGENTS.md)); each app registers them itself so the order stays visible in its `index.ts`.
**Root app (every route):**
1. **`requestIdMiddleware`** - first, so every later middleware, `errorHandler`, and response can reference it. Mints `crypto.randomUUID()` into `c.get("requestId")`, tags `request_id` on the Sentry scope (`withSentry` opens the per-request isolation scope around `app.fetch`, before any middleware), and sets `X-Request-Id` after `next()`, so `onError` / `notFound` responses carry it. It never reads an inbound `X-Request-Id`: a caller-supplied id could carry a user identifier, and a shared id would no longer name one invocation.
2. **`sentryMiddleware(app, { release })`** - wraps `sentry()` from `@sentry/hono/cloudflare`, whose direct import oxlint blocks in apps. It reports `c.error` 5xx even when `onError` handles the error: never add `captureException` there. The locked-down `dataCollection` (no user info, cookies, headers, bodies, query params, frame variables) and the console-breadcrumb drop live in the package; never loosen them per app.
3. **`jsonMethodNotAllowed(app)`** - `405` plus `Allow` when the path exists but the method does not.
4. **`apiSecureHeaders`** (`hono/secure-headers`) - defaults (HSTS, `nosniff`, `no-referrer`, COOP/CORP, `X-Powered-By` removed) plus CSP `default-src 'none'; frame-ancestors 'none'` (harmless for JSON, hardening if a response is ever rendered - keep it) and a `permissionsPolicy` denying camera/mic/geolocation/payment. CORP `same-origin` is fine for CORS-mode `fetch` from `front-app`; never disable it to fix SPA reads.
5. **`cors()`** on `/api/*` (gateway-local `src/middlewares/cors.ts`) - preflight `OPTIONS` clears before auth/routes. Read the allowlist from `c.env.CORS_ORIGINS` per request (env is unavailable at module scope on Workers). `exposeHeaders` is `CORS_EXPOSED_HEADERS` from `@repo/enums-common`, so browsers can read `X-Request-Id` and `X-Worker-Version-Id`. An empty allowlist is permissive (`*`) in `dev` only; any other `ENVIRONMENT` (staging, production, typos) must set origins or `/api/*` returns **503**. A single-label prefix wildcard (`https://*-front-app-production.<subdomain>.workers.dev`, three or more labels after the wildcard label) is honored only when `ENVIRONMENT` is `AppEnvironment.PREVIEW`; anywhere else it returns 503. CORS and the CSRF gate share the matcher in `src/middlewares/cors-origins.ts`.
6. **Origin / CSRF gate** on `/api/*` (gateway-local) - unsafe methods only, any `Content-Type` including `application/json`; never blocks preflight. Allows when Origin is on the allowlist or `Sec-Fetch-Site` is `same-origin` / `same-site`. Hono's `csrf()` covers only form content-types, so never rely on it alone here. Browser JSON mutations rely on this gate plus CORS: never reintroduce a permissive CSRF in strict environments.
End with `app.notFound(notFoundHandler)` and `app.onError(errorHandler)` on the root app: a sub-app without its own `onError` falls through to the parent's.
**API sub-app (`/api/v1`):**
7. **`timing()`** - `Server-Timing`, dev only (`c.env.ENVIRONMENT === AppEnvironment.DEV`): Workers timers advance only on I/O, and internal timings must not leak to clients, staging and Previews included.
8. **`timeout(ms, () => new HTTPException(504, …))`** - always pass the exception factory: Hono's default is one shared `HTTPException`, and Sentry skips an error object it already captured, so only the first timeout per isolate would be reported. Read the timeout caveat below before adding routes.
9. **`bodyLimit()`** - e.g. 3 MB cap; `413` on overflow.
10. **`prettyJSON()`** - dev only.
## Errors
A middleware or handler rejects by throwing `new HTTPException(status, { message })`; `errorHandler` renders `{ error, requestId }` (plus `issues` for validation failures). Never build that envelope by hand; the one exception is `jsonMethodNotAllowed`, whose `Allow` header would not survive the throw. Clients receive `message`, so keep it generic (no sensitive content, no upstream provider text); unexpected errors stay `"Internal server error"` + `requestId`.
## Observability
- **Native first.** With `observability.enabled`, Workers emits an invocation log per request (method, path, status, CPU/wall time, outcome). Never re-implement a per-request access log in middleware: it duplicates that data and doubles ingest.
- `errorHandler` logs every 5xx with its `requestId` - unhandled errors and thrown 5xx `HTTPException`s alike, never a 4xx - and `errorHandler` / `notFoundHandler` echo the id in the body next to the `X-Request-Id` header; `front-app` shows it on its error screen.
- **Log objects, never `JSON.stringify` strings**: Workers Logs indexes the keys of an object passed to `console.*`, so `requestId` stays filterable. Reserve `console.error` for real failures; success is the invocation log's job.
- **Debugging from a request id**: (1) Workers Logs (`cloudflare-observability` MCP or dashboard), filter `requestId = <id>` for the error line and stack beside the invocation log - 5xx only, a 4xx leaves just its invocation log; (2) Sentry `request_id:<id>` for the backend event, then its trace for the SPA spans and errors, linked by `trace_id` through `sentry-trace` / `baggage` even when unsampled - an `Error id` on the SPA error screen is a Sentry event id, search it directly; (3) across Workers, see [service-bindings.mdc](service-bindings.mdc).
- Never log, return, or hardcode a secret (`bindings.secret()`) value.
- **Sentry for exceptions, Workers Observability for traffic.** `SENTRY_DSN` is a `bindings.secret()`; `test` and Preview bind `bindings.text("")`, and locally it is set only from the shell, so empty or unset keeps the SDK off. Release is `worker-api@<semver>`; `environment` is `ENVIRONMENT`, and `front-app` sends the same `AppEnvironment` value via `VITE_APP_ENVIRONMENT`. Trace sampling in `packages/hono-middleware/src/sentry.ts` mirrors each deployment's `headSamplingRate` (1 in `dev` / `preview`, 0.01 elsewhere) in every consuming app: change them together, and `front-app`'s `sentry.ts` with them, because the gateway continues the SPA's sampling decision. `beforeBreadcrumb` drops console breadcrumbs: console text must not reach a third party. Source maps match by release, not debug ID: `sentry:sourcemaps` uploads the maps in `.cloudflare/output/v0/workers/default/bundle/`, the Build Output the `--prebuilt` upload shipped.
## Timeout caveat (read before adding routes)
`hono/timeout` is `Promise.race([next(), timer])`: on fire it returns `504` but **does not cancel the handler** - downstream work, `fetch` included, keeps running and on Workers is only guaranteed to finish under `c.executionCtx.waitUntil()`. It cannot wrap streaming / SSE responses: mount such a route outside the timeout (separate sub-app) or carve it out with `except` from `hono/combine`. For real cancellation pass `AbortSignal.timeout(ms)` to subrequests. Keep `front-app`'s fetch timeout (`DEFAULT_TIMEOUT_MS` in `src/utils/fetch-api.ts`) above the gateway's, or the SPA aborts before the `504` and its `X-Request-Id` arrive; the health probe's shorter timeout is fine, since it only drives a status dot.
## Validation
- Validate every input at the route boundary with `validator(target, Schema)` from `@repo/hono-middleware` (`"json" | "param" | "query" | "header"`): `zValidator` with a hook that throws `HTTPException(400, { cause })`, so failures reach `errorHandler` as `{ error, requestId, issues }`. oxlint blocks importing `@hono/zod-validator` in apps: without the hook Hono answers `{ success, error }`, serializing Zod internals and dropping the `requestId`.
- **Never `z.compile()`**: it builds its fast path with `new Function`, which workerd forbids during request handling, so the schema silently falls back to the interpreted parser.
- Never log validation failures: the body carries every issue and the invocation log records the 400; a `console` line duplicates both and lets a public caller inflate log ingest.
## Handlers and routes
- Status codes: `400` validation, `401` unauthenticated, `403` forbidden, `404` not found, `413` body too large, `500` internal, `504` timeout.
- RESTful paths: plural nouns (`/items`), verbs via HTTP method.
## Typing & structure
- Type the app with `export type AppEnv = HonoEnv<Env>` in `src/app-env.ts` (`HonoEnv` from `@repo/hono-middleware`). Its `Bindings extends BaseBindings` constraint is the only compile-time check that `cloudflare.config.ts` declares what the shared middleware reads (`ENVIRONMENT` as an `AppEnvironment` value, `SENTRY_DSN`), because `app.use()` merges a middleware's Env instead of checking it.
- A guard that depends on required config fails closed when the value is missing (throw or 503), never with a permissive fallback.
- Small custom middleware stays inline in `index.ts`; extract to `src/middlewares/<name>.ts` (`createMiddleware<AppEnv>`, `hono/factory`) when it grows; move it to `@repo/hono-middleware` when a second Hono app needs it.
- **Name every middleware** with a named function expression (`createMiddleware<AppEnv>(async function originGate(c, next) { … })`, `api.use(async function devPrettyJson(c, next) { … })`), never an anonymous arrow: `hono routes --verbose` prints `function.name`, and an anonymous one shows as `[middleware]`.
- Broad scope with carve-outs: `except` / `some` / `every` from `hono/combine`, not one `app.use()` per sub-route.
- `hono/context-storage` (`getContext()`) works (Node.js compatibility is on via `compatibilityDate`), but a thin gateway passes `c` explicitly; do not reach for it by default.
## Workers runtime
- No global mutable state for per-request data: use `c.get` / `c.set`.
- Background work after a response goes through `c.executionCtx.waitUntil()` (floating promises are a lint error).
- No `setInterval` or long-lived timers: CPU time limits apply.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

