Skip to main content

Frameworks and Hono

While standard fetch(request) event handlers are sufficient for simple middleware and proxies, managing dozens of HTTP routes, GET/POST methods, and URL parameters manually using if/else statements becomes unmaintainable quickly.

Learning Focus

By the end of this module, you will understand why Express.js doesn't work on Workers, and how to structure robust APIs using Hono — the gold standard web framework for the edge.


The Node.js Framework Problem

If you come from the Node.js ecosystem, your instinct for building an API is to run npm install express.

This will fail on Cloudflare Workers.

Express.js, Koa, and NestJS are heavily reliant on native Node.js APIs (fs module, standard HTTP Node streams, etc.). Because Workers run in a V8 Isolate, not a Node.js process, these frameworks crash or cannot execute efficiently. Additionally, Express is quite "heavy," bloating the script size of a Worker which must load into memory within milliseconds.

To build APIs at the edge, you need frameworks designed explicitly for the standard Web Fetch API.


The Solution: Hono

Hono (Japanese for "flame") is an ultrafast web framework explicitly designed for Cloudflare Workers, Deno, and standard Web APIs. Structurally, it is heavily inspired by Express.js, making the learning curve very small for backend developers.

It provides:

  • Clean routing (app.get, app.post)
  • URL parameter parsing (/users/:id)
  • Built-in middleware (CORS, JWT authentication, Logger)
  • 0 dependencies and a tiny footprint.

Installing Hono

npm install hono

Writing a Hono Worker

Here is a complete Cloudflare Worker API written in Hono:

src/index.ts
import { Hono } from 'hono';

// Define Cloudflare Bindings for Type Safety
type Bindings = {
MY_DB: D1Database;
API_SECRET: string;
};

// Initialize the app and pass in the Bindings interface format
const app = new Hono<{ Bindings: Bindings }>();

// 1. Basic Route
app.get('/api/ping', (c) => {
// 'c' is the Context object containing the request, response helpers, and env
return c.text('pong!');
});

// 2. URL Parameters
app.get('/api/users/:id', (c) => {
const userId = c.req.param('id');
return c.json({ user: userId });
});

// 3. Reading POST Body JSON
app.post('/api/submit', async (c) => {
const body = await c.req.json();
return c.json({ received: body.name }, 201); // 201 Created status
});

// 4. Accessing Cloudflare Bindings (env vars)
app.get('/api/secure', async (c) => {
// Access env vars off the Context object (c.env)
const secret = c.env.API_SECRET;
return c.text(`Secret is safe!`);
});

// Crucial: Export the app's fetch method to Cloudflare's runtime
export default app;

Hono Middleware

Hono's true power lies in its built-in middleware, eliminating the need to write custom interceptors.

import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';

const app = new Hono();

// Add logger to all routes
app.use('*', logger());

// Apply aggressive CORS to /api/* routes
app.use('/api/*', cors({
origin: ['https://mydomain.com', 'http://localhost:3000'],
allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
allowMethods: ['POST', 'GET', 'OPTIONS'],
}));

app.get('/api/data', (c) => c.json({ data: "secured data" }));

export default app;

Alternative: Itty Router

If Hono still feels "too heavy" (which is rare), the alternative is Itty Router. It is astronomically small (less than 1kb) but strips away most of the safety and built-in middleware that Hono provides.

npm install itty-router
src/index.ts
import { Router } from 'itty-router';

// Create a new router
const router = Router();

router.get('/api/hello', () => new Response('Hello!'));

router.get('/api/users/:id', ({ params }) => {
return new Response(`User ${params.id}`);
});

// Fallback for 404
router.all('*', () => new Response('Not Found.', { status: 404 }));

export default {
// Pass the request to the router
fetch: (request, env, ctx) => router.handle(request, env, ctx).then(Response.json)
};
Hono vs Itty

In 2024, Hono is the undisputed standard for Cloudflare Workers. It has official support from Cloudflare Developer Advocates and integrates heavily with modern RPC and JSX rendering features. Start with Hono.


What's Next

Your API is now robustly routed. Let's look at how to ensure your endpoints return data as fast as physically possible across the globe.

Continue to Module 8: Caching and Performance.