anantbhandarkar/make-it-right/mir-backend-bun-hono

Claude Code and agent skill by anantbhandarkar/make-it-right

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Make It Right (Hono module). Hono 4 reliability augmentation for backends on the Web-standard Request/Response model - Bun, Cloudflare Workers, Deno, and Node via @hono/node-server. Footguns the runtime tiers omit: the request body is a stream read once, so c.req.raw throws after a validator ran; use cloneRawRequest; `await next()` never throws, so try/catch cleanup middleware sees nothing and the error lands in c.error instead; validator() parses but does not authorize, and yields an empty object when Content-Type is missing; the hono/bun vs hono/cloudflare-workers adapter split, where Node built-ins, the filesystem, and module-scope state work on Bun and fail on Workers. Plus 2026 advisories: CORS credentials-with-wildcard origin reflection (CVE-2026-54290, HIGH). Chains: mir-backend -> mir-backend-bun (or mir-backend-node when served through @hono/node-server) -> this. TRIGGER only when the web framework is Hono - a Hono route, middleware, validator, RPC client, adapter, or stream handler, on any runtime. SKIP for Elysia and raw Bun.serve handlers, SKIP for Express, Fastify, NestJS, Koa, and Hapi (mir-backend-node-express, -fastify, -nestjs), SKIP for a Cloudflare Worker with no Hono in it, and SKIP for Bun runtime mechanics (bundler, test runner, Bun-native APIs, install supply chain) - mir-backend-bun.

Install

npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-bun-hono

SKILL.md

The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-bun-hono.

/mir-backend-bun-hono · Make It Right (Hono)

Bottom tier of the chain: mir-backend (generic gates) → mir-backend-bun (Bun runtime model) → this (Hono library mechanics). Run the gates first; load the runtime tier for the process, scheduler, and install-time concerns; reach for this at Gate 5 (design mechanics), Gate 6 (implementation), and Gate 7 review. Runtime-level concerns (Bun's event loop and worker model, Bun-native APIs, the test runner and bundler, install scripts and lockfile trust) live in `mir-backend-bun` — not here. If the deploy target is Node through @hono/node-server, load mir-backend-node as the runtime tier instead.

Stack assumed (npm registry + GitHub advisory DB, 13 Aug 2026): hono@4.13.1 is latest, published 2026-08-07. Hono 4 is the only current major; there is no v5. The package has zero runtime dependencies and declares engines.node >= 16.9.0, but target the runtime tier's floor, not Hono's. Bun 1.3.14. Companions: @hono/node-server@2.1.0, @hono/zod-validator@0.9.0 (peer hono >= 4.11.2, zod ^3.25 || ^4), @hono/standard-validator@0.4.0, @hono/zod-openapi@1.5.2. Rate limiting is not built in — hono-rate-limiter@0.5.3 is third-party.

Minimum patched version is 4.12.34, not just "4.x" — see the advisory table in Security. 4.13.0 also reworked the core request path for speed and added HTTP QUERY method support; treat a 4.12→4.13 bump as a real upgrade and re-run route tests.

The Hono footguns AI walks into most

1. The request body is a stream, read once — c.req caches, c.req.raw does not

Hono hands you a Web-standard Request, not Node's IncomingMessage. There is no req.body already-parsed object, and the body stream is consumed on first read.

HonoRequest shields you from most of that: c.req.json(), .text(), .arrayBuffer(), .parseBody() all go through an internal bodyCache and cross-convert, so calling them repeatedly — or after a validator already ran — is safe. c.req.raw is the underlying Request and has no such cache:

ts
// WRONG — the validator already drained raw; this throws "ReadableStream is locked"
app.post('/forward', zValidator('json', Schema), async (c) => {
return fetch(UPSTREAM, { method: 'POST', body: c.req.raw.body }) // raw.bodyUsed === true
})
// RIGHT — rebuild a fresh Request from the cached body
import { cloneRawRequest } from 'hono/request'
app.post('/forward', zValidator('json', Schema), async (c) => {
return fetch(UPSTREAM, await cloneRawRequest(c.req))
})

cloneRawRequest clones directly when raw.bodyUsed is false, otherwise rebuilds from bodyCache. If you bypassed Hono and read c.req.raw.json() yourself, there is no cache and it throws HTTPException(500) telling you so. Rule: read bodies through `c.req.*`, never through `c.req.raw.*`. Same rule outbound — a Response body is read-once, so res.clone() before you both log it and return it.

2. Context is request-scoped and dies with the response

One Context per request, alive until the response is returned. c.set() / c.get() values exist only inside that request.

  • Never store c in a module-level variable, a class field, or a closure that outlives the handler. On Workers you get Cannot perform I/O on behalf of a different request; on Bun you get silent cross-request bleed.
  • Fire-and-forget work must not hold c. Extract the values first, then hand those to the background task — and on Workers wrap it in c.executionCtx.waitUntil(p) or the isolate is frozen the moment you return. Reading c.executionCtx on any other runtime throws This context has no ExecutionContext; see references/runtime-portability.md for the branch that actually works.
  • Type variables with a generic on the app (new Hono<{ Variables: { user: User } }>()), not with the global ContextVariableMap. The docs are explicit that ContextVariableMap "adds types globally to all contexts, regardless of whether the middleware that sets the variable has actually run" — so a route missing its auth middleware still type-checks and c.get('user') is undefined at runtime.
3. await next() never throws — your try/catch middleware is dead code

The onion order is registration order: everything before await next() runs outward-in, everything after runs inward-out. The trap is that Hono catches handler and downstream-middleware errors itself, so next() resolves normally and puts the error on c.error:

ts
// WRONG — catch never fires; the transaction commits on a failed handler
app.use(async (c, next) => {
const tx = await db.begin()
try { await next(); await tx.commit() }
catch { await tx.rollback() } // unreachable
})
// RIGHT — decide from c.error and the response status
app.use(async (c, next) => {
const tx = await db.begin()
await next()
if (c.error || c.res.status >= 500) { await tx.rollback() } else { await tx.commit() }
})

Two more ordering rules:

  • Not awaiting `next()` silently skips the rest of the chain's post-phase and lets the handler race your middleware. Always await it.
  • Middleware either await next() and returns nothing, or returns a Response to short-circuit. A middleware that calls next() and returns a Response discards the handler's work. To replace a response after the fact, assign c.res — set it to undefined first, which is the documented way to drop the existing one.
  • Auth middleware must be registered before the routes it guards, on the same instance. app.use('/admin/*', auth) after app.route('/admin', adminApp) does not protect those routes.
4. validator() is a parser, not a guard

zValidator('json', Schema) gives you c.req.valid('json'). Three separate failures:

  • Validation is not authorization. A schema-valid { "orderId": "..." } is still a request to touch someone else's order. The ownership predicate belongs in the query — see Security.
  • A missing `Content-Type` yields `{}`. The docs: when you validate json or form, "the request _must_ contain a matching content-type header," otherwise the body is not parsed. If every field in your schema is optional, {} passes validation and the handler runs on nothing. Make at least one field required, or check the header.
  • Header targets must be lowercase keys — validate value['idempotency-key'], not Idempotency-Key. c.req.header() with no argument also returns all-lowercase keys.

Mass assignment is your job: define the input schema with exactly the client-settable fields, and take userId / tenantId / role / price from the authenticated context, never from c.req.valid().

5. Typed routing and the hc client drift from runtime reality

AppType inference only works if you chain route definitions (app.get(...).post(...)) and chain again at each .route() merge. Break the chain and the client silently degrades to any — no error, just no safety.

What the types do not know:

  • Responses produced by app.onError and by middleware are not in the inferred union unless you merge them with ApplyGlobalResponse. The client's exhaustive status handling is therefore incomplete.
  • c.notFound() blocks correct 404 inference — return c.json({...}, 404) instead.
  • The client is a compile-time artifact. A deployed server on an older build serves a different shape than the types say. Version the API or the type is a lie.

For large apps, export a pre-computed Client type from a wrapper module so tsc instantiates the generics once — otherwise tsserver recomputes them per keystroke and the editor stalls in proportion to route count.

6. The adapter split: it runs on Bun, it fails on Workers

Hono's core is runtime-neutral; everything platform-specific is an adapter import. Portable code on Bun is not automatically portable to Workers. Read references/runtime-portability.md before committing to a multi-runtime deploy.

WhatBunCloudflare Workers
Static filesserveStatic from hono/bunhono/cloudflare-workers (assets binding) — no disk
Node built-insworknodejs_compat required, and the subset depends on your compatibility_date. fs is a virtual filesystem (/tmp writable but per-request); child_process and worker_threads are importable stubs that do nothing
Configprocess.env via env(c)c.env.BINDING — process.env is absent by default
Work after the responsejust await itmust be c.executionCtx.waitUntil(p) — and c.executionCtx is a throwing getter off Workers, so c.executionCtx?.waitUntil?.(p) does not degrade gracefully, it 500s. Branch on getRuntimeKey() === 'workerd'
Request body capBun's maxRequestBodySize, default 128 MiBplatform limit
WebSocketscreateBunWebSocket() from hono/bunupgradeWebSocket from hono/cloudflare-workers

Use getRuntimeKey() (bun · workerd · node · deno · edge-light · fastly · other) when a branch is genuinely unavoidable, and env(c) to read config uniformly. Preset choice is a real decision: hono (SmartRouter) is the documented default for long-lived Bun/Node servers and is fine on Workers because isolates persist; hono/quick is for environments re-initialized per request; hono/tiny for size-constrained ones.

7. Streaming: once the first byte is written, onError is gone

stream() / streamText() / streamSSE() return immediately and the callback runs against an already-committed response. The docs state it plainly: if the streaming callback throws, "the onError event of Hono will not be triggered." Status and headers are already on the wire, so there is nothing left to turn into a 500 — the client sees a truncated 200.

ts
app.get('/events', (c) => streamSSE(c,
async (stream) => {
stream.onAbort(() => cleanup()) // client disconnect
while (!stream.aborted) {
await stream.writeSSE({ data: JSON.stringify(await nextEvent()) })
}
},
async (err, stream) => { log.error({ err }); await stream.close() } // the 3rd arg is the only handler
))

Do every failable thing — auth, the first DB read, permission checks — before returning the stream, so a real failure is still an ordinary status code. Always pass the third onError argument; always handle stream.aborted / onAbort, or a disconnected client leaves the producer running and billing.

8. onError and notFound — one shape, one place, no internals

app.onError((err, c) => Response) catches everything the handlers and middleware throw (not streaming callbacks, see §7). Route-level handlers take priority over a parent app's. app.notFound() only fires from the top-level app — setting it on a sub-router does nothing.

ts
import { HTTPException } from 'hono/http-exception'
app.onError((err, c) => {
if (err instanceof HTTPException) { return err.getResponse() }
c.get('log').error({ err, requestId: c.get('requestId') }, 'unhandled')
// never echo err.message on 5xx — driver errors carry SQL, table names, and paths
return c.json({ error: 'Internal error', requestId: c.get('requestId') }, 500)
})

Throw HTTPException(status, { message }) for expected failures; it carries the status through. A bare throw new Error() becomes a 500 with whatever your handler decides to print.

9. Module-scope state is wrong on edge isolates
ts
const hits = new Map<string, number>() // WRONG on Workers, unreliable on multi-process Bun

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
15
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/anantbhandarkar/make-it-right/mir-backend-bun-hono/badge)](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-bun-hono)

Something wrong with this skill or its page? Tell us.