release · 

H3 v2 beta

⚡ H3 v2 测试版现已发布 - 完全基于 Web 标准重写,向下兼容,速度比以往更快!¥⚡ H3 v2 beta is here — fully rewritten on web standards, backward-compatible, and faster than ever!
Pooya Parsa

Pooya Parsa

访问新的 H3 Guide 快速入门。

H3 于 2020 年末推出,正值边缘计算工作者兴起之际。使用 H3 + unjs/unenv,我们可以在兼容 Node.js 的工作环境中运行 Nitro 部署,两全其美!自 v1.8 以来,H3 改进了对 Web 标准的支持。

¥H3 started in late 2020, during the rise of edge workers. With H3 + unjs/unenv, we could run Nitro deployments in worker environments with Node.js compatibility, best of both worlds! Since v1.8, H3 has improved its support for web standards.

不过,H3 主要基于 Node.js API,并带有一个 Web 标准兼容层。考虑到 Node.js 在 JavaScript 服务器运行时中的流行度,这在当时是合乎逻辑的选择。

¥But still, H3 was primarily based on Node.js APIs with a compatibility layer for web standards. Logical choice at the time, given Node.js's popularity amongst JavaScript server runtimes.

得益于 WinterTC 等项目不断发展的 Web 标准,以及 DenoBun 和最新的 Node.js 中的运行时支持,生态系统已准备好将 Web 标准作为服务器开发的首要标准。优势包括:

¥Thanks to evolving web standards by initiatives like WinterTC and runtime support in Deno, Bun, and the latest Node.js, ecosystem is ready to embrace web standards first class for server development. Benefits include:

  • 跨运行时互操作性(Node.js、Deno、Bun、Workers 等)
  • 跨框架兼容性(H3、Hono、Elysia 等)
  • 跨环境兼容性(前后端共享且熟悉的代码)
  • 利用更多运行时原生原语,例如(请求、URL、标头等)
  • 更简单的 API 测试

💥 Srvx:通用 Web 服务器 API

¥💥 Srvx: Universal Web Server API

一个主要的挑战是 Node.js 缺乏对 Web 标准 HTTP 服务器的内置支持。为了兼容 node:http,需要一个适配器将 Node.js IncomingMessage 桥接到 Web Request,并通过 Node.js ServerResponse 处理 Web Response。我们实现了 兼容层,它可以桥接各种接口,并实现高达 96.98% 的原生 node:http 性能(参见 benchmarks)。

¥A major challenge was that Node.js lacks built-in support for web-standard HTTP servers. For node:http compatibility, an adapter is needed to bridge Node.js IncomingMessage to web Request, and to handle web Response via Node.js ServerResponse. We have implemented a compatibility layer that bridges interfaces and achieves up to 96.98% of native node:http performance (see benchmarks).

诸如 DenoBun 和 Edge Workers 之类的运行时率先采用了 Web 服务器标准,但由于缺乏足够的规范,它们未能就相同的接口达成一致。那么如何访问客户端 IP 地址和其他上下文呢?如何设置服务器端口和 TLS 选项?如何处理 WebSocket 升级?每个运行时都创建了自己的 API。

¥Runtimes such as Deno, Bun, and Edge Workers pioneered the adoption of web standards for servers, but they did not agree on the same interface due to lack of enough specs. So how do you access the client IP address and additional context? How do you set the server port and TLS options? How do you handle WebSocket upgrades? Each runtime created its own API.

我们已创建 💥 srvx:一个统一的层,在任何地方都以完全相同的方式工作。兼容 Deno、Bun、Node.js、Service Workers 和 Edge Workers。

¥We have created 💥 srvx: A unified layer that works everywhere exactly the same. Compatible with Deno, Bun, Node.js, Service Workers, Edge Workers.

Example
// Dynamic adapter will be used based export conditions of each runtime
import { serve } from "srvx";

serve({
  port: 3000,
  // tls: { cert: "server.crt", key: "server.key" }
  fetch(req) {
    // Server Extensions: req.ip, req.waitUntil(), req.runtime?.{bun,deno,node,cloudflare,...}
    return new Response("👋 Hello there!");
  },
});
由于 💥 srvx 统一了运行时差异,H3 可以保持更简洁,专注于 Web 标准 API。¥!TIP With 💥 srvx unifying runtime differences, H3 can remain simpler, focusing exclusively on web standard APIs.

⚡ H3:微型服务器编写器 🎶

¥⚡ H3: Tiny Server Composer 🎶

我们努力最小化和简化 H3 的作用域。

¥We worked hard to minimize and simplify H3’s scope.

import { H3, serve } from "h3";

const app = new H3().get("/", () => "⚡️ Tadaa!");

serve(app, { port: 3000 });

🪶 轻盈无比

¥🪶 Lighter Than a Feather

我们采用一种新方法进行基准测试,该方法侧重于衡量框架本身引入的开销,而不是网络层。我们的目标是同时优化所有相关的测量指标,使这些数字尽可能接近未添加或使用任何框架的基准。此方法使 H3 能够优化每个请求的延迟,并显著减小核心包的大小。

¥We approached benchmarking with a new method that focuses on measuring the overhead introduced by the framework itself, rather than the network layer. Our goal is to optimize all relevant measurements together, making the numbers as close as possible to a baseline where no framework is added or used. This method allowed H3 to achieve optimized latency improvements per request and a dramatically smaller core bundle size.

测量H3 v1🚀 H3 v2
请求处理节点:36 µs
Bun:27 µs
Deno:7 ms
节点:7 µs(速度提升 5 倍)
Bun:3 µs(速度提升 9 倍)
Deno:1.2 µs (速度提高 156 倍)
包大小最小值:101 kB
min+gzip:39.6 kB
最小值:9.1 kB(体积缩小 91%)
min+gzip:3.6 kB(体积缩小 90%)
min:5.2 kB / min+gzip:2.1 kB (fetchable 处理程序)
H3 v2 的性能与使用 new URL(req.url).pathname 进行路由的普通 fetch 处理程序几乎相同。换句话说,你可以享受 H3 的优势,而性能几乎为零!¥!TIP H3 v2 performance is nearly identical to plain fetch handler with new URL(req.url).pathname for routing. In other words, you get the benefits of H3 with nearly zero performance cost!
基准测试适用于使用 Web 标准目标的 H3 核心,不包含适配器。它们主要用于内部优化目的。查看详细信息,请参阅 benchmark;查看 Node.js 适配器性能,请参阅 srvx 基准测试。¥!NOTE Benchmarks apply to the H3 core using the Web Standard target and do not include adapters. They are primarily intended for internal optimization purposes. See the benchmark for details and srvx benchmarks for Node.js adapter performances.

✅ 类型化 Web 标准

¥✅ Typed Web Standards

H3 采用 Web 标准 API,例如 请求响应URL标头,而不会在标准之上引入新的约定。

¥H3 adopts web standard APIs such as Request, Response, URL, and Headers, without introducing new conventions on top of the standards.

我们推出了一项新的举措,旨在实现 Web API 的强类型化:✅ fetchdts。集成到 H3 中,我们现在将两者的优势结合起来 - 标准和类型的便捷性。

¥We have launched a new initiative to strongly type Web APIs: ✅ fetchdts. Integrated into the H3, now we combine the best of both worlds—standards and the convenience of types.

import { defineHandler } from "h3";

const handler = defineHandler(async (event) => {
  // URL Parsing
  const { pathname, searchParams } = event.url;

  // Access to request headers (try auto-completion in editor!)
  const accept = event.req.headers.get("Accept");

  // Read body
  const bodyStream = await event.req.body;
  const bodyText = await event.req.text();
  const bodyJSON = await event.req.json();
  const bodyFormData = await event.req.formData();

  // Access to runtime specific context
  const { deno, bun, node } = event.req.runtime;

  // Prepare response (h3 does this smartly)
  event.res.headers.set("Content-Type", "application/json");

  return { hello: "web" };
});

现在继续调用处理程序 .fetch

¥Now go ahead and call handler .fetch:

const response = await handler.fetch("/");

// 🧙 Typed response: { hello: string; }
const json = await response.json();
你可以直接将事件处理程序用作独立的、甚至更小的 Web 处理程序,而无需 H3 核心!¥!TIP You can directly use event handlers as a standalone, even smaller web handlers without h3 core!

🧩 中间件和插件

¥🧩 Middleware and Plugins

H3 现在提供了一种符合人机工程学且可组合的方式,使用 next() 函数(受 Hono 中间件 💛 启发)来链接中间件。

¥H3 now offers an ergonomic, composable way to chain middleware using next() function (inspired by Hono middleware 💛).

此外,我们引入了一种简单但功能强大的模式,使用可重用的 plugins 扩展 H3 应用。

¥Additionally, we have introduced a simple yet powerful pattern to extend H3 apps using reusable plugins.

import { H3 } from "h3";

const app = new H3().use(async (event, next) => {
  // ... before response ...
  const body = await next();
  // ... after response ...
  event.res.headers.append("x-middleware", "works");
  event.waitUntil(sendMetrics(event));
  return body;
});
接受 next 回调是可选的。中间件可以像 v1 一样编写,但不返回响应。¥!NOTE Accepting next callback is optional. Middleware can be written like v1 without returning a response.

⬆️ 从版本 1 迁移

¥⬆️ Migration from Version 1

我们尽力减少重大变更。大多数实用程序保留了向后兼容性。

¥We've tried to minimize breaking changes. Most of utilities preserved backward compatibility.

查看 Migration Guide

🙌 统一 H(TTP) 服务器工具所有人

¥🙌 Unified H(TTP) Server Tools for Everyone

H3 及相关项目已迁移至专用的 github org 和新的 h3.dev 域名(感谢 syntax.fm 和其他 sponsors 💛 的捐赠)。

¥H3 and related projects moved to a dedicated github org and new h3.dev domain (thanks to the donation from syntax.fm and other sponsors 💛).

在 H3 框架下,我们维护了几个通用 JavaScript 服务器的关键组件。

¥Under the H3 umbrella, we maintain several key components for universal JavaScript servers.

无论是否使用 H3,以及任何 JavaScript 运行时,所有内容都完全开放且可用。

¥All fully open and usable with or without H3, and with any JavaScript runtime.

❤️ 特别感谢

¥❤️ Special Thanks

如果没有出色的 contributorscommunity 的反馈、包括 HonoElysia 在内的 Web 标准框架的启发,以及 sponsors 的帮助,这个版本是不可能实现的。sponsors 使开源工作成为可能。

¥This release would not have been possible without wonderful contributors, feedback from the community, inspirations from web-standard frameworks including Hono and Elysia, and sponsors who made it possible to work on open source.

🗺️ v2 路线图(稳定版)

¥🗺️ Roadmap to v2 (stable)

后续步骤:

¥Next steps:

  • 收集社区反馈。
  • 根据反馈完成 API 更新。
  • 确保生态系统兼容性并升级到 Nitro v3。

::callout{to="https://discord.h3.dev"} 加入我们的 Discord,分享你的经验和反馈!::

¥::callout{to="https://discord.h3.dev"} Join our Discord to share your experience and feedback! ::

访问新的 H3 Guide 快速入门。