Hono is a ultra-fast, lightweight web framework designed for edge computing environments like Cloudflare Workers, Fastly Compute, Vercel, and Bun. With zero external dependencies and a footprint under 14KB, it brings the familiar Express-style API to modern, standards-compliant JavaScript runtimes.
This reference sheet covers core server setup, routing mechanics, middleware integration, context manipulation, validation, and deployment steps.
- Routing: Setup static, dynamic, and wildcard routes using standard HTTP methods.
- Context API: Access request headers, search parameters, body payloads, and environment variables through the unified
ccontext object. - Built-in Middleware: Apply CORS, logging, and authentication layers directly out-of-the-box.
- Payload Validation: Validate client inputs securely using the official
@hono/zod-validatorintegration. - Edge Deployment: Bundle and publish applications to Cloudflare Workers with minimal effort.
Before diving into this cheatsheet, check out my previous deep-dive on TypeScript Generics & Advanced Types Cheatsheet: The Complete Reference to see how we structured these patterns in practice.
Setting Up Hono
To create a new Hono project, initialize it using Bun or npm. Below is a base server initialization.
import { Hono } from 'hono';
// Create the main app instance
const app = new Hono();
// Define a basic JSON route
app.get('/', (c) => {
return c.json({ status: 'healthy', timestamp: Date.now() });
});
export default app;
Routing & Param Extraction
Hono features a powerful trie-based router that supports path parameters, wildcards, and regular expressions.
// 1. Path Parameters
app.get('/users/:id', (c) => {
const userId = c.req.param('id');
return c.text(`User ID requested: ${userId}`);
});
// 2. Multiple Path Parameters
app.get('/posts/:year/:month', (c) => {
const { year, month } = c.req.param();
return c.json({ year, month });
});
// 3. Wildcard Routes
app.get('/wildcard/*', (c) => {
const path = c.req.path;
return c.text(`Captured wildcard path: ${path}`);
});
// 4. Grouped Routes (Sub-routing)
const api = new Hono();
api.get('/status', (c) => c.text('API Status: OK'));
app.route('/api/v1', api); // Mounts under /api/v1/status
Utilizing the Context Object
The Context object (c) is passed to every route handler. It consolidates request information and response utilities.
app.post('/submit', async (c) => {
// Extract query parameters
const filter = c.req.query('filter');
// Extract request headers
const userAgent = c.req.header('user-agent');
// Parse JSON payloads securely
const body = await c.req.json();
// Access environment variables (Cloudflare bindings)
const dbUrl = c.env.DATABASE_URL;
// Set response headers and status codes
c.header('X-Custom-Header', 'MeshWorld-Edge');
c.status(201);
return c.json({
received: true,
filter,
userAgent,
payload: body,
});
});
Incorporating Middleware
Hono includes excellent built-in middleware modules that handle typical web application tasks.
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { bearerAuth } from 'hono/bearer-auth';
// Apply logging globally
app.use('*', logger());
// Apply CORS to specific paths
app.use('/api/*', cors({
origin: 'https://meshworld.in',
allowMethods: ['GET', 'POST'],
}));
// Protect private routes with Bearer authentication
const token = 'super-secret-token';
app.use('/admin/*', bearerAuth({ token }));
app.get('/admin/dashboard', (c) => {
return c.text('Welcome to the admin area.');
});
Client Input Validation
Using @hono/zod-validator, you can validate incoming JSON payloads, query parameters, and form data.
import { z } from 'zod';
import { zValidator } from '@hono/zod-validator';
// 1. Define your validation schema
const userSchema = z.object({
username: z.string().min(3).max(20),
email: z.string().email(),
age: z.number().int().positive().optional(),
});
// 2. Apply validator to route
app.post('/register', zValidator('json', userSchema), (c) => {
// The data here is guaranteed to be validated and typed
const validatedData = c.req.valid('json');
return c.json({
success: true,
user: validatedData
});
});
Designing Custom Middleware
You can build custom middleware using standard async/await operations. This is useful for writing custom authentication filters or performance metrics trackers.
// Custom execution-time tracker middleware
app.use('*', async (c, next) => {
const start = Date.now();
// Proceed to the next middleware or handler in the chain
await next();
const duration = Date.now() - start;
console.log(`[Request] ${c.req.method} ${c.req.path} completed in ${duration}ms`);
// Append a response header tracking timing
c.res.headers.append('X-Response-Time', `${duration}ms`);
});
Edge Deployments
Deploying a Hono app to Cloudflare Workers is straightforward using the Wrangler CLI.
1. Configuration (wrangler.toml)
Create a wrangler.toml file in your project root to instruct Wrangler how to bundle and deploy.
name = "hono-edge-api"
main = "src/index.ts"
compatibility_date = "2026-05-01"
[vars]
ENVIRONMENT = "production"
2. Deployment CLI Commands
Execute these commands to manage your local development environment and edge deployments.
# Start a local Wrangler development server simulating Cloudflare Workers
bunx wrangler dev
# Package and publish your application to Cloudflare Edge Network
bunx wrangler deploy Related Articles
Deepen your understanding with these curated continuations.
TypeScript Generics & Advanced Types Cheatsheet: The Complete Reference
Deep dive into advanced TypeScript: generics, conditional types, mapped types, template literal types, and type guards.
React Hooks & Custom Hooks Cheatsheet: The Complete Reference
A complete guide to React Hooks and writing robust custom hooks with optimal rendering performance.
FastAPI & Pydantic v2 Boilerplate Cheatsheet: The Complete Reference
Build high-performance APIs: FastAPI routers, Pydantic v2 models, dependency injection, async database integration, and security.