Ani la rând, alegerea unui framework web JavaScript însemna acceptarea unui compromis: Express era universal dar lent și legat de Node, Fastify era rapid dar doar Node, Next.js era complet dar greu. Când au apărut runtime-urile edge — Cloudflare Workers, Deno Deploy, Bun, Vercel Edge — acele framework-uri și-au arătat limitele.
Hono (japoneză pentru "flacără" 🔥) este răspunsul modern. Un framework sub 14KB, construit complet pe Web Standards (Request, Response, fetch), care rulează oriunde există un runtime JavaScript. Același cod se deploy-uiește pe Cloudflare Workers, Bun, Deno, Node.js, Vercel, Netlify și AWS Lambda — fără modificări.
De ce Hono
- Performanță.
RegExpRoutercompilează toate pattern-urile de rute într-un singur regex. Benchmark-urile depășesc 400.000 ops/s. - Portabilitate. Web Standards înseamnă zero dependențe de Node.
- DX TypeScript-first. Parametrii de cale inferați ca literal types, client RPC type-safe end-to-end.
Inceput
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
Pe Cloudflare Workers atat e suficient. Pe Bun: Bun.serve({ fetch: app.fetch, port: 3000 }). Pe Node: serve({ fetch: app.fetch }) din @hono/node-server.
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) })
Gruparea rutelor
// 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)
Obiectul 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 }) })
Middleware: modelul ceapa
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`) })
Middleware integrate
| Middleware | Rol |
|---|---|
logger | Logs structurate pentru metoda, cale, status, durata |
cors | CORS configurabil pe origin, metode, headere |
csrf | Protectie CSRF bazata pe origin |
secureHeaders | Seteaza CSP, HSTS, X-Frame-Options |
bearerAuth / basicAuth | Auth Bearer/Basic gata de folosit |
jwt | Verifica/semneaza JWT cu jose |
etag | Genereaza ETag si gestioneaza 304 |
cache | Cache prin Web Cache API |
compress | gzip/deflate pe raspuns |
bodyLimit | Respinge body-uri peste prag |
timing | Header Server-Timing pentru profiling |
Middleware custom 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 }) })
Validare cu 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: client 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: 'Salut', body: 'Hono este o flacara' }, })
Discriminarea pe cod de status
.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() }
Routere si performanta
| Router | Puncte forte | Cand sa folosesti |
|---|---|---|
RegExpRouter | Viteza maxima, regex compilat | Default pentru majoritatea API-urilor |
TrieRouter | Suporta toate pattern-urile | Pattern-uri complexe pe care RegExp nu le acopera |
SmartRouter | Alege automat cel mai bun | Default recomandat |
LinearRouter | Inregistrare ultrarapida | Workeri one-shot, cold start critic |
PatternRouter | Bundle minim (<15KB) | Restrictii extreme de marime |
import { Hono } from 'hono' import { LinearRouter } from 'hono/router/linear-router' const app = new Hono({ router: new LinearRouter() })
Deploy multi-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)
Exemplu practic: REST API cu auth si 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
Testare
import { describe, it, expect } from 'vitest' import app from '../src/index' describe('GET /api/posts', () => { it('returneaza lista de posts', async () => { const res = await app.request('/api/posts') expect(res.status).toBe(200) const body = await res.json() expect(body.posts).toBeInstanceOf(Array) }) })
Bune practici
1. Inlantuie definitiile de rute
const app = new Hono() .get('/posts', handler1) .post('/posts', handler2) .get('/posts/:id', handler3)
2. Exporta tipul, nu implementarea
Clientul trebuie sa importe AppType.
3. Un router pe domeniu
Sub-app pentru posts, users, webhooks.
4. Validare la margine, mereu
Fiecare input extern trebuie sa treaca prin zValidator.
5. Bazeaza-te pe bindings, nu pe clienti globali
Pe Cloudflare, acceseaza KV/D1/R2 prin c.env.
6. Masoara inainte sa optimizezi router-ul
Default-ul SmartRouter se potriveste in 95% din cazuri.
Concluzie
Hono a devenit in 2026 standardul de facto pentru construirea de API-uri pregatite pentru edge in TypeScript.
Checklist de start:
npm create hono@latestsi alege template-ul runtime-ului tau- Defineste rutele cu inlantuire (
.get(...).post(...))- Adauga
logger,cors,secureHeadersca middleware globale- Valideaza fiecare input cu
@hono/zod-validator- Exporta
AppTypesi consuma API-ul cu clientulhctype-safe- Scrie teste cu
app.request()— fara server HTTP- Deploy cu
wrangler deploy(CF),vercel deploysau bundler-ul runtime-ului tau