Hono typescript

From Mindrally/skills · View interactive version

Hono typescript is an AI agent skill from the GitHub repository Mindrally/skills. Guidelines for building edge-first, high-performance APIs with Hono and TypeScript for Cloudflare Workers, Deno, Bun, and Node.js

How to use this skill

Skill file

Hono TypeScript Development

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.

TypeScript General Guidelines

Basic Principles

Nomenclature

Functions

Types and Interfaces

Hono-Specific Guidelines

Project Structure

src/
  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

App Initialization

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 }>();

Routing

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);

Middleware

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();
};

Request Validation with Zod

import { 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
});

Context and Response Handling

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);
});

Error Handling

import { 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);
});

Cloudflare Workers Integration

// 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);

Testing

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);
  });
});

Performance

Security

Multi-Runtime Support

Hono 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);
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.