Agent RulesAgent Rules
Builder
Options
Browse all rules by language and framework
Templates
Pre-built rule sets ready to use
Popular Rules
Top community-ranked rules leaderboard
GuidesAnalyzePricingContact
Builder
OptionsTemplatesPopular Rules
GuidesAnalyzePricingContact

Product

  • Builder
  • Templates
  • Browse Rules
  • My Library

Learn

  • What are AI Agent Rules?
  • Guides
  • FAQ
  • About

Resources

  • Terms
  • Privacy Policy
  • Pricing
  • Contact
  • DMCA Policy

Support

Help keep this project free.

Agent RulesAgent Rules Builder
© 2026 Aurora Algorithm Inc.
Back to Templates

TypeScript + Hono

Rules for Hono web framework covering middleware patterns, routing, validation, multi-runtime deployment (Cloudflare Workers, Deno, Bun, Node.js), and RPC mode.

typescriptTypeScript/honoHono
typescript
hono
edge
cloudflare
api
middleware
Customize in Builder

Details

Language
typescriptTypeScript
Framework
honoHono

Rules Content

AGENTS.md
Edit in Builder

TypeScript + Hono Agent Rules

Project Context

You are building a Hono application targeting edge runtimes — Cloudflare Workers, Vercel Edge Functions, Bun, or Deno Deploy. Hono is runtime-agnostic by design; keep core logic free of platform-specific APIs and isolate adapter code behind thin wrappers.

Code Style & Structure

- Use TypeScript strict mode. Pass `Bindings` and `Variables` generics to `new Hono<{ Bindings: Env; Variables: Vars }>()` for typed `c.env` and `c.var`.
- Use functional patterns. Avoid classes; Hono handlers and middleware are plain functions.
- Use named exports for route modules and middleware files.
- Keep handler functions under 20 lines. Extract business logic to service modules that have no Hono imports.

Project Structure

```
src/
index.ts # Entry point — creates app, registers routes, exports fetch
app.ts # createApp(): composes middleware, mounts routers
routes/
users.ts # new Hono() with /users prefix, mounted in app.ts
auth.ts
middleware/
auth.ts # JWT verification, sets c.var.user
logger.ts
schemas/ # Zod schemas and inferred types per domain
services/ # Business logic — no Hono imports
lib/ # Crypto helpers, formatting, constants
types/ # Bindings, Variables, shared interfaces
```

Routing

- Define routes using method-specific helpers: `app.get()`, `app.post()`, `app.put()`, `app.delete()`.
- Group related routes with `new Hono()` and mount with `app.route('/prefix', subApp)`.
- Use typed path param extraction: `c.req.param('id')`. Use `c.req.valid('param')` after `zValidator` for Zod-parsed params.
- Register `app.notFound((c) => c.json({ error: 'Not Found' }, 404))` and `app.onError(handler)` for consistent error responses.
- Avoid `app.all()` unless building a passthrough proxy — explicit method handlers prevent accidental handler matching.

Middleware

- Write middleware as `async (c, next) => { ...; await next(); ... }`.
- Use built-in middleware: `cors()`, `logger()`, `secureHeaders()`, `timing()`, `bearerAuth()`.
- Set request-scoped data via `c.set('user', userData)` in auth middleware. Access with `c.get('user')` in handlers.
- Apply middleware at the correct scope: global with `app.use('*', mw)`, group-level on a sub-app, or per-route.
- Order intentionally: `logger` → `secureHeaders` → `cors` → auth → validation → handler.
- For Cloudflare Workers, use `c.executionCtx.waitUntil()` to extend the request lifetime for background work.

Validation with Zod

- Use `@hono/zod-validator` for request validation: `zValidator('json', schema)`, `zValidator('query', schema)`, `zValidator('param', schema)`.
- Infer types with `z.infer<typeof schema>` and use `c.req.valid('json')` in the handler for type-safe access.
- Pass a custom hook to `zValidator` to return structured error responses: `zValidator('json', schema, (result, c) => { if (!result.success) return c.json({ errors: result.error.issues }, 422) })`.
- Define schemas in `src/schemas/` and import them into route files. Never inline `z.object()` inside route definitions.
- Use `.transform()` for normalization (trim strings, parse ISO dates) and `.refine()` for cross-field rules.

Context & Bindings

- Access Cloudflare bindings through `c.env` with a typed `Bindings` interface: KV, D1, R2, Queues, service bindings.
- Use `c.var` for request-scoped variables set by middleware. Declare them in the `Variables` type for type safety.
- Return responses with typed helpers: `c.json(data, status)`, `c.text(str)`, `c.html(str)`, `c.redirect(url)`.
- Stream responses with `c.stream(async (stream) => { ... })` for SSE or chunked transfer.
- Set response headers with `c.header('Cache-Control', 'public, max-age=3600')`.

Error Handling

- Register `app.onError((err, c) => { ... })` as the global error handler. Always return a JSON response with a consistent shape.
- Throw `new HTTPException(404, { message: 'User not found' })` for expected HTTP errors in handlers.
- Never expose stack traces in production. Check `process.env.NODE_ENV !== 'production'` before including error details.
- Log errors with request context: `c.req.method`, `c.req.path`, and a request ID from headers.
- Return a consistent error shape: `{ error: { code, message, details? } }`.

Performance

- Hono has virtually zero overhead on Cloudflare Workers — avoid adding unnecessary middleware layers.
- Use `c.executionCtx.waitUntil(promise)` for fire-and-forget background work (analytics, logging) without blocking the response.
- Cache responses at the Cloudflare CDN layer with `Cache-Control` headers rather than application-level caching.
- For D1 queries, batch reads using `db.batch([...])` to minimize round-trip latency.
- Keep the total bundle size below 1 MB for Workers; tree-shake unused Hono packages.

Testing

- Use Hono's built-in test client: `const res = await app.request('/path', { method: 'POST', body: JSON.stringify(data) })`.
- Create a test app instance with mocked bindings injected via the constructor options.
- Test middleware in isolation by creating a minimal app that exercises only the middleware under test.
- Use `vitest` as the test runner for fast, ESM-compatible execution.
- Assert `res.status`, `res.headers.get('content-type')`, and `await res.json()` for each test case.
- Test validation errors: send invalid JSON → expect 422, missing required field → expect 422.

Deployment

- Cloudflare Workers: define bindings in `wrangler.toml`, deploy with `wrangler deploy`, develop with `wrangler dev`.
- Bun: use `Bun.serve({ fetch: app.fetch })` as the entry point.
- Deno Deploy: use `Deno.serve(app.fetch)` as the entry point.
- Vercel Edge: export `export const GET = handle(app)` using `@hono/vercel` adapter.
- Keep runtime-specific adapters in `src/adapters/` and import only in the entry point.

Related Templates

typescript

Next.js + TypeScript

Production-ready rules for Next.js applications with TypeScript, App Router, and React Server Components.

typescript

React + TypeScript

Modern React with TypeScript, hooks-first patterns, and component best practices.

typescript

React Performance

Eliminate render waterfalls, reduce bundle size, and optimize server and client rendering in React applications.