hono-routing
БесплатноБез исполняемых скриптовНе проверенThis skill provides comprehensive knowledge for building type-safe APIs with Hono, focusing on routing patterns, middleware composition, request validation…
Об этом скилле
Hono Routing & Middleware
Status: Production Ready ✅ Last Updated: 2025-10-22 Dependencies: None (framework-agnostic) Latest Versions: [email protected], [email protected], [email protected], @hono/[email protected], @hono/[email protected]
Quick Start (15 Minutes)
1. Install Hono
npm install [email protected]
Why Hono:
- Fast: Built on Web Standards, runs on any JavaScript runtime
- Lightweight: ~10KB, no dependencies
- Type-safe: Full TypeScript support with type inference
- Flexible: Works on Cloudflare Workers, Deno, Bun, Node.js, Vercel
2. Create Basic App
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => {
return c.json({ message: 'Hello Hono!' })
})
export default app
CRITICAL:
- Use
c.json(),c.text(),c.html()for responses - Return the response (don't use
res.send()like Express) - Export app for runtime (Cloudflare Workers, Deno, Bun, Node.js)
3. Add Request Validation
npm install [email protected] @hono/[email protected]
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const schema = z.object({
name: z.string(),
age: z.number(),
})
app.post('/user', zValidator('json', schema), (c) => {
const data = c.req.valid('json')
return c.json({ success: true, data })
})
Why Validation:
- Type-safe request data
- Automatic error responses
- Runtime validation, not just TypeScript
The 6-Part Hono Mastery Guide
Part 1: Routing Patterns
Basic Routes
import { Hono } from 'hono'
const app = new Hono()
// GET request
app.get('/posts', (c) => c.json({ posts: [] }))
// POST request
app.post('/posts', (c) => c.json({ created: true }))
// PUT request
app.put('/posts/:id', (c) => c.json({ updated: true }))
// DELETE request
app.delete('/posts/:id', (c) => c.json({ deleted: true }))
// Multiple methods
app.on(['GET', 'POST'], '/multi', (c) => c.text('GET or POST'))
// All methods
app.all('/catch-all', (c) => c.text('Any method'))
Key Points:
- Always return a Response (c.json, c.text, c.html, etc.)
- Routes are matched in order (first match wins)
- Use specific routes before wildcard routes
Route Parameters
// Single parameter
app.get('/users/:id', (c) => {
const id = c.req.param('id')
return c.json({ userId: id })
})
// Multiple parameters
app.get('/posts/:postId/comments/:commentId', (c) => {
const { postId, commentId } = c.req.param()
return c.json({ postId, commentId })
})
// Optional parameters (using wildcards)
app.get('/files/*', (c) => {
const path = c.req.param('*')
return c.json({ filePath: path })
})
CRITICAL:
c.req.param('name')returns single parameterc.req.param()returns all parameters as object- Parameters are always strings (cast to number if needed)
Query Parameters
app.get('/search', (c) => {
// Single query param
const q = c.req.query('q')
// Multiple query params
const { page, limit } = c.req.query()
// Query param array (e.g., ?tag=js&tag=ts)
const tags = c.req.queries('tag')
return c.json({ q, page, limit, tags })
})
Best Practice:
- Use validation for query params (see Part 4)
- Provide defaults for optional params
- Parse numbers/booleans from query strings
Wildcard Routes
// Match any path after /api/
app.get('/api/*', (c) => {
const path = c.req.param('*')
return c.json({ catchAll: path })
})
// Named wildcard
app.get('/files/:filepath{.+}', (c) => {
const filepath = c.req.param('filepath')
return c.json({ file: filepath })
})
Route Grouping (Sub-apps)
// Create sub-app
const api = new Hono()
api.get('/users', (c) => c.json({ users: [] }))
api.get('/posts', (c) => c.json({ posts: [] }))
// Mount sub-app
const app = new Hono()
app.route('/api', api)
// Result: /api/users, /api/posts
Why Group Routes:
- Organize large applications
- Share middleware for specific routes
- Better code structure and maintainability
Part 2: Middleware Composition
Middleware Flow
import { Hono } from 'hono'
const app = new Hono()
// Global middleware (runs for all routes)
app.use('*', async (c, next) => {
console.log(`[${c.req.method}] ${c.req.url}`)
await next() // CRITICAL: Must call next()
console.log('Response sent')
})
// Route-specific middleware
app.use('/admin/*', async (c, next) => {
// Auth check
const token = c.req.header('Authorization')
if (!token) {
return c.json({ error: 'Unauthorized' }, 401)
}
await next()
})
app.get('/admin/dashboard', (c) => {
return c.json({ message: 'Admin Dashboard' })
})
CRITICAL:
- Always call
await next()in middleware - Middleware runs BEFORE the handler
- Return early to prevent handler execution
- Check
c.errorAFTERnext()for error handling
Built-in Middleware
import { Hono } f
Установить hono-routing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл hono-routing?
This skill provides comprehensive knowledge for building type-safe APIs with Hono, focusing on routing patterns, middleware composition, request validation, RPC client/server patterns, error handling, and context management. Use when: building APIs with Hono (any runtime), setting up request validation with Zod/Valibot/Typia/ArkType validators, creating type-safe RPC client/server communication, implementing custom middleware, handling errors with HTTPException, extending Hono context with custom variables, or encountering middleware type inference issues, validation hook confusion, or RPC performance problems. Keywords: hono, hono routing, hono middleware, hono rpc, hono validator, zod validator, valibot validator, type-safe api, hono context, hono error handling, HTTPException, c.req.valid, middleware composition, hono hooks, typed routes, hono client, middleware response not typed, hono validation failed, hono rpc type inference
Как установить скилл hono-routing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл hono-routing запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic