Skip to main content
skill CX Codex

hono-core — Claude Code skill: Hono framework basics

A skill covering Hono routing, context, handlers and response patterns, so the same code runs on Cloudflare Workers, Deno, Bun and Node.js.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add bobmatnyc/claude-mpm-skills --skill hono-core -a claude-code
Open on GitHub

What hono-core does

This skill hands the agent a reference for Hono, a web framework built on Web Standards. It covers creating an app, the context object c, response methods, path parameters and route grouping. The agent leans on it while you build an API or web app for edge and serverless targets.

Multi-file setup gets its own section: routes live in separate modules and mount through app.route(). There is also a typed-handler pattern with createFactory and generics for Bindings and Variables. On Node.js you need the @hono/node-server adapter; a fresh project starts with npm create hono@latest.

The skill text cuts off at the error section, so error handling is not covered. Coming from Express or Fastify, the shift is real: there is no separate req and res, just one c object. That is worth checking against code that leans on Node-specific APIs.

What it helps with

  • ship an API that runs the same on Cloudflare Workers and Node.js
  • define routes with parameters, regex validation and wildcards
  • split routes into files and mount them under one prefix
  • type environment bindings and request variables in handlers
  • return JSON, HTML, a redirect or a stream from one place

Example prompts for the agent

  • Create a Hono app and add a GET /users/:id route that returns JSON
  • Split the routes into files under routes/ and mount them with app.route()
  • Add Bindings and Variables types to this Hono app

How to install hono-core

1Skills CLI (Vercel)

npx skills add bobmatnyc/claude-mpm-skills --skill hono-core -a claude-code

2Manually: put the files in place

~/.claude/skills/hono-core/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/hono-core/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about hono-core

How do I install hono-core in Claude?

Run npx skills add bobmatnyc/claude-mpm-skills --skill hono-core -a claude-code. The skill lands at ~/.claude/skills/hono-core/SKILL.md.

What does hono-core do?

It gives the agent Hono fundamentals: routing, request context, handlers and response methods. Useful when you want one codebase across several runtimes.

Which runtimes does Hono support?

Cloudflare Workers, Deno, Bun, Node.js, Vercel and AWS Lambda. Node.js needs the @hono/node-server package.

Source text

SKILL.md · MIT
---
name: hono-core
description: Hono ultrafast web framework fundamentals - routing, context, handlers, and response patterns for multi-runtime deployment
user-invocable: false
disable-model-invocation: true
skill_version: 1.0.0
updated_at: 2025-01-03T00:00:00Z
tags: [hono, web-framework, routing, typescript, cloudflare-workers, deno, bun, nodejs]
progressive_disclosure:
  entry_point:
    summary: "Ultrafast web framework built on Web Standards for Cloudflare Workers, Deno, Bun, Node.js"
    when_to_use: "Building APIs/web apps that need multi-runtime deployment, edge computing, or lightweight performance"
    quick_start: "1. npm create hono@latest 2. Define routes with app.get/post 3. Return responses via context"
  references: []
context_limit: 800
---

# Hono - Ultrafast Web Framework

## Overview

Hono is a small, simple, and ultrafast web framework built on Web Standards. It runs on Cloudflare Workers, Deno, Bun, Node.js, and more with the same codebase. The name means "flame" in Japanese.

**Key Features**:
- Built on Web Standards (Request/Response/fetch)
- Multi-runtime: Cloudflare Workers, Deno, Bun, Node.js, Vercel, AWS Lambda
- Ultrafast routing with RegExpRouter
- First-class TypeScript support
- Lightweight (~14KB minified)
- Rich middleware ecosystem

**Installation**:
```bash
# Create new project (recommended)
npm create hono@latest my-app

# Or install in existing project
npm install hono

# Runtime-specific adapters
npm install @hono/node-server  # Node.js
```

## When to Use This Skill

Use Hono when:
- Building APIs for edge/serverless environments (Cloudflare Workers, Vercel Edge)
- Need multi-runtime portability (same code on Bun, Deno, Node.js)
- Want TypeScript-first development with excellent type inference
- Building lightweight, high-performance APIs
- Need built-in middleware for common patterns (CORS, auth, compression)

**Hono vs Other Frameworks**:
- **Hono**: Multi-runtime, Web Standards, ultrafast, edge-optimized
- **Express**: Node.js only, larger ecosystem, slower
- **Fastify**: Node.js only, schema-based, good performance
- **Elysia**: Bun only, excellent performance, different API style

## Core Concepts

### Creating an Application

```typescript
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.text('Hello Hono!'))

export default app
```

**With TypeScript Generics** (for bindings/variables):
```typescript
type Bindings = {
  DATABASE_URL: string
  API_KEY: string
}

type Variables = {
  user: { id: string; name: string }
}

const app = new Hono<{ Bindings: Bindings; Variables: Variables }>()
```

### The Context Object (c)

The context `c` provides access to request data and response methods:

```typescript
app.get('/users/:id', async (c) => {
  // Request data
  const id = c.req.param('id')           // Path parameter
  const query = c.req.query('sort')       // Query parameter ?sort=asc
  const queries = c.req.queries('tags')   // Multiple: ?tags=a&tags=b
  const header = c.req.header('Authorization')
  const body = await c.req.json()         // JSON body
  const form = await c.req.formData()     // Form data

  // Environment (Cloudflare Workers bindings)
  const db = c.env.DATABASE_URL

  // Custom variables (set by middleware)
  const user = c.get('user')

  // Response methods
  return c.text('Plain text')
  return c.json({ id, name: 'User' })
  return c.html('<h1>Hello</h1>')
  return c.redirect('/login')
  return c.notFound()
})
```

### Response Methods

```typescript
// Text response
c.text('Hello', 200)

// JSON response
c.json({ message: 'Success' }, 201)
c.json({ error: 'Not found' }, 404)

// HTML response
c.html('<h1>Hello</h1>')

// Redirect
c.redirect('/login')           // 302 default
c.redirect('/login', 301)      // Permanent redirect

// Headers
c.header('X-Custom', 'value')
c.header('Cache-Control', 'max-age=3600')

// Streaming
c.streamText(async (stream) => {
  await stream.write('Hello ')
  await stream.write('World!')
})

// Raw Response
return new Response('Raw', { status: 200 })
```

## Routing Patterns

### Basic Routing

```typescript
const app = new Hono()

// HTTP methods
app.get('/users', getUsers)
app.post('/users', createUser)
app.put('/users/:id', updateUser)
app.delete('/users/:id', deleteUser)
app.patch('/users/:id', patchUser)

// All methods
app.all('/webhook', handleWebhook)

// Custom methods
app.on('PURGE', '/cache', purgeCache)
app.on(['GET', 'POST'], '/form', handleForm)
```

### Path Parameters

```typescript
// Single parameter
app.get('/users/:id', (c) => {
  const id = c.req.param('id')
  return c.json({ id })
})

// Multiple parameters
app.get('/posts/:postId/comments/:commentId', (c) => {
  const { postId, commentId } = c.req.param()
  return c.json({ postId, commentId })
})

// Optional parameter
app.get('/api/animal/:type?', (c) => {
  const type = c.req.param('type') || 'all'
  return c.json({ type })
})

// Regex validation
app.get('/posts/:id{[0-9]+}', (c) => {
  const id = c.req.param('id')  // Only numeric IDs
  return c.json({ id })
})

// Wildcards
app.get('/files/*', (c) => {
  const path = c.req.param('*')  // Everything after /files/
  return c.text(`File: ${path}`)
})
```

### Route Grouping

```typescript
// Using app.route()
const api = new Hono()
api.get('/users', getUsers)
api.get('/posts', getPosts)

const app = new Hono()
app.route('/api/v1', api)  // /api/v1/users, /api/v1/posts

// Using basePath()
const v2 = new Hono().basePath('/api/v2')
v2.get('/users', getUsers)  // /api/v2/users

// Chaining
app
  .get('/a', handlerA)
  .post('/b', handlerB)
  .delete('/c', handlerC)
```

### Route Organization (Multi-File)

```typescript
// routes/users.ts
import { Hono } from 'hono'

const users = new Hono()

users.get('/', async (c) => {
  return c.json({ users: [] })
})

users.post('/', async (c) => {
  const body = await c.req.json()
  return c.json({ created: body }, 201)
})

users.get('/:id', async (c) => {
  const id = c.req.param('id')
  return c.json({ id })
})

export default users

// app.ts
import { Hono } from 'hono'
import users from './routes/users'
import posts from './routes/posts'

const app = new Hono()

app.route('/users', users)
app.route('/posts', posts)

export default app
```

## Handler Patterns

### Inline Handlers

```typescript
// Simple handler
app.get('/hello', (c) => c.text('Hello!'))

// Async handler
app.get('/users', async (c) => {
  const users = await fetchUsers()
  return c.json({ users })
})

// Multiple handlers (middleware chain)
app.get('/admin', authenticate, authorize, (c) => {
  return c.json({ admin: true })
})
```

### Using Factory for Type-Safe Handlers

```typescript
import { createFactory } from 'hono/factory'

const factory = createFactory<{ Bindings: Bindings }>()

// Create typed handler
const getUser = factory.createHandlers(async (c) => {
  const id = c.req.param('id')
  const db = c.env.DATABASE_URL  // Typed!
  return c.json({ id })
})

app.get('/users/:id', ...getUser)
```

## Error Handling

### Built-in Error Handling

```typescript
import { HTTPException } from 'hono/http-exception'

app.get('/users/:id', async (c) => {
  const user = await findUser(c.req.param('id'))

  if (!user) {
    throw new HTTPException(404, { message: 'User not found' })
  }

  return c.json(user)
})

// Global error handler
app.onError((err, c) => {
  console.error(`${err}`)

  if (err instanceof HTTPException) {
    return err.getResponse()
  }

  return c.json({ error: 'Internal Server Error' }, 500)
})

// Not found handler
app.notFound((c) => {
  return c.json({ error: 'Route not found' }, 404)
})
```

### Custom Error Classes

```typescript
class ValidationError extends HTTPException {
  constructor(errors: string[]) {
    super(400, {
      message: 'Validation failed',
      cause: errors
    })
  }
}

class AuthenticationError extends HTTPException {
  constructor() {
    super(401, { message: 'Authentication required' })
  }
}
```

## Runtime-Specific Exports

### Cloudflare Workers

```typescript
// src/index.ts
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Cloudflare!'))

export default app
```

### Node.js

```typescript
// src/index.ts
import { serve } from '@hono/node-server'
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Node!'))

serve({
  fetch: app.fetch,
  port: 3000
})
```

### Bun

```typescript
// src/index.ts
import { Hono } from 'hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Bun!'))

export default {
  port: 3000,
  fetch: app.fetch
}
```

### Deno

```typescript
// main.ts
import { Hono } from 'npm:hono'

const app = new Hono()
app.get('/', (c) => c.text('Hello Deno!'))

Deno.serve(app.fetch)
```

## Best Practices

### Write Handlers Inline (Not Controllers)

```typescript
// CORRECT: Inline handlers with proper type inference
app.get('/users/:id', async (c) => {
  const id = c.req.param('id')  // Type: string
  return c.json({ id })
})

// AVOID: Controller-style (loses type inference)
class UserController {
  getUser(c: Context) {
    const id = c.req.param('id')  // Type: string | undefined
    return c.json({ id })
  }
}
```

### Use Modular Routes

