字
字节笔记本
2026年5月3日
TanStack Start - Static Server Functions 静态服务端函数
API中转
¥120
静态服务端函数是在使用预渲染/静态生成时,在构建时执行并缓存为静态资产的服务端函数。这是 TanStack Start 的实验性功能。
注意: Static Server Functions 是实验性功能!
什么是静态服务端函数
通过将 staticFunctionMiddleware 中间件应用于 createServerFn,可以设置为"静态"模式:
tsx
import { createServerFn } from '@tanstack/react-start'
import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions'
const myServerFn = createServerFn({ method: 'GET' })
.middleware([staticFunctionMiddleware])
.handler(async () => {
return 'Hello, world!'
})确保
staticFunctionMiddleware是最后的中间件!
工作流程
构建时
- 在构建时预渲染期间,执行带有
staticFunctionMiddleware的服务端函数 - 结果在派生键(函数 ID + 参数/payload 哈希)下作为静态 JSON 文件与构建输出一起缓存
- 结果在预渲染/静态生成期间正常返回,用于预渲染页面
运行时
- 最初,提供预渲染页面的 HTML,服务端函数数据嵌入在 HTML 中
- 当客户端挂载时,嵌入的服务端函数数据被水合
- 对于未来的客户端端调用,服务端函数被替换为对静态 JSON 文件的 fetch 调用
使用场景
适合静态化的数据
| 场景 | 示例 | 原因 |
|---|---|---|
| 配置数据 | 功能开关、应用设置 | 构建时确定,很少变化 |
| 静态内容 | 文档、博客文章 | 内容稳定,可预渲染 |
| 公开数据 | 产品列表、定价 | 无需个性化,可缓存 |
| 地理位置数据 | 国家列表、时区 | 不变的参考数据 |
不适合静态化的数据
| 场景 | 原因 |
|---|---|
| 用户特定数据 | 需要认证和个性化 |
| 实时数据 | 股票价格、实时状态 |
| 频繁变化数据 | 评论、通知 |
| 私有数据 | 需要访问控制 |
基础示例
简单静态函数
tsx
export const getAppConfig = createServerFn({ method: 'GET' })
.middleware([staticFunctionMiddleware])
.handler(async () => {
return {
appName: 'My App',
version: '1.0.0',
features: {
darkMode: true,
notifications: true,
}
}
})带参数的静态函数
tsx
export const getPostBySlug = createServerFn({ method: 'GET' })
.middleware([staticFunctionMiddleware])
.inputValidator((data: { slug: string }) => data)
.handler(async ({ data }) => {
const post = await db.posts.findBySlug(data.slug)
return post
})中间件顺序
tsx
// ✅ 正确: staticFunctionMiddleware 在最后
export const myFunction = createServerFn({ method: 'GET' })
.inputValidator(schema)
.middleware([authMiddleware, loggingMiddleware, staticFunctionMiddleware])
.handler(async ({ data, context }) => {
// Handler logic
})性能优势
| 方面 | 动态服务端函数 | 静态服务端函数 |
|---|---|---|
| 首次加载 | 服务端执行 | 提供静态 HTML |
| 后续请求 | 每次执行 | 提供 JSON 文件 |
| 服务器负载 | 每次请求 | 无(CDN 缓存) |
| 响应时间 | 取决于逻辑 | 接近零 |
| 成本 | 计算资源 | CDN 带宽 |
限制
- 实验性功能: API 可能发生变化
- GET 方法: 主要设计用于 GET 请求
- 构建时数据: 只能访问构建时可用的数据
- 重新构建: 数据更新需要重新构建
分享: