Eveken at egy JavaScript web framework valasztasa kompromisszumot jelentett: az Express univerzalis volt, de lassu es Node-hoz kotott, a Fastify gyors, de csak Node, a Next.js teljes erteku, de nehez. Amikor megerkeztek az edge runtime-ok — Cloudflare Workers, Deno Deploy, Bun, Vercel Edge — ezek a frameworkok megmutattak a hatarukat.
A Hono (japanul "lang" 🔥) a modern valasz. Egy 14KB alatti framework, teljes mertekben Web Standardson (Request, Response, fetch) epul, es minden olyan helyen fut, ahol JavaScript runtime van. Ugyanaz a kod deployolhato Cloudflare Workersre, Bunra, Denora, Node.js-re, Vercelra, Netlifyra es AWS Lambdara — valtoztatas nelkul.
Miert Hono
- Teljesitmeny. A
RegExpRouterminden route mintat egyetlen regexbe forditja. A benchmarkok meghaladjak a 400 000 ops/s-ot. - Hordozhatosag. A Web Standards nulla Node fuggoseget jelent.
- TypeScript-first DX. Path parametereket literal tipuskent kovetkezteti ki, end-to-end type-safe RPC kliens.
Kezdes
npm create hono@latest my-api cd my-api npm install npm run dev
// src/index.ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Hono!')) export default app
Cloudflare Workersen ennyi eleg. Bunon: Bun.serve({ fetch: app.fetch, port: 3000 }). Node-on: serve({ fetch: app.fetch }) a @hono/node-server-bol.
Routing
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) })
Routok csoportositasa
// 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)
A Context objektum
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 }) })
Middleware: hagyma modell
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`) })
Beepitett middleware-ek
| Middleware | Cel |
|---|---|
logger | Strukturalt logok metodusrol, utvonalrol, statuszrol, idotartamrol |
cors | Origin, metodusok, headerek szerint konfiguralhato CORS |
csrf | Origin alapu CSRF vedelem |
secureHeaders | Beallitja CSP, HSTS, X-Frame-Options |
bearerAuth / basicAuth | Keszen hasznalhato Bearer/Basic auth |
jwt | JWT verify/sign jose-val |
etag | ETag generalas es 304 kezeles |
cache | Cache a Web Cache API-n keresztul |
compress | gzip/deflate a valaszon |
bodyLimit | Visszautasitja a kuszob feletti body-kat |
timing | Server-Timing header profilingehoz |
Type-safe egyedi middleware
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 }) })
Validacio Zoddal
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: end-to-end type-safe kliens
// 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: 'Szia', body: 'A Hono egy lang' }, })
Status kod megkulonboztetes
.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() }
Routerek es teljesitmeny
| Router | Erossegek | Mikor hasznalja |
|---|---|---|
RegExpRouter | Maximalis sebesseg, fordított regex | Default a legtobb API-hoz |
TrieRouter | Minden mintat tamogat | Komplex mintak, amiket a RegExp nem kezel |
SmartRouter | Automatikusan a legjobbat valasztja | Ajanlott default |
LinearRouter | Ultragyors regisztracio | One-shot workerek, kritikus cold start |
PatternRouter | Minimalis bundle (<15KB) | Extrem meretkorlatozasok |
import { Hono } from 'hono' import { LinearRouter } from 'hono/router/linear-router' const app = new Hono({ router: new LinearRouter() })
Multi-runtime deploy
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)
Gyakorlati pelda: REST API auth-tel es DB-vel
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
Tesztelés
import { describe, it, expect } from 'vitest' import app from '../src/index' describe('GET /api/posts', () => { it('visszaadja a posztok listajat', async () => { const res = await app.request('/api/posts') expect(res.status).toBe(200) const body = await res.json() expect(body.posts).toBeInstanceOf(Array) }) })
Legjobb gyakorlatok
1. Lancold a route definiciokat
const app = new Hono() .get('/posts', handler1) .post('/posts', handler2) .get('/posts/:id', handler3)
2. Exportald a tipust, ne az implementaciot
A kliensnek AppType-ot kell importalnia.
3. Egy router domain-enkent
Sub-app posts, users, webhooks szamara.
4. Validacio a hataron, mindig
Minden kulso bemenetnek at kell mennie a zValidator-on.
5. Tamaszkodj a bindingsre, ne a globalis kliensekre
Cloudflare-en ferj hozza KV/D1/R2-hoz c.env-en keresztul.
6. Mérj, mielott optimalizalod a routert
A default SmartRouter az esetek 95%-ban megfelel.
Konkluzio
A Hono 2026-ban de facto standardda valt edge-ready API-k epitesehez TypeScriptben.
Indulasi checklist:
npm create hono@latestes valaszd a runtime sablont- Definialj routokat lancolassal (
.get(...).post(...))- Add hozza
logger,cors,secureHeaders-t globalis middleware-kent- Validalj minden bemenetet a
@hono/zod-validator-ral- Exportald
AppType-ot es hasznald az API-t a type-safehcklienssel- Irj teszteket
app.request()-tel — HTTP szerver nelkul- Deployolj
wrangler deploy-jal (CF),vercel deploy-jal vagy a runtime bundlerével