This is the tiny developer documentation for Hono. # Start of Hono documentation # Hono Hono - 在日语中是火焰🔥的意思 - 是一个基于 Web 标准构建的小型、简单且超快的 Web 框架。它适用于任何 JavaScript 运行时:Cloudflare Workers、Fastly Compute、Deno、Bun、Vercel、Netlify、AWS Lambda、Lambda@Edge 和 Node.js。 ¥Hono - ***means flame🔥 in Japanese*** - is a small, simple, and ultrafast web framework built on Web Standards. It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Netlify, AWS Lambda, Lambda@Edge, and Node.js. 快速,但不仅仅是快速。 ¥Fast, but not only fast. ```ts twoslash import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hono!')) export default app ``` ## 快速入门 ¥Quick Start 只需运行这个: ¥Just run this: ::: code-group ```sh [npm] npm create hono@latest ``` ```sh [yarn] yarn create hono ``` ```sh [pnpm] pnpm create hono@latest ``` ```sh [bun] bun create hono@latest ``` ```sh [deno] deno init --npm hono@latest ``` ::: ## 功能 ¥Features * 超快 🚀 - 路由 `RegExpRouter` 非常快。不使用线性循环。快速。 ¥**Ultrafast** 🚀 - The router `RegExpRouter` is really fast. Not using linear loops. Fast. * 轻量级 🪶 - `hono/tiny` 预设小于 14kB。Hono 没有任何依赖,仅使用 Web 标准。 ¥**Lightweight** 🪶 - The `hono/tiny` preset is under 14kB. Hono has zero dependencies and uses only the Web Standards. * 多运行时 🌍 - 适用于 Cloudflare Workers、Fastly Compute、Deno、Bun、AWS Lambda 或 Node.js。相同的代码在所有平台上运行。 ¥**Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute, Deno, Bun, AWS Lambda, or Node.js. The same code runs on all platforms. * 包含适配 🔋 - Hono 具有内置中间件、自定义中间件、第三方中间件和助手。包含适配。 ¥**Batteries Included** 🔋 - Hono has built-in middleware, custom middleware, third-party middleware, and helpers. Batteries included. * Delightful DX 😃 - 超级干净的 API。一流的 TypeScript 支持。现在,我们得到了 "类型"。 ¥**Delightful DX** 😃 - Super clean APIs. First-class TypeScript support. Now, we've got "Types". ## 用例 ¥Use-cases Hono 是一个类似于 Express 的简单 Web 应用框架,没有前端。但它在 CDN Edges 上运行,并允许你与中间件结合使用时构建更大的应用。以下是一些用例示例。 ¥Hono is a simple web application framework similar to Express, without a frontend. But it runs on CDN Edges and allows you to construct larger applications when combined with middleware. Here are some examples of use-cases. * 构建 Web API ¥Building Web APIs * 后端服务器的代理 ¥Proxy of backend servers * CDN 前端 ¥Front of CDN * Edge 应用 ¥Edge application * 库的基本服务器 ¥Base server for a library * 全栈应用 ¥Full-stack application ## 谁在使用 Hono? ¥Who is using Hono? | 项目 | 平台 | 用于什么? | | ---------------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------- | | [cdnjs](https://cdnjs.com) | Cloudflare Workers | 免费开源 CDN 服务。Hono 用于 API 服务器。 | | [Cloudflare D1](https://www.cloudflare.com/developer-platform/d1/) | Cloudflare Workers | 无服务器 SQL 数据库。Hono 用于内部 API 服务器。 | | [Cloudflare Workers KV](https://www.cloudflare.com/developer-platform/workers-kv/) | Cloudflare Workers | 无服务器键值数据库。Hono 用于内部 API 服务器。 | | [BaseAI](https://baseai.dev) | 本地 AI 服务器 | 带内存的无服务器 AI 代理管道。一个用于 Web 的开源代理 AI 框架。带有 Hono 的 API 服务器。 | | [Unkey](https://unkey.dev) | Cloudflare Workers | 一个开源 API 身份验证和授权。Hono 用于 API 服务器。 | | [OpenStatus](https://openstatus.dev) | Bun | 一个开源网站和 API 监控平台。Hono 用于 API 服务器。 | | [Deno 基准测试](https://deno.com/benchmarks) | Deno | 基于 V8 构建的安全 TypeScript 运行时。Hono 用于基准测试。 | 以及以下内容。 ¥And the following. * [Drivly](https://driv.ly/) - Cloudflare Workers * [repeat.dev](https://repeat.dev/) - Cloudflare Workers 你想看更多吗?参见 [谁在生产中使用 Hono?](https://github.com/orgs/honojs/discussions/1510)。 ¥Do you want to see more? See [Who is using Hono in production?](https://github.com/orgs/honojs/discussions/1510). ## 1 分钟内掌握 Hono ¥Hono in 1 minute 使用 Hono 为 Cloudflare Workers 创建应用的演示。 ¥A demonstration to create an application for Cloudflare Workers with Hono. ![Demo](/images/sc.gif) ## 超快 ¥Ultrafast 与 Cloudflare Workers 的其他路由相比,Hono 是最快的。 ¥**Hono is the fastest**, compared to other routers for Cloudflare Workers. ``` Hono x 402,820 ops/sec ±4.78% (80 runs sampled) itty-router x 212,598 ops/sec ±3.11% (87 runs sampled) sunder x 297,036 ops/sec ±4.76% (77 runs sampled) worktop x 197,345 ops/sec ±2.40% (88 runs sampled) Fastest is Hono ✨ Done in 28.06s. ``` 参见 [更多基准](/docs/concepts/benchmarks)。 ¥See [more benchmarks](/docs/concepts/benchmarks). ## 轻量级 ¥Lightweight Hono 很小。使用 `hono/tiny` 预设,其大小在最小化时低于 14KB。有许多中间件和适配器,但它们仅在使用时打包在一起。有关上下文,Express 的大小为 572KB。 ¥**Hono is so small**. With the `hono/tiny` preset, its size is **under 14KB** when minified. There are many middleware and adapters, but they are bundled only when used. For context, the size of Express is 572KB. ``` $ npx wrangler dev --minify ./src/index.ts ⛅️ wrangler 2.20.0 -------------------- ⬣ Listening at http://0.0.0.0:8787 - http://127.0.0.1:8787 - http://192.168.128.165:8787 Total Upload: 11.47 KiB / gzip: 4.34 KiB ``` ## 多个路由 ¥Multiple routers Hono 有多个路由。 ¥**Hono has multiple routers**. RegExpRouter 是 JavaScript 世界中最快的路由。它使用在调度之前创建的单个大型正则表达式来匹配路由。使用 SmartRouter,它支持所有路由模式。 ¥**RegExpRouter** is the fastest router in the JavaScript world. It matches the route using a single large Regex created before dispatch. With **SmartRouter**, it supports all route patterns. LinearRouter 可以非常快速地注册路由,因此它适用于每次初始化应用的环境。PatternRouter 只是添加和匹配模式,使其变小。 ¥**LinearRouter** registers the routes very quickly, so it's suitable for an environment that initializes applications every time. **PatternRouter** simply adds and matches the pattern, making it small. 参见 [有关路由的更多信息](/docs/concepts/routers)。 ¥See [more information about routes](/docs/concepts/routers). ## Web 标准 ¥Web Standards 由于使用了 Web 标准,Hono 可以在很多平台上运行。 ¥Thanks to the use of the **Web Standards**, Hono works on a lot of platforms. * Cloudflare Workers * Cloudflare 页面 ¥Cloudflare Pages * Fastly 计算 ¥Fastly Compute * Deno * Bun * Vercel * AWS Lambda * Lambda@Edge * 其他 ¥Others 通过使用 [Node.js 适配器](https://github.com/honojs/node-server),Hono 可以在 Node.js 上运行。 ¥And by using [a Node.js adapter](https://github.com/honojs/node-server), Hono works on Node.js. 参见 [有关 Web 标准的更多信息](/docs/concepts/web-standard)。 ¥See [more information about Web Standards](/docs/concepts/web-standard). ## 中间件和助手 ¥Middleware & Helpers Hono 有许多中间件和助手。这使 "写得少,做得多" 成为现实。 ¥**Hono has many middleware and helpers**. This makes "Write Less, do more" a reality. 开箱即用,Hono 提供中间件和助手: ¥Out of the box, Hono provides middleware and helpers for: * [基本身份验证](/docs/middleware/builtin/basic-auth) ¥[Basic Authentication](/docs/middleware/builtin/basic-auth) * [承载身份验证](/docs/middleware/builtin/bearer-auth) ¥[Bearer Authentication](/docs/middleware/builtin/bearer-auth) * [主体限制](/docs/middleware/builtin/body-limit) ¥[Body Limit](/docs/middleware/builtin/body-limit) * [缓存](/docs/middleware/builtin/cache) ¥[Cache](/docs/middleware/builtin/cache) * [压缩](/docs/middleware/builtin/compress) ¥[Compress](/docs/middleware/builtin/compress) * [上下文存储](/docs/middleware/builtin/context-storage) ¥[Context Storage](/docs/middleware/builtin/context-storage) * [Cookie](/docs/helpers/cookie) * [CORS](/docs/middleware/builtin/cors) * [ETag](/docs/middleware/builtin/etag) * [html](/docs/helpers/html) * [JSX](/docs/guides/jsx) * [JWT 身份验证](/docs/middleware/builtin/jwt) ¥[JWT Authentication](/docs/middleware/builtin/jwt) * [日志器](/docs/middleware/builtin/logger) ¥[Logger](/docs/middleware/builtin/logger) * [语言](/docs/middleware/builtin/language) ¥[Language](/docs/middleware/builtin/language) * [漂亮的 JSON](/docs/middleware/builtin/pretty-json) ¥[Pretty JSON](/docs/middleware/builtin/pretty-json) * [安全标头](/docs/middleware/builtin/secure-headers) ¥[Secure Headers](/docs/middleware/builtin/secure-headers) * [SSG](/docs/helpers/ssg) * [流式传输](/docs/helpers/streaming) ¥[Streaming](/docs/helpers/streaming) * [GraphQL 服务器](https://github.com/honojs/middleware/tree/main/packages/graphql-server) ¥[GraphQL Server](https://github.com/honojs/middleware/tree/main/packages/graphql-server) * [Firebase 身份验证](https://github.com/honojs/middleware/tree/main/packages/firebase-auth) ¥[Firebase Authentication](https://github.com/honojs/middleware/tree/main/packages/firebase-auth) * [Sentry](https://github.com/honojs/middleware/tree/main/packages/sentry) * 其他! ¥Others! 例如,使用 Hono 添加 ETag 和请求日志记录只需要几行代码: ¥For example, adding ETag and request logging only takes a few lines of code with Hono: ```ts import { Hono } from 'hono' import { etag } from 'hono/etag' import { logger } from 'hono/logger' const app = new Hono() app.use(etag(), logger()) ``` 参见 [有关中间件的更多信息](/docs/concepts/middleware)。 ¥See [more information about Middleware](/docs/concepts/middleware). ## 开发者体验 ¥Developer Experience Hono 提供了令人愉悦的 "开发者体验"。 ¥Hono provides a delightful "**Developer Experience**". 借助 `Context` 对象,可以轻松访问请求/响应。此外,Hono 是用 TypeScript 编写的。Hono 有 "类型"。 ¥Easy access to Request/Response thanks to the `Context` object. Moreover, Hono is written in TypeScript. Hono has "**Types**". 例如,路径参数将是字面量类型。 ¥For example, the path parameters will be literal types. ![SS](/images/ss.png) Validator 和 Hono Client `hc` 启用了 RPC 模式。在 RPC 模式下,你可以使用自己喜欢的验证器(例如 Zod),并轻松地与客户端共享服务器端 API 规范并构建类型安全的应用。 ¥And, the Validator and Hono Client `hc` enable the RPC mode. In RPC mode, you can use your favorite validator such as Zod and easily share server-side API specs with the client and build type-safe applications. 参见 [Hono Stacks](/docs/concepts/stacks)。 ¥See [Hono Stacks](/docs/concepts/stacks). # 最佳实践 ¥Best Practices Hono 非常灵活。你可以根据需要编写应用。但是,有更好的最佳实践可以遵循。 ¥Hono is very flexible. You can write your app as you like. However, there are best practices that are better to follow. ## 尽可能不要制作 "控制器" ¥Don't make "Controllers" when possible 如果可能,你不应创建 "类似 Ruby on Rails 的控制器"。 ¥When possible, you should not create "Ruby on Rails-like Controllers". ```ts // 🙁 // A RoR-like Controller const booksList = (c: Context) => { return c.json('list books') } app.get('/books', booksList) ``` 问题与类型有关。例如,如果不编写复杂的泛型,则无法在 Controller 中推断路径参数。 ¥The issue is related to types. For example, the path parameter cannot be inferred in the Controller without writing complex generics. ```ts // 🙁 // A RoR-like Controller const bookPermalink = (c: Context) => { const id = c.req.param('id') // Can't infer the path param return c.json(`get ${id}`) } ``` 因此,你不需要创建类似 RoR 的控制器,而应该在路径定义后直接编写处理程序。 ¥Therefore, you don't need to create RoR-like controllers and should write handlers directly after path definitions. ```ts // 😃 app.get('/books/:id', (c) => { const id = c.req.param('id') // Can infer the path param return c.json(`get ${id}`) }) ``` ## `hono/factory` 中的 `factory.createHandlers()` ¥`factory.createHandlers()` in `hono/factory` 如果你仍想创建类似 RoR 的控制器,请在 [`hono/factory`](/docs/helpers/factory) 中使用 `factory.createHandlers()`。如果你使用这种方法,类型推断将正常工作。 ¥If you still want to create a RoR-like Controller, use `factory.createHandlers()` in [`hono/factory`](/docs/helpers/factory). If you use this, type inference will work correctly. ```ts import { createFactory } from 'hono/factory' import { logger } from 'hono/logger' // ... // 😃 const factory = createFactory() const middleware = factory.createMiddleware(async (c, next) => { c.set('foo', 'bar') await next() }) const handlers = factory.createHandlers(logger(), middleware, (c) => { return c.json(c.var.foo) }) app.get('/api', ...handlers) ``` ## 构建更大的应用 ¥Building a larger application 使用 `app.route()` 构建更大的应用而无需创建 "类似 Ruby on Rails 的控制器"。 ¥Use `app.route()` to build a larger application without creating "Ruby on Rails-like Controllers". 如果你的应用有 `/authors` 和 `/books` 端点,并且你希望将文件与 `index.ts` 分开,请创建 `authors.ts` 和 `books.ts`。 ¥If your application has `/authors` and `/books` endpoints and you wish to separate files from `index.ts`, create `authors.ts` and `books.ts`. ```ts // authors.ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.json('list authors')) app.post('/', (c) => c.json('create an author', 201)) app.get('/:id', (c) => c.json(`get ${c.req.param('id')}`)) export default app ``` ```ts // books.ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.json('list books')) app.post('/', (c) => c.json('create a book', 201)) app.get('/:id', (c) => c.json(`get ${c.req.param('id')}`)) export default app ``` 然后,导入它们并将其与 `app.route()` 一起挂载在路径 `/authors` 和 `/books` 上。 ¥Then, import them and mount on the paths `/authors` and `/books` with `app.route()`. ```ts // index.ts import { Hono } from 'hono' import authors from './authors' import books from './books' const app = new Hono() // 😃 app.route('/authors', authors) app.route('/books', books) export default app ``` ### 如果要使用 RPC 功能 ¥If you want to use RPC features 上面的代码对于正常用例来说效果很好。但是,如果你想使用 `RPC` 功能,可以通过如下链接获取正确的类型。 ¥The code above works well for normal use cases. However, if you want to use the `RPC` feature, you can get the correct type by chaining as follows. ```ts // authors.ts import { Hono } from 'hono' const app = new Hono() .get('/', (c) => c.json('list authors')) .post('/', (c) => c.json('create an author', 201)) .get('/:id', (c) => c.json(`get ${c.req.param('id')}`)) export default app ``` 如果你将 `app` 的类型传递给 `hc`,它将获得正确的类型。 ¥If you pass the type of the `app` to `hc`, it will get the correct type. ```ts import app from './authors' import { hc } from 'hono/client' // 😃 const client = hc('http://localhost') // Typed correctly ``` 有关更多详细信息,请参阅 [RPC 页面](/docs/guides/rpc#using-rpc-with-larger-applications)。 ¥For more detailed information, please see [the RPC page](/docs/guides/rpc#using-rpc-with-larger-applications). # 示例 ¥Examples 查看 [示例部分](/examples/)。 ¥See the [Examples section](/examples/). # 常见问题 ¥Frequently Asked Questions 本指南收集了有关 Hono 的常见问题 (FAQ) 及其解决方法。 ¥This guide is a collection of frequently asked questions (FAQ) about Hono and how to resolve them. ## Hono 有官方的 Renovate 配置吗? ¥Is there an official Renovate config for Hono? Hono 团队目前不维护 [Renovate](https://github.com/renovatebot/renovate) 配置。因此,请按如下方式使用第三方 renovate-config。 ¥The Hono teams does not currently maintain [Renovate](https://github.com/renovatebot/renovate) Configuration. Therefore, please use third-party renovate-config as follows. 在你的 `renovate.json` 中: ¥In your `renovate.json` : ```json // renovate.json { "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "github>shinGangan/renovate-config-hono" // [!code ++] ] } ``` 有关更多详细信息,请参阅 [renovate-config-hono](https://github.com/shinGangan/renovate-config-hono) 存储库。 ¥see [renovate-config-hono](https://github.com/shinGangan/renovate-config-hono) repository for more details. # 助手工具 ¥Helpers 辅助程序可用于协助开发你的应用。与中间件不同,它们不充当处理程序,而是提供有用的功能。 ¥Helpers are available to assist in developing your application. Unlike middleware, they don't act as handlers, but rather provide useful functions. 例如,以下是如何使用 [Cookie 助手](/docs/helpers/cookie): ¥For instance, here's how to use the [Cookie helper](/docs/helpers/cookie): ```ts import { getCookie, setCookie } from 'hono/cookie' const app = new Hono() app.get('/cookie', (c) => { const yummyCookie = getCookie(c, 'yummy_cookie') // ... setCookie(c, 'delicious_cookie', 'macha') // }) ``` ## 可用助手 ¥Available Helpers * [接受](/docs/helpers/accepts) ¥[Accepts](/docs/helpers/accepts) * [适配器](/docs/helpers/adapter) ¥[Adapter](/docs/helpers/adapter) * [Cookie](/docs/helpers/cookie) * [css](/docs/helpers/css) * [开发](/docs/helpers/dev) ¥[Dev](/docs/helpers/dev) * [工厂](/docs/helpers/factory) ¥[Factory](/docs/helpers/factory) * [html](/docs/helpers/html) * [JWT](/docs/helpers/jwt) * [SSG](/docs/helpers/ssg) * [流式传输](/docs/helpers/streaming) ¥[Streaming](/docs/helpers/streaming) * [测试](/docs/helpers/testing) ¥[Testing](/docs/helpers/testing) * [WebSocket](/docs/helpers/websocket) # 客户端组件 ¥Client Components `hono/jsx` 不仅支持服务器端,还支持客户端。这意味着可以创建一个在浏览器中运行的交互式 UI。我们称之为客户端组件或 `hono/jsx/dom`。 ¥`hono/jsx` supports not only server side but also client side. This means that it is possible to create an interactive UI that runs in the browser. We call it Client Components or `hono/jsx/dom`. 它速度快而且非常小。`hono/jsx/dom` 中的计数器程序使用 Brotli 压缩后只有 2.8KB。但是,React 占用 47.8KB。 ¥It is fast and very small. The counter program in `hono/jsx/dom` is only 2.8KB with Brotli compression. But, 47.8KB for React. 本节介绍客户端组件特有的功能。 ¥This section introduces Client Components-specific features. ## 反例 ¥Counter example 以下是简单计数器的示例,相同的代码与 React 中的工作方式相同。 ¥Here is an example of a simple counter, the same code works as in React. ```tsx import { useState } from 'hono/jsx' import { render } from 'hono/jsx/dom' function Counter() { const [count, setCount] = useState(0) return (

