¿Qué es Hono?
Hono es un framework web ultraligero y rápido que funciona en múltiples runtimes como Cloudflare Workers, Deno, Bun y Node.js. Se caracteriza por una API similar a Express y un excelente soporte de TypeScript.
Nuevas funciones de Hono 4
Mejoras en hono/jsx
import { Hono } from 'hono';
import { FC } from 'hono/jsx';
const Layout: FC = (props) => {
return (
<html>
<head>
<title>{props.title}</title>
</head>
<body>{props.children}</body>
</html>
);
};
const app = new Hono();
app.get('/', (c) => {
return c.html(
<Layout title="Home">
<h1>Welcome to Hono!</h1>
</Layout>
);
});
Streaming de JSX
import { Suspense } from 'hono/jsx';
import { renderToReadableStream } from 'hono/jsx/streaming';
const AsyncComponent: FC = async () => {
const data = await fetchData();
return <div>{data}</div>;
};
app.get('/stream', (c) => {
const stream = renderToReadableStream(
<Layout>
<Suspense fallback={<div>Loading...</div>}>
<AsyncComponent />
</Suspense>
</Layout>
);
return c.body(stream, {
headers: { 'Content-Type': 'text/html' }
});
});
Funcionalidad RPC
Permite comunicación tipo-segura entre cliente y servidor.
Lado del servidor
import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
const app = new Hono()
.get('/users', async (c) => {
const users = await db.users.findMany();
return c.json(users);
})
.post(
'/users',
zValidator('json', z.object({
name: z.string(),
email: z.string().email()
})),
async (c) => {
const data = c.req.valid('json');
const user = await db.users.create(data);
return c.json(user, 201);
}
)
.get('/users/:id', async (c) => {
const id = c.req.param('id');
const user = await db.users.findById(id);
return c.json(user);
});
export type AppType = typeof app;
export default app;
Lado del cliente
import { hc } from 'hono/client';
import type { AppType } from './server';
const client = hc<AppType>('http://localhost:3000');
// ¡Inferencia de tipos completa!
const users = await client.users.$get();
const usersData = await users.json(); // tipo User[]
const newUser = await client.users.$post({
json: { name: 'Alice', email: 'alice@example.com' }
});
const user = await client.users[':id'].$get({
param: { id: '123' }
});
Middleware
Middleware incorporado
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { secureHeaders } from 'hono/secure-headers';
import { compress } from 'hono/compress';
import { cache } from 'hono/cache';
const app = new Hono();
app.use('*', logger());
app.use('*', cors());
app.use('*', secureHeaders());
app.use('*', compress());
app.use('/api/*', cache({ cacheName: 'api-cache', cacheControl: 'max-age=60' }));
Middleware de autenticación
import { jwt } from 'hono/jwt';
import { bearerAuth } from 'hono/bearer-auth';
// Autenticación JWT
app.use('/api/*', jwt({
secret: 'your-secret-key'
}));
app.get('/api/protected', (c) => {
const payload = c.get('jwtPayload');
return c.json({ userId: payload.sub });
});
// Autenticación Bearer
app.use('/admin/*', bearerAuth({
token: 'admin-token'
}));
Validación
Integración con Zod
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
const createUserSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().positive().optional()
});
app.post(
'/users',
zValidator('json', createUserSchema),
async (c) => {
const data = c.req.valid('json');
// data tiene tipo seguro
return c.json({ message: 'Created', user: data });
}
);
Soporte multi-runtime
// Cloudflare Workers
export default app;
// Deno
Deno.serve(app.fetch);
// Bun
export default {
port: 3000,
fetch: app.fetch
};
// Node.js
import { serve } from '@hono/node-server';
serve(app);
Benchmark
Solicitudes/segundo (respuesta JSON simple):
- Express: 15,000
- Fastify: 45,000
- Hono (Bun): 120,000
- Hono (Cloudflare Workers): 100,000+
Enrutamiento basado en archivos
// routes/users.ts
import { Hono } from 'hono';
const users = new Hono();
users.get('/', (c) => c.json([]));
users.get('/:id', (c) => c.json({ id: c.req.param('id') }));
export default users;
// index.ts
import { Hono } from 'hono';
import users from './routes/users';
const app = new Hono();
app.route('/users', users);
export default app;
Resumen
Hono 4 es un framework óptimo para el desarrollo de aplicaciones web modernas con su diseño TypeScript-first y soporte multi-runtime. La funcionalidad RPC para clientes API tipo-seguros ofrece mejoras significativas de productividad, especialmente en desarrollo full-stack.
← Volver a la lista