ByteNoteByteNote

字节笔记本

2026年2月20日

Hono v4.12.0 发布:$path 方法、类型增强与性能提升

本文介绍 Hono v4.12.0 的主要更新内容,包括 Hono Client 的 $path 方法、RPC 客户端类型增强、SSG 重定向插件,以及显著的性能提升。

版本概览

Hono v4.12.0 已正式发布!本次更新带来了多项新功能和改进:

  • Hono Client 新增 $path() 方法
  • RPC 客户端类型增强
  • SSG 重定向插件
  • Basic Auth 新增 onAuthSuccess 回调
  • 更多适配器支持 getConnInfo
  • TrieRouter 性能提升 1.5x ~ 2.0x

新功能详解

$path 方法

Hono Client 现在支持 $path() 方法,返回路径字符串而非完整 URL,适用于路由或缓存键场景:

typescript
const client = hc<typeof app>('http://localhost:8787')

// 获取路径字符串
const path = client.api.posts.$path() // => '/api/posts'

// 带路径参数
const postPath = client.api.posts[':id'].$path({
  param: { id: '123' },
}) // => '/api/posts/123'

// 带查询参数
const searchPath = client.api.posts.$path({
  query: { filter: 'test' },
}) // => '/api/posts?filter=test'

ApplyGlobalResponse 类型助手

新增的 ApplyGlobalResponse 类型助手允许为 RPC 客户端的所有路由添加全局错误响应类型:

typescript
const app = new Hono()
  .get('/api/users', (c) => c.json({ users: ['alice', 'bob'] }, 200))
  .onError((err, c) => c.json({ error: err.message }, 500))

type AppWithErrors = ApplyGlobalResponse<
  typeof app,
  {
    401: { json: { error: string; message: string } }
    500: { json: { error: string; message: string } }
  }
>

const client = hc<AppWithErrors>('http://api.example.com')
// 客户端现在知道成功和错误响应类型

SSG 重定向插件

新的 redirectPlugin 为 SSG 生成静态 HTML 重定向页面,支持 301、302、303、307、308 状态码:

typescript
import { toSSG } from 'hono/ssg'
import { defaultPlugin, redirectPlugin } from 'hono/ssg'

const app = new Hono()
app.get('/old', (c) => c.redirect('/new'))
app.get('/new', (c) => c.html('New Page'))

await toSSG(app, fs, {
  plugins: [redirectPlugin(), defaultPlugin()],
})

生成的重定向页面包含 <meta http-equiv="refresh"> 标签、canonical link 和 robots noindex meta 标签。

Basic Auth onAuthSuccess 回调

Basic Auth 中间件新增 onAuthSuccess 回调,在认证成功后调用:

typescript
app.use(
  '/auth/*',
  basicAuth({
    username: 'hono',
    password: 'ahotproject',
    onAuthSuccess: (c, username) => {
      c.set('user', { name: username, role: 'admin' })
      console.log(`User ${username} authenticated`)
    },
  })
)

更多适配器支持 getConnInfo

getConnInfo() 现在支持三个额外的适配器:

typescript
// AWS Lambda(支持 API Gateway v1、v2 和 ALB)
import { handle, getConnInfo } from 'hono/aws-lambda'

// Cloudflare Pages
import { handle, getConnInfo } from 'hono/cloudflare-pages'

// Netlify
import { handle, getConnInfo } from 'hono/netlify'

app.get('/', (c) => {
  const info = getConnInfo(c)
  return c.text(`Your IP: ${info.remote.address}`)
})

Trailing Slash 中间件 alwaysRedirect 选项

Trailing Slash 中间件新增 alwaysRedirect 选项,启用后会在执行处理器前进行重定向:

typescript
app.use(trimTrailingSlash({ alwaysRedirect: true }))

app.get('/my-path/*', async (c) => {
  return c.text('wildcard')
})
// /my-path/something/ 会在通配符处理器执行前重定向到 /my-path/something

语言中间件渐进式区域代码截断

normalizeLanguage 函数现在支持基于 RFC 4647 Lookup 的渐进式截断:ja-JP 会在 supportedLanguages 中只有基础语言时匹配 ja

typescript
app.use(
  '/*',
  languageDetector({
    supportedLanguages: ['en', 'ja'],
    fallbackLanguage: 'en',
    order: ['cookie', 'header'],
  })
)
// Accept-Language: ja-JP → 匹配 'ja'
// Accept-Language: ko-KR → 回退到 'en'

性能提升

TrieRouter 1.5x ~ 2.0x 更快

通过减少展开语法使用、O(1) hasChildren 检查、惰性正则表达式生成和移除冗余流程,TrieRouter 性能显著提升:

路由类型Node.jsDenoBun
短静态 GET /user1.70x1.40x1.34x
动态 GET /user/lookup/username/hey1.38x1.69x1.51x
通配符 GET /static/index.html1.51x1.72x1.43x
综合1.58x1.60x1.82x

c.json() 快速路径

c.json() 现在拥有与 c.text() 相同的快速路径优化。当没有自定义状态、头部或 finalized 状态时,Response 会直接创建而不分配 Headers 对象:

typescript
// 这个常见模式现在更快
return c.json({ message: 'Hello' })

项目链接

分享: