---
id: start.server-route
kind: recipe
product: start
framework: react
locale: zh-CN
revision: 2
sourceCheckedOn: "2026-08-03"
versionRange: "Start ^1 / Router ^1"
verifiedAgainst: "@tanstack/react-start@1.168.34 + @tanstack/react-router@1.170.18"
contentModel: 2
packages:
  - "@tanstack/react-start"
  - "@tanstack/react-router"
tasks:
  - "create-server-route"
  - "external-api"
  - "return-http-status"
  - "choose-server-route"
sourceRefs:
  - "https://tanstack.com/start/latest/docs/framework/react/guide/server-routes"
  - "https://tanstack.com/start/latest/docs/framework/react/guide/server-functions"
---

# 创建外部可调用的 Server Route

> 为第三方调用方建立原生 HTTP 端点，并显式返回状态、缓存和安全响应。

## 执行契约

- **适用场景:** Webhook、外部客户端或标准 HTTP 集成需要稳定端点。
- **不要使用:** 仅供同一 Start 应用内部调用且需要端到端类型时，优先 Server Function。
- **前置检查:** 定义方法、路径、输入、状态码、响应 Schema、鉴权方式和幂等要求。
- **验证结果:** 用独立 HTTP 客户端测试成功、无权限、非法输入和未找到响应。
- **失败模式:** 外部调用出现 HTML 或 200 错误体时，检查是否显式返回 Response、状态码和 Content-Type。
- **安全边界:** 外部入口必须验证身份、授权、输入大小与重放风险；不要依赖浏览器同源保护。

## 选择条件

应用内部、同源、需要端到端类型的 RPC 使用 Server Function。Webhook、移动端、第三方集成或必须遵守独立 HTTP 契约的入口使用 Server Route。

## 最小实现

在文件路由的 server.handlers 中返回 Response。所有失败分支都要显式选择状态码；页面级 notFound() 控制流不是 Server Route 的 404 响应。

File: `src/routes/api/health[.]json.ts`

```ts
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/api/health.json')({
  server: {
    handlers: {
      GET: async () => Response.json(
        { ok: true },
        { headers: { 'Cache-Control': 'no-store' } },
      ),
    },
  },
})
```

## 安全与验证

把 params、search、headers 和 body 当作 unknown。写入前验证并执行认证、授权和速率限制；返回稳定错误对象，不泄露内部异常。对身份相关响应使用 no-store 或 private，不能使用 public 共享缓存。

## Official sources

- https://tanstack.com/start/latest/docs/framework/react/guide/server-routes
- https://tanstack.com/start/latest/docs/framework/react/guide/server-functions
