在 Next.js 项目中,前端有时需要面向浏览器或外部客户端提供 HTTP 接口。Route Handlers 使用 Web 标准 Request 和 Response 对象处理请求。本文以工作记录接口为例,讨论路由定义、请求校验、权限、错误契约和可测试性。
1. 明确 HTTP 接口的职责
Route Handler 适合作为外部请求边界。内部数据访问函数不必为了在服务器使用而绕行同一应用的 HTTP 接口。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/fe110286a84374724bf24554b23aef731c10a2c7">
<section><h2>工作记录</h2><p>通过统一接口读取和创建记录</p></section>
</div>
app/api/records/route.ts
lib/records/service.ts
lib/auth/session.ts
2. 定义 GET 请求
GET 接口读取数据时仍需验证会话。返回字段应经过业务层筛选,不应直接序列化数据库中的全部列。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b79a134c126e9bd7f27da79f2a33bbad350b7ef1">
<ul>{records.map(item => <li key={item.id}>{item.title}</li>)}</ul>
</div>
export async function GET(request: Request) {
const user = await authenticate(request);
if (!user) return Response.json({
code: 'UNAUTHORIZED' }, {
status: 401 });
const records = await listVisibleRecords(user.id);
return Response.json({
items: records });
}
3. 解析并验证查询参数
URLSearchParams 返回字符串或 null,不能直接作为数据库分页数量使用。限定整数范围,避免异常输入扩大查询负载。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c67ad9feb927a1c3c728a53bd04418c3bf624e63">
<label>每页数量 <select value={limit} onChange={changeLimit}><option value="20">20</option><option value="50">50</option></select></label>
</div>
function parseLimit(url: URL) {
const raw = url.searchParams.get('limit') ?? '20';
const limit = Number(raw);
if (!/^\d+$/.test(raw) || !Number.isInteger(limit) || limit < 1 || limit > 100) return null;
return limit;
}
4. 正确处理 POST 请求体
request.json 可能因为无效 JSON 抛出异常。应先检查请求类型,再验证解析后的未知数据,不要直接断言为业务类型。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/f7fb53f771a9cd0b32c7b7206177a5f51ac94d67">
<form onSubmit={createRecord}><label>标题 <input name="title" required maxLength={120} /></label><button>创建</button></form>
</div>
let payload: unknown;
try {
payload = await request.json(); }
catch {
return Response.json({
code: 'INVALID_JSON' }, {
status: 400 }); }
if (!isValidRecordInput(payload)) return Response.json({
code: 'INVALID_INPUT' }, {
status: 422 });
5. 区分认证与资源授权
已登录用户不一定有权修改指定记录。资源查询必须包含用户或租户范围,权限判断不能依赖请求体中的 ownerId。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4f9a787a218b40a582497a6234eb752663a6306b">
<section><p>当前工作区:{workspaceName}</p><button disabled={!canCreate}>新增记录</button></section>
</div>
服务端使用认证会话确定用户身份,再由权限服务校验资源范围。Cookie 认证的写入接口还应按部署环境处理 CSRF 风险。
6. 建立稳定的错误响应契约
前端需要稳定错误码而不是数据库异常字符串。将预期业务错误映射到合适 HTTP 状态,未知异常记录在服务端并返回一般性错误。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/893c790be6c761f08885628d340c77d3517298d1">
{error && <p role="alert">{errorMessage(error.code)}</p>}
</div>
function conflict() {
return Response.json({
code: 'RECORD_CONFLICT', message: '记录状态已变化' }, {
status: 409 });
}
7. 为写入操作设计幂等边界
重复点击和网络重试可能产生多次请求。对于创建记录,可以使用服务端唯一约束或经校验的请求键,确保同一业务意图不重复创建。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/cc161de407f18c17088cb3532b8784fb6cbe3fe9">
<button type="submit" disabled={submitting}>{submitting ? '提交中' : '创建记录'}</button>
</div>
前端按钮禁用只是交互保护。服务器需在事务内验证幂等键与用户、请求内容的绑定,并明确冲突时返回的结果。
8. 明确响应缓存策略
含有用户数据的读取接口通常不应进入公共缓存。框架版本、路由配置和代理层都可能影响缓存,因此应明确声明所需行为。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/0e8282925a6a8a9c894c6e06617f6575ce9101e9">
<p>数据更新时间:{updatedAt}</p><button onClick={reload}>刷新</button>
</div>
return Response.json({
items }, {
headers: {
'Cache-Control': 'private, no-store' } });
9. 让前端区分网络与业务错误
fetch 在收到 HTTP 错误状态时通常仍会返回 Response。前端应根据状态和约定的响应体进行错误处理,避免把所有失败都描述为网络断开。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/097eae212646aab4eb3f7216f9e635b589692066">
<section role="status">{loading ? '正在读取' : '读取结束'}</section>
</div>
const response = await fetch('/api/records');
const result = await response.json();
if (!response.ok) throw new ApiError(response.status, result.code);
10. 以 HTTP 边界进行验收
验证无凭据、权限不足、无效 JSON、非法分页、重复提交和正常数据。还要检查接口错误不会暴露 SQL、路径或内部凭据。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/ff03ff0cbae91e018fc6cb04c5e41e7c80a1b835">
<dl><dt>请求状态</dt><dd>{status}</dd><dt>错误码</dt><dd>{code ?? '无'}</dd></dl>
</div>
测试时可以直接构造 Request 调用 handler,但还需要部署环境的集成测试验证代理、Cookie 和运行时配置。
总结
Route Handlers 的重点是清晰的 HTTP 契约。将身份校验、参数验证、数据访问和错误转换分离,并为写入操作建立服务端幂等保障,能够使 Next.js 接口在多种客户端场景下保持稳定。
推荐阅读
React useReducer 实战:复杂组件状态转换与可测试的业务流程
https://github.com/tiktokwuyu-ux/technical-notes/commit/9230820adc2173383c177b3abd09fd51a5c65e47
Nuxt useAsyncData 实战:服务端数据预取、请求去重与刷新控制
https://github.com/tiktokwuyu-ux/technical-notes/commit/c0ec79cfc95bc481145d72a4e705799aa2e7cbcf
Angular 依赖注入实战:服务作用域、InjectionToken 与可替换架构
https://github.com/tiktokwuyu-ux/technical-notes/commit/ff03ff0cbae91e018fc6cb04c5e41e7c80a1b835
Vue Router 4 实战:导航守卫、权限路由与离开页面确认
https://github.com/tiktokwuyu-ux/technical-notes/commit/893c790be6c761f08885628d340c77d3517298d1
Svelte 动画实战:transition、animate 与列表重排交互
https://github.com/tiktokwuyu-ux/technical-notes/commit/c67ad9feb927a1c3c728a53bd04418c3bf624e63
React Suspense 实战:组件按需加载、错误边界与交互等待
https://github.com/tiktokwuyu-ux/technical-notes/commit/75af52f5c33999f7dc136f021f71bc9fe4a0e57d
JavaScript History API 实战:单页导航、前进后退与滚动恢复
https://github.com/tiktokwuyu-ux/technical-notes/commit/4759071e38859cf641eaf059b4a791d334cc119c
Angular Reactive Forms 实战:动态字段、交叉校验与复杂表单
https://github.com/tiktokwuyu-ux/technical-notes/commit/5687b48cf61c04b9e0b75d455ec8aede8ace71f6
React useSyncExternalStore 实战:订阅外部数据源与稳定快照
https://github.com/tiktokwuyu-ux/technical-notes/commit/097eae212646aab4eb3f7216f9e635b589692066
React useId 与无障碍组件实战:表单关联、提示信息与组件复用
https://github.com/tiktokwuyu-ux/technical-notes/commit/d20a4ef58f781077cdf42606deadb704e041699e