Hono Web Framework
website·Indexed 32 days ago
https://hono.zhcndoc.comA small, simple, and ultra-fast web framework built on Web standards. Hono is compatible with any JavaScript runtime, including Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Netlify, and AWS Lambda. It features a comprehensive suite of built-in middleware (such as JWT, CORS, and Basic Auth) and helper utilities for HTML, CSS, and streaming.
What's inside Hono
- Google Cloud Run is a serverless platform by Google Cloud that runs services using containers. It automatically manages underlying compute resources. You can use any runtime (such as Deno, Bun, or Node.js) by providing a Dockerfile; otherwise, Google Cloud Run defaults to a Node.js build pack.
Overview of Hono Client Components (hono/jsx/dom)
Hono provideshono/jsx/dom, a lightweight JSX runtime for creating interactive UIs that run directly in the browser. It is designed to be significantly smaller than React (e.g., a counter example is ~2.8KB Brotli compressed compared to React's ~47.8KB).Overview of Hono's design philosophy
Hono is a lightweight, ultra-fast web framework designed to be 'the standard of Web standards.' It is built using Web Standard APIs, allowing it to run across multiple environments including Cloudflare Workers, Deno, Bun, and Node.js (via an adapter). Its core architecture leverages a high-performance router (inspired by Trie trees and RegExpRouter) to ensure speed and versatility across the edge and server-side ecosystems.Overview of Hono Developer Experience
Hono is written in TypeScript and provides type safety for applications. It allows developers to write applications for Cloudflare Workers, Deno, and Bun using TypeScript without the need to transpile the code into JavaScript.Overview of Hono Web Framework
Hono is a small, simple, and ultra-fast web framework built on Web standards. It is designed to be runtime-agnostic, meaning the same code can run across various JavaScript environments including Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Netlify, AWS Lambda, Lambda@Edge, and Node.js. It is characterized by its lightweight footprint (under 14kB with thehono/tinypreset) and zero dependencies.Enable RPC type safety in large applications
To use Hono's RPC features with a split-file architecture, use method chaining when defining the sub-app and export theAppType. This ensures thehc(Hono Client) can correctly infer the API types.// authors.ts import { Hono } from 'hono' const app = new Hono() .get('/', (c) => c.json('List authors')) .get('/:id', (c) => c.json(`Author ${c.req.param('id')}`)) export default app export type AppType = typeof app // client.ts import type { AppType } from './authors' import { hc } from 'hono/client' const client = hc<AppType>('http://localhost') // Fully typedImplement Hono RPC for type-safe API communication
Hono RPC allows sharing API specifications between a server and a client by exporting the server's application type (
AppType). The Hono Client (hc) uses this type to provide full TypeScript inference for request inputs (validators) and response outputs (c.json()).Critical Requirement: For RPC types to work correctly in a monorepo, both the client and server
tsconfig.jsonfiles must have"strict": trueset incompilerOptions.Prevent CSRF attacks using Hono CSRF middleware
The
csrfmiddleware protects against CSRF attacks by verifying theOriginandSec-Fetch-Siteheaders. A request is allowed if either validation passes.To optimize performance and avoid false positives, the middleware only validates requests that meet both of these criteria:
- Use an unsafe HTTP method (anything other than GET, HEAD, or OPTIONS).
- Have a content type that can be sent via HTML forms (
application/x-www-form-urlencoded,multipart/form-data, ortext/plain).
Caveat: This middleware may not work in environments where the
Originheader is stripped by reverse proxies or in very old browsers. In such cases, use a CSRF token-based approach.import { Hono } from 'hono' import { csrf } from 'hono/csrf' const app = new Hono() // Enable default CSRF protection app.use(csrf())Run Hono on Azure Functions V4
Hono can be deployed to Azure Functions V4 (Node.js 18+) using the@marplex/hono-azurefunc-adapter. This allows Hono to handle HTTP requests within the Azure serverless environment.Understand the Hono Context object
TheContextobject is instantiated for every request and persists until the response is returned. It provides a unified interface to access theHonoRequestandResponseobjects, set HTTP status codes and headers, and store request-scoped variables.Understand Hono's compatibility with Web Standards
Hono is built exclusively using Web Standards, primarily those associated with thefetchfunction. This includes core objects for handling HTTP requests and responses such asRequest,Response,URL,URLSearchParams, andHeaders. Because it adheres to these standards, Hono code is highly portable across different JavaScript runtimes and environments.Understand Hono's routing options and performance
Hono provides five different router implementations to balance speed, feature support, and bundle size. By default, Hono uses a
SmartRouterthat combinesRegExpRouterandTrieRouterto automatically select the fastest option based on the registered routes.- RegExpRouter: The fastest for matching. It compiles routes into a single large regular expression to avoid linear loops. However, it does not support all routing patterns.
- TrieRouter: Uses a Trie tree algorithm. It is slower than RegExpRouter but faster than Express and supports all routing patterns.
- SmartRouter: A wrapper that infers the best router to use from the registered routes. It typically manages a set of routers (e.g., RegExpRouter and TrieRouter).
- LinearRouter: Optimized for 'one-off' environments where the router is initialized on every request. It has much faster registration times because it avoids string compilation.
- PatternRouter: The smallest implementation, designed for resource-constrained environments. Applications using only PatternRouter can be under 15KB.