Bun + Hono: stack edge minimal
Costruire API edge ultra-leggere combina Bun (runtime JavaScript moderno e velocissimo) con Hono (framework web minimalista). Questo stack elimina l'overhead tradizionale dei framework Node.js, offrendo latenza sub-millisecondale e bundle ridotti. Scopri come deployare un'API REST completa con autenticazione, database e cache in meno di 50KB di codice compilato.
Perché Bun per le edge
Bun è un runtime JavaScript costruito da zero con performance come priorità principale. A differenza di Node.js (basato su V8 isolato), Bun usa JavaScriptCore (il motore Safari), riducendo il footprint di memoria e aumentando la velocità di esecuzione fino a 3 volte su operazioni I/O. Il binario standalone Bun pesa circa 65MB (vs 50-100MB di Node.js), ma una volta caricato in memoria, rimane più efficiente.
Per le edge function (FaaS su Cloudflare Workers, Vercel Edge, AWS Lambda@Edge), questo significa:
- Cold start < 50ms (vs 500-1000ms con Node.js)
- Consumo memoria < 30MB per funzione attiva
- Bundle totale < 10MB dopo tree-shake
- Native TypeScript: zero compilazione, esecuzione diretta
Hono: il framework invisibile
Hono è un web framework ultraleggero (~15KB gzipped) progettato specificamente per ambienti edge. Non ha dipendenze pesanti: niente Express, niente middleware chain complessa, solo il routing e la gestione HTTP di cui hai realmente bisogno.
Le caratteristiche chiave di Hono:
- Tiny footprint: 15KB per il core + middleware opzionali
- Adapter universale: supporta Bun, Cloudflare Workers, Vercel Edge, AWS Lambda, Node.js
- Type-safe routing: middleware e handler con type hint completi
- Zero runtime overhead: build-time routing, nessuna magic string
Setup iniziale
Installa Bun da https://bun.sh. Su macOS/Linux:
curl -fsSL https://bun.sh/install | bash
Crea un nuovo progetto Hono su Bun:
bun create hono my-edge-api
cd my-edge-api
bun install
Il file `src/index.ts` contiene:
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hello Bun!'))
export default app
Esegui in development:
bun run src/index.ts
Il server avvia su http://localhost:3000 in ~20ms.
Creare un'API REST minimale
Costruisci un'API per gestire articoli di blog con CRUD completo:
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
const app = new Hono()
// Middleware
app.use('*', logger())
app.use('*', cors())
// In-memory store (in produzione: database)
const articles: Record<string, any> = {}
let nextId = 1
// GET /articles
app.get('/articles', (c) => {
return c.json(Object.values(articles))
})
// POST /articles
app.post('/articles', async (c) => {
const body = await c.req.json()
const id = String(nextId++)
articles[id] = { id, ...body, createdAt: new Date() }
return c.json(articles[id], 201)
})
// GET /articles/:id
app.get('/articles/:id', (c) => {
const id = c.req.param('id')
if (!articles[id]) return c.notFound()
return c.json(articles[id])
})
// PUT /articles/:id
app.put('/articles/:id', async (c) => {
const id = c.req.param('id')
if (!articles[id]) return c.notFound()
const body = await c.req.json()
articles[id] = { ...articles[id], ...body }
return c.json(articles[id])
})
// DELETE /articles/:id
app.delete('/articles/:id', (c) => {
const id = c.req.param('id')
if (!articles[id]) return c.notFound()
delete articles[id]
return c.text('', 204)
})
export default app
Aggiungere autenticazione JWT
Usa il middleware `jwt` di Hono per proteggere le rotte:
import { jwt } from 'hono/jwt'
const secret = Bun.env.JWT_SECRET || 'dev-secret-key'
app.use('/api/*', jwt({ secret }))
// Rotta pubblica (bypassa JWT)
app.post('/auth/login', async (c) => {
const { email, password } = await c.req.json()
// Valida credenziali (semplificato)
if (email === 'admin@example.com' && password === 'password') {
const token = await signJWT({ email, sub: 'admin' }, secret)
return c.json({ token })
}
return c.json({ error: 'Invalid credentials' }, 401)
})
// Rotta protetta
app.get('/api/profile', (c) => {
const payload = c.get('jwtPayload')
return c.json({ profile: payload })
})
Integrazione database e cache
Bun ha driver nativi per PostgreSQL e SQLite. Usa SQLite per edge per semplicità:
import { Database } from 'bun:sqlite'
const db = new Database(':memory:')
// Schema
db.exec(`
CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP
)
`)
// Query helper
const getArticles = () => db.prepare('SELECT * FROM articles').all()
const createArticle = (title: string, content: string) => {
db.prepare('INSERT INTO articles (title, content) VALUES (?, ?)').run(title, content)
}
// Endpoint
app.get('/api/articles', (c) => c.json(getArticles()))
app.post('/api/articles', async (c) => {
const { title, content } = await c.req.json()
createArticle(title, content)
return c.json({ success: true }, 201)
})
Per la cache, Bun supporta nativamenteMemcached e Redis. Usa le variabili d'ambiente per i secret:
const REDIS_URL = Bun.env.REDIS_URL || 'redis://localhost:6379'
// Cache wrapper
async function cachedGet(key: string, fetcher: () => Promise<any>, ttl = 3600) {
// Implementa cache logic con Redis
const cached = await redis.get(key)
if (cached) return JSON.parse(cached)
const fresh = await fetcher()
await redis.set(key, JSON.stringify(fresh), 'EX', ttl)
return fresh
}
Deployment su edge
Bun + Hono deployano ovunque. Per Cloudflare Workers:
npm install -D wrangler
wrangler init
Nel `wrangler.toml`:
name = "my-edge-api"
type = "javascript"
main = "src/index.ts"
compatibility_date = "2024-01-01"
[env.production]
vars = { JWT_SECRET = "prod-secret" }
[[r2_buckets]]
binding = "BUCKET"
bucket_name = "my-bucket"
Deploy:
wrangler deploy
La tua API è live su `https://my-edge-api.yourname.workers.dev` in 5 secondi.
Performance e benchmarking
Bun ha un built-in test runner per benchmark. Crea `perf.test.ts`:
import { bench } from 'bun:test'
bench('GET /articles', async () => {
await fetch('http://localhost:3000/articles')
})
bench('POST /articles', async () => {
await fetch('http://localhost:3000/articles', {
method: 'POST',
body: JSON.stringify({ title: 'Test' })
})
})
bench('JWT validation', async () => {
await signJWT({ sub: 'user-1' }, 'secret')
})
Esegui:
bun test --run perf.test.ts
Su una macchina moderna:
- GET request: 0.2ms
- POST con JSON parse: 0.5ms
- JWT signing: 0.8ms
Best practice e pattern
1. Gestione errori centralizzata
app.onError((err, c) => {
console.error(err)
return c.json(
{ error: 'Internal Server Error', message: err.message },
500
)
})
2. Validazione input con schema
import { z } from 'zod'
const ArticleSchema = z.object({
title: z.string().min(5).max(200),
content: z.string().min(10)
})
app.post('/api/articles', async (c) => {
const body = await c.req.json()
const parsed = ArticleSchema.safeParse(body)
if (!parsed.success) {
return c.json({ error: parsed.error.flatten() }, 400)
}
// Procedi con dati validati
})
3. Logging strutturato
app.use('*', async (c, next) => {
const start = Date.now()
await next()
const duration = Date.now() - start
console.log({
method: c.req.method,
path: c.req.path,
status: c.res.status,
duration_ms: duration
})
})
Troubleshooting comune
Problema: "Module not found"
Bun è rigoroso sui path. Usa sempre estensioni `.ts` e path relativi espliciti:
// Sbagliato
import { db } from './database'
// Corretto
import { db } from './database.ts'
Problema: Cold start lento
Se il bundle è > 10MB, usa tree-shaking. Nel `bunfig.toml`:
[loader]
extensions = [".ts", ".tsx"]
[define]
"process.env.NODE_ENV" = "\"production\""
Problema: Type hints mancanti in editor
Assicurati che `tsconfig.json` punti a Bun:
{
"compilerOptions": {
"lib": ["ES2020"],
"types": ["bun-types"]
}
}
Installa:
bun add -d bun-types
FAQ
D: Bun è pronto per la produzione?
R: Sì, dal 2024. Usa Bun 1.0+ per stabilità garantita. Evita librerie con dipendenze native scarse (es. imaging) finché non hanno binding Bun nativi.
D: Hono funziona su Node.js?
R: Sì. Hono è un adapter universale. Puoi eseguirlo su Node.js, Bun, Deno, Cloudflare Workers, tutti con lo stesso codice.
D: Come gestire le sessioni su edge?
R: Edge ha zero state persistente. Usa JWT (token nel client), non sessioni server. Se serve uno stato condiviso, usa una KV store (Cloudflare KV, Vercel KV).
D: Qual è il limite di dimensione per una edge function?
R: Cloudflare Workers: 1MB (50MB non compresso). Con Bun + Hono compresso: ~100-200KB per un'API ricca.
D: Posso usare Ollama in una edge function?
R: No, le edge function non possono raggiungere reti locali. Usa Ollama solo su backend tradizionale. Dalle edge, fai fetch HTTP a un Ollama esposto via tunnel (ngrok, CloudFlare Tunnel).
Conclusioni
Bun + Hono è il combo ideale per chi vuole costruire API moderne senza i compromessi di framework legacy. La latenza microscopica, il bundle piccolo e la developer experience nativa di TypeScript lo rendono perfetto per microservizi edge, BFF e serverless. Inizia small — un CRUD di 50 righe su Bun è più veloce e leggero di una API Node.js tradizionale di 500 righe.
Prossimo step: integra Bun + Hono nel tuo workflow di deployment e misura i guadagni di performance. 🚀

Commenti
Caricamento commenti...
Accedi per commentare