```typescript
// CORRECT: Split routes by domain
// routes/users.ts
export const users = new Hono()
  .get('/', listUsers)
  .post('/', createUser)
  .get('/:id', getUser)

// app.ts
app.route('/users', users)
```

### Type Everything

```typescript
// Define your environment bindings
type Bindings = {
  DATABASE_URL: string
  JWT_SECRET: string
  MY_KV: KVNamespace
}

// Pass to Hono
const app = new Hono<{ Bindings: Bindings }>()

// Now c.env is fully typed
app.get('/', (c) => {
  const url = c.env.DATABASE_URL  // string
  const kv = c.env.MY_KV          // KVNamespace
})
```

## Quick Reference

### Common Context Methods

| Method | Description | Example |
|--------|-------------|---------|
| `c.req.param(name)` | Get path parameter | `c.req.param('id')` |
| `c.req.query(name)` | Get query parameter | `c.req.query('page')` |
| `c.req.header(name)` | Get request header | `c.req.header('Authorization')` |
| `c.req.json()` | Parse JSON body | `await c.req.json()` |
| `c.req.formData()` | Parse form data | `await c.req.formData()` |
| `c.text(str, status)` | Text response | `c.text('OK', 200)` |
| `c.json(obj, status)` | JSON response | `c.json({}, 201)` |
| `c.html(str)` | HTML response | `c.html('<h1>Hi</h1>')` |
| `c.redirect(url)` | Redirect | `c.redirect('/login')` |
| `c.header(k, v)` | Set response header | `c.header('X-Custom', 'val')` |
| `c.set(key, val)` | Set context variable | `c.set('user', user)` |
| `c.get(key)` | Get context variable | `c.get('user')` |
| `c.env` | Environment bindings | `c.env.API_KEY` |

### HTTP Methods

```typescript
app.get(path, ...handlers)
app.post(path, ...handlers)
app.put(path, ...handlers)
app.delete(path, ...handlers)
app.patch(path, ...handlers)
app.options(path, ...handlers)
app.head(path, ...handlers)
app.all(path, ...handlers)
app.on(method, path, ...handlers)
```

## Related Skills

- **hono-middleware** - Middleware patterns and composition
- **hono-validation** - Request validation with Zod
- **hono-rpc** - Type-safe RPC client
- **hono-testing** - Testing patterns
- **hono-jsx** - Server-side JSX rendering
- **hono-cloudflare** - Cloudflare Workers deployment

---

**Version**: Hono 4.x
**Last Updated**: January 2025
**License**: MIT

© bobmatnyc · MIT · bobmatnyc/claude-mpm-skills

Similar skills

Everything for Backend and APIs →

From the same set65

wordpress-security-validation A skill for safe WordPress plugin and theme development: sanitize input, validate logic, escape output. Useful when handling forms, AJAX, or rendering untrusted content. CX Codex +1 581installs fastify A skill that feeds your coding agent production Fastify patterns for TypeScript: schema validation, plugins, error handling, inject tests. CX Codex +1 571installs git-workflow A skill that hands your agent ready Git patterns: commits, branches, conflicts, rebase and hooks. Useful whenever version control is in play. CX Codex +1 556installs zustand A skill that teaches your agent zustand: a small hook-based state manager for React with no providers. Handy when you need global state but not Redux. CX Codex +1 485installs asyncio A Python asyncio skill covering coroutines, tasks, the event loop, aiohttp and async FastAPI endpoints. Useful when code waits on network or database. CX Codex +1 476installs typescript-core A skill with modern TypeScript patterns: a strict tsconfig, runtime validation, advanced types. Useful once a TS codebase outgrows its type setup. CX Codex +1 475installs celery A Celery reference skill for background jobs, scheduled tasks and worker chains in Python. Useful when long operations should leave the request cycle. CX Codex +1 454installs golang-testing-strategies A skill for writing Go tests: table-driven cases, testify assertions, gomock mocks, benchmarks and CI coverage. Useful when a project's test suite needs structure. CX Codex +1 443installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor