หลายปีที่ผ่านมา การเลือกเฟรมเวิร์กเว็บ JavaScript หมายถึงการยอมรับการแลกเปลี่ยน Express ใช้ได้สากลแต่ช้าและผูกกับ Node, Fastify เร็วแต่เฉพาะ Node, Next.js ครบครันแต่หนัก เมื่อ runtime แบบ edge — Cloudflare Workers, Deno Deploy, Bun, Vercel Edge — มาถึง เฟรมเวิร์กเหล่านั้นเผยข้อจำกัด
Hono (ภาษาญี่ปุ่นแปลว่า "เปลวไฟ" 🔥) คือคำตอบสมัยใหม่ เฟรมเวิร์กขนาดต่ำกว่า 14KB ที่สร้างบนมาตรฐานเว็บทั้งหมด (Request, Response, fetch) ทำงานทุกที่ที่มี runtime JavaScript รหัสเดียวกัน deploy ได้บน Cloudflare Workers, Bun, Deno, Node.js, Vercel, Netlify และ AWS Lambda โดยไม่มีการเปลี่ยนแปลง
ทำไมต้อง Hono
- ประสิทธิภาพ
RegExpRouterคอมไพล์รูปแบบเส้นทางทั้งหมดเป็น regex เดียว หลีกเลี่ยงลูปเชิงเส้นของเราเตอร์แบบดั้งเดิม Benchmark เกิน 400,000 ops/วินาที - ความสามารถในการพกพา มาตรฐานเว็บหมายถึงไม่มี dependency กับ Node เลย
app.fetchเดียวกัน export เป็น default ใน Cloudflare Worker ส่งให้Bun.servemount ใน Deno server หรือปรับด้วย@hono/node-server - DX แบบ TypeScript-first Path parameter ถูก infer เป็น literal type, RPC client type-safe end-to-end
เริ่มต้น
npm create hono@latest my-api cd my-api npm install npm run dev
Starter ถามว่าใช้ template ไหน: cloudflare-workers, bun, deno, nodejs, vercel, aws-lambda, nextjs และอื่นๆ
// src/index.ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Hono!')) export default app
บน Cloudflare Workers แค่นี้พอ บน Bun: Bun.serve({ fetch: app.fetch, port: 3000 }) บน Node: serve({ fetch: app.fetch }) จาก @hono/node-server
การกำหนดเส้นทาง
import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Home')) app.get('/posts/:id', (c) => { const id = c.req.param('id') return c.json({ id }) }) app.get('/posts/:id/comments/:commentId', (c) => { const { id, commentId } = c.req.param() return c.json({ id, commentId }) }) app.get('/files/*', (c) => c.text('Wildcard')) app.post('/posts', async (c) => { const body = await c.req.json() return c.json({ created: body }, 201) })
การจัดกลุ่มเส้นทาง
// routes/posts.ts import { Hono } from 'hono' const posts = new Hono() posts.get('/', (c) => c.json({ posts: [] })) posts.get('/:id', (c) => c.json({ id: c.req.param('id') })) export default posts // src/index.ts import { Hono } from 'hono' import posts from './routes/posts' const app = new Hono() app.route('/posts', posts)
ออบเจ็กต์ Context
app.post('/echo', async (c) => { const userAgent = c.req.header('User-Agent') const page = c.req.query('page') const body = await c.req.json() const env = c.env c.set('requestId', crypto.randomUUID()) const id = c.get('requestId') c.header('X-Request-Id', id) c.status(200) return c.json({ userAgent, page, body, id }) })
มิดเดิลแวร์: โมเดลหัวหอม
import { Hono } from 'hono' import { logger } from 'hono/logger' import { cors } from 'hono/cors' import { secureHeaders } from 'hono/secure-headers' const app = new Hono() app.use('*', logger()) app.use('*', secureHeaders()) app.use('/api/*', cors({ origin: 'https://spinny.dev' })) app.use('*', async (c, next) => { const start = performance.now() await next() c.header('X-Response-Time', `${performance.now() - start}ms`) })
มิดเดิลแวร์ในตัว
| มิดเดิลแวร์ | หน้าที่ |
|---|---|
logger | ล็อกแบบมีโครงสร้างของ method, path, status, ระยะเวลา |
cors | CORS ปรับได้ตาม origin, methods, headers |
csrf | การป้องกัน CSRF ตาม origin |
secureHeaders | ตั้ง CSP, HSTS, X-Frame-Options |
bearerAuth / basicAuth | Bearer/Basic auth พร้อมใช้ |
jwt | ตรวจสอบ/เซ็น JWT ด้วย jose |
etag | สร้าง ETag และจัดการ 304 |
cache | แคชผ่าน Web Cache API |
compress | gzip/deflate สำหรับ response |
bodyLimit | ปฏิเสธ body เกินเกณฑ์ |
timing | ส่วนหัว Server-Timing สำหรับ profiling |
มิดเดิลแวร์กำหนดเอง type-safe
import { createMiddleware } from 'hono/factory' type AuthVars = { userId: string; role: 'user' | 'admin' } export const requireAuth = createMiddleware<{ Variables: AuthVars }>( async (c, next) => { const token = c.req.header('Authorization')?.replace('Bearer ', '') if (!token) return c.json({ error: 'Unauthorized' }, 401) const payload = await verifyJwt(token) c.set('userId', payload.sub) c.set('role', payload.role) await next() } ) app.get('/me', requireAuth, (c) => { const userId = c.var.userId return c.json({ userId }) })
การตรวจสอบด้วย Zod
import { Hono } from 'hono' import { zValidator } from '@hono/zod-validator' import { z } from 'zod' const createPost = z.object({ title: z.string().min(1).max(200), body: z.string().min(1), tags: z.array(z.string()).default([]), }) app.post( '/posts', zValidator('json', createPost), (c) => { const data = c.req.valid('json') return c.json({ ok: true, post: data }, 201) } )
RPC: ไคลเอ็นต์ type-safe end-to-end
// server.ts import { Hono } from 'hono' import { zValidator } from '@hono/zod-validator' import { z } from 'zod' const app = new Hono() .get('/posts/:id', (c) => c.json({ id: c.req.param('id'), title: 'Hello' }) ) .post( '/posts', zValidator('json', z.object({ title: z.string(), body: z.string() })), (c) => c.json({ ok: true }, 201) ) export type AppType = typeof app export default app
// client.ts import { hc } from 'hono/client' import type { AppType } from './server' const client = hc<AppType>('https://api.spinny.dev') const res = await client.posts[':id'].$get({ param: { id: '42' } }) if (res.ok) { const data = await res.json() console.log(data.title) } const created = await client.posts.$post({ json: { title: 'สวัสดี', body: 'Hono คือเปลวไฟ' }, })
การแยกตามรหัสสถานะ
.get('/posts/:id', (c) => { const post = findPost(c.req.param('id')) if (!post) return c.json({ error: 'not found' }, 404) return c.json({ post }, 200) })
const res = await client.posts[':id'].$get({ param: { id } }) if (res.status === 404) { const { error } = await res.json() } if (res.status === 200) { const { post } = await res.json() }
เราเตอร์และประสิทธิภาพ
| เราเตอร์ | จุดเด่น | ใช้เมื่อใด |
|---|---|---|
RegExpRouter | ความเร็วสูงสุด regex คอมไพล์แล้ว | ค่าเริ่มต้นสำหรับ API ส่วนใหญ่ |
TrieRouter | รองรับทุก pattern | Pattern ซับซ้อนที่ RegExp จัดการไม่ได้ |
SmartRouter | เลือกสิ่งที่ดีที่สุดอัตโนมัติ | ค่าเริ่มต้นที่แนะนำ |
LinearRouter | การลงทะเบียนเร็วสุด | Worker one-shot, cold start สำคัญ |
PatternRouter | Bundle ขั้นต่ำ (<15KB) | ข้อจำกัดขนาดสุดขีด |
import { Hono } from 'hono' import { LinearRouter } from 'hono/router/linear-router' const app = new Hono({ router: new LinearRouter() })
การ deploy หลาย runtime
Cloudflare Workers
import { Hono } from 'hono' type Bindings = { MY_KV: KVNamespace; DB: D1Database } const app = new Hono<{ Bindings: Bindings }>() app.get('/cache/:key', async (c) => { const value = await c.env.MY_KV.get(c.req.param('key')) return c.json({ value }) }) export default app
Deploy: npx wrangler deploy
Bun
import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Bun + Hono')) Bun.serve({ fetch: app.fetch, port: 3000 })
Node.js
import { serve } from '@hono/node-server' import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Node + Hono')) serve({ fetch: app.fetch, port: 3000 })
Deno
import { Hono } from 'jsr:@hono/hono' const app = new Hono() app.get('/', (c) => c.text('Deno + Hono')) Deno.serve(app.fetch)
Vercel
// api/[[...route]].ts import { Hono } from 'hono' import { handle } from 'hono/vercel' const app = new Hono().basePath('/api') app.get('/hello', (c) => c.json({ msg: 'Hello from Vercel' })) export const GET = handle(app) export const POST = handle(app)
ตัวอย่างใช้งานจริง: REST API พร้อม auth และ DB
import { Hono } from 'hono' import { jwt } from 'hono/jwt' import { logger } from 'hono/logger' import { cors } from 'hono/cors' import { zValidator } from '@hono/zod-validator' import { z } from 'zod' type Bindings = { DB: D1Database; JWT_SECRET: string } type Variables = { jwtPayload: { sub: string } } const app = new Hono<{ Bindings: Bindings; Variables: Variables }>() app.use('*', logger()) app.use('/api/*', cors({ origin: 'https://spinny.dev', credentials: true })) const auth = (c: any, next: any) => jwt({ secret: c.env.JWT_SECRET })(c, next) const api = app.basePath('/api') api.get('/posts', async (c) => { const { results } = await c.env.DB .prepare('SELECT id, title, created_at FROM posts ORDER BY created_at DESC LIMIT 50') .all() return c.json({ posts: results }) }) api.post( '/posts', auth, zValidator('json', z.object({ title: z.string().min(1).max(200), body: z.string().min(1), })), async (c) => { const { title, body } = c.req.valid('json') const userId = c.var.jwtPayload.sub const result = await c.env.DB .prepare('INSERT INTO posts (title, body, author_id) VALUES (?, ?, ?) RETURNING id') .bind(title, body, userId) .first<{ id: number }>() return c.json({ id: result?.id }, 201) } ) api.onError((err, c) => { console.error(err) return c.json({ error: 'Internal error' }, 500) }) export type AppType = typeof api export default app
การทดสอบ
import { describe, it, expect } from 'vitest' import app from '../src/index' describe('GET /api/posts', () => { it('คืนค่ารายการโพสต์', async () => { const res = await app.request('/api/posts') expect(res.status).toBe(200) const body = await res.json() expect(body.posts).toBeInstanceOf(Array) }) })
แนวปฏิบัติที่ดีที่สุด
1. ทำ chain การกำหนด route
const app = new Hono() .get('/posts', handler1) .post('/posts', handler2) .get('/posts/:id', handler3)
2. Export type ไม่ใช่ implementation
ไคลเอ็นต์ต้อง import AppType
3. หนึ่ง router ต่อหนึ่ง domain
Sub-app สำหรับ posts, users, webhooks
4. ตรวจสอบที่ขอบ เสมอ
ทุก input ภายนอกต้องผ่าน zValidator
5. พึ่งพา binding ไม่ใช่ client ระดับ global
บน Cloudflare เข้าถึง KV/D1/R2 ผ่าน c.env
6. วัดก่อนปรับแต่ง router
SmartRouter เริ่มต้นเหมาะกับ 95% ของกรณี
บทสรุป
Hono กลายเป็นมาตรฐาน de facto ในปี 2026 สำหรับการสร้าง API ที่พร้อมสำหรับ edge ด้วย TypeScript
เช็คลิสต์เริ่มต้น:
npm create hono@latestและเลือก template runtime ของคุณ- กำหนดเส้นทางด้วย chaining (
.get(...).post(...))- เพิ่ม
logger,cors,secureHeadersเป็นมิดเดิลแวร์ระดับ global- ตรวจสอบทุก input ด้วย
@hono/zod-validator- Export
AppTypeและใช้ API ด้วยไคลเอ็นต์hctype-safe- เขียน test ด้วย
app.request()— ไม่ต้องมี HTTP server- Deploy ด้วย
wrangler deploy(CF),vercel deployหรือ bundler ของ runtime