Guidelines for building edge-first, high-performance APIs with Hono and TypeScript for Cloudflare Workers, Deno, Bun, and Node.js
You are an expert in Hono and TypeScript development with deep knowledge of building ultrafast, edge-first APIs that run on Cloudflare Workers, Deno, Bun, and Node.js.
any type - create necessary types insteadisLoading, hasError, canDeletereadonly for immutable propertiesimport type for type-only importssrc/
routes/
{resource}/
index.ts
handlers.ts
validators.ts
middleware/
auth.ts
cors.ts
logger.ts
services/
{domain}Service.ts
types/
index.ts
utils/
config/
index.ts
import { Hono } from 'hono';
// Type your environment bindings
type Bindings = {
DB: D1Database;
KV: KVNamespace;
JWT_SECRET: string;
};
type Variables = {
user: User;
};
const app = new Hono<{ Bindings: Bindings; Variables: Variables }>();
app.route()const users = new Hono<{ Bindings: Bindings }>();
users.get('/', listUsers);
users.get('/:id', getUser);
users.post('/', zValidator('json', createUserSchema), createUser);
users.put('/:id', zValidator('json', updateUserSchema), updateUser);
users.delete('/:id', deleteUser);
app.route('/api/users', users);
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { jwt } from 'hono/jwt';
app.use('*', logger());
app.use('/api/*', cors());
app.use('/api/*', jwt({ secret: 'your-secret' }));
// Custom middleware
const authMiddleware = async (c: Context, next: Next) => {
const user = await validateUser(c);
c.set('user', user);
await next();
};
@hono/zod-validator for request validationimport { z } from 'zod';
import { zValidator } from '@hono/zod-validator';
const createUserSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
role: z.enum(['user', 'admin']).default('user'),
});
type CreateUserInput = z.infer<typeof createUserSchema>;
app.post('/users', zValidator('json', createUserSchema), async (c) => {
const data = c.req.valid('json');
// data is typed as CreateUserInput
});
c.json(), c.text(), c.html()app.get('/users/:id', async (c) => {
const id = c.req.param('id');
const db = c.env.DB;
const user = await db.prepare('SELECT * FROM users WHERE id = ?')
.bind(id)
.first();
if (!user) {
return c.json({ error: 'User not found' }, 404);
}
return c.json(user);
});
HTTPException for expected errorsimport { HTTPException } from 'hono/http-exception';
// Throwing errors
if (!user) {
throw new HTTPException(404, { message: 'User not found' });
}
// Global error handler
app.onError((err, c) => {
if (err instanceof HTTPException) {
return c.json({ error: err.message }, err.status);
}
console.error(err);
return c.json({ error: 'Internal Server Error' }, 500);
});
// D1 Database
const result = await c.env.DB.prepare('SELECT * FROM users').all();
// KV Storage
await c.env.KV.put('key', 'value');
const value = await c.env.KV.get('key');
// R2 Storage
await c.env.BUCKET.put('file.txt', content);
import { testClient } from 'hono/testing';
import { describe, it, expect } from 'vitest';
describe('User API', () => {
const client = testClient(app);
it('should list users', async () => {
const res = await client.api.users.$get();
expect(res.status).toBe(200);
const data = await res.json();
expect(Array.isArray(data)).toBe(true);
});
});
hono/tiny preset for minimal bundle sizehono/secure-headers middlewareHono runs on multiple runtimes. Configure appropriately:
// Cloudflare Workers
export default app;
// Node.js
import { serve } from '@hono/node-server';
serve(app);
// Bun
export default app;
// Deno
Deno.serve(app.fetch);
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer