Hono
Hono is a fast, lightweight web framework for building web applications and APIs in JavaScript and TypeScript. It's optimized for Edge environments like Cloudflare Workers, Deno Deploy, and more.
Core Concepts
-
Minimal and Fast:
Hono is designed for high performance with minimal overhead. -
Routing:
Hono uses an intuitive, declarative routing system.import { Hono } from 'hono';
const app = new Hono();
app.get('/', (c) => c.text('Hello, Hono!'));
export default app; -
Middleware:
Middleware in Hono is used to handle cross-cutting concerns like authentication, logging, etc.app.use('*', async (c, next) => {
console.log('Request received');
await next();
}); -
Response Helpers:
Hono provides simple methods likec.text()
,c.json()
,c.html()
to send responses.
Basic Setup
-
Installation (Node.js):
npm install hono
-
Deno Usage:
import { Hono } from 'https://deno.land/x/hono/mod.ts';
const app = new Hono();
app.get('/', (c) => c.text('Hello from Deno!'));
console.log('Listening on http://localhost:3000');
app.fire(); -
Cloudflare Workers Example:
import { Hono } from 'hono';
const app = new Hono();
app.get('/', (c) => c.text('Running on Cloudflare Workers'));
export default app;
Common Routing Patterns
-
Basic Routes:
app.get('/hello', (c) => c.text('Hello World!'));
-
Dynamic Routes:
app.get('/user/:id', (c) => {
const userId = c.req.param('id');
return c.text(`User ID: ${userId}`);
}); -
Query Parameters:
app.get('/search', (c) => {
const query = c.req.query('q');
return c.text(`Search Query: ${query}`);
}); -
Post Request:
app.post('/submit', async (c) => {
const data = await c.req.json();
return c.json({ message: 'Data received', data });
});
Middleware Examples
-
Global Middleware for Logging:
app.use('*', async (c, next) => {
console.log(`Request: ${c.req.method} ${c.req.url}`);
await next();
}); -
Error Handling Middleware:
app.use('*', async (c, next) => {
try {
await next();
} catch (err) {
return c.json({ error: 'Something went wrong' }, 500);
}
});
Key Methods Cheat Sheet
Method | Description |
---|---|
c.text() | Send plain text response |
c.json() | Send JSON response |
c.html() | Send HTML response |
c.req.param() | Access dynamic route parameters |
c.req.query() | Access query parameters |
c.req.header() | Access request headers |
-
Start Small:
Build a simple API with GET and POST routes to understand the core structure. -
Use Middleware Wisely:
Add logging, CORS, and error-handling middleware for robustness. -
Deploy on Edge:
Deploy to platforms like Cloudflare Workers or Vercel for instant scalability. -
Check Hono Documentation:
Visit the Hono Docs for advanced guides and API references.