Count: {count}

) } function App() { return ( ) } const root = document.getElementById('root') render(, root) ``` ## `render()` 你可以使用 `render()` 在指定的 HTML 元素内插入 JSX 组件。 ¥You can use `render()` to insert JSX components within a specified HTML element. ```tsx render(, container) ``` ## 与 React 兼容的 Hooks ¥Hooks compatible with React hono/jsx/dom 具有与 React 兼容或部分兼容的 Hooks。你可以通过查看 [React 文档](https://react.nodejs.cn/reference/react/hooks) 来了解这些 API。 ¥hono/jsx/dom has Hooks that are compatible or partially compatible with React. You can learn about these APIs by looking at [the React documentation](https://react.nodejs.cn/reference/react/hooks). * `useState()` * `useEffect()` * `useRef()` * `useCallback()` * `use()` * `startTransition()` * `useTransition()` * `useDeferredValue()` * `useMemo()` * `useLayoutEffect()` * `useReducer()` * `useDebugValue()` * `createElement()` * `memo()` * `isValidElement()` * `useId()` * `createRef()` * `forwardRef()` * `useImperativeHandle()` * `useSyncExternalStore()` * `useInsertionEffect()` * `useFormStatus()` * `useActionState()` * `useOptimistic()` ## `startViewTransition()` 系列 ¥`startViewTransition()` family `startViewTransition()` 系列包含原始钩子和函数,可轻松处理 [查看转换 API](https://web.nodejs.cn/en-US/docs/Web/API/View_Transitions_API)。以下是如何使用它们的示例。 ¥The `startViewTransition()` family contains original hooks and functions to handle [View Transitions API](https://web.nodejs.cn/en-US/docs/Web/API/View_Transitions_API) easily. The followings are examples of how to use them. ### 1. 最简单的例子 ¥ An easiest example 你可以使用 `document.startViewTransition` 或 `startViewTransition()` 语法编写过渡。 ¥You can write a transition using the `document.startViewTransition` shortly with the `startViewTransition()`. ```tsx import { useState, startViewTransition } from 'hono/jsx' import { css, Style } from 'hono/css' export default function App() { const [showLargeImage, setShowLargeImage] = useState(false) return ( <>