边缘函数和中间件
在边缘运行代码,实现认证、A/B 测试和地理路由,延迟极低。
边缘高级
为什么
边缘函数在 300+ 位置运行,认证和路由逻辑延迟低于 50ms。Cloudflare 边缘网络覆盖 330+ 城市,全球 p95 延迟低于 50ms。
边缘函数相比源服务器将 TTFB 降低 60-80%,Akamai 报告 2024 年 40% 的企业使用边缘计算。
何时使用
边缘认证检查、地理路由、A/B 测试或请求重写。 需要数据库写入的有状态逻辑避免边缘函数 — 边缘运行时无持久连接池。需要长时间运行任务(>30s)或重 CPU 计算时跳过。
如何做
# Next.js 中间件 (运行s at 边缘)
import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
export function middleware(req: NextRequest) {
// Geo-based 路由
const country = req.geo.country || 'US';
if (country === 'CN') {
return NextResponse.rewrite(new URL('/cn' + req.nextUrl.pathname, req.url));
}
// 认证 检查
const token = req.cookies.get('token');
if (!token && req.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon).*)'],
};
4. 验证部署 — curl -I https://your-app.example.com
5. 监控日志 — 前 5 分钟检查错误
6. 需要时回滚 — 回退到上一版本
示例
# Vercel 边缘 函数
export default function handler(req: Request) {
const country = req.headers.get('x-vercel-ip-country');
return Response.json({
message: `Hello from ${country}`,
timestamp: Date.now(),
});
}
export const config = { runtime: 'edge' };
常见问题
- ⚠无 Node.js API — 仅用 Web API(fetch、Response、Request)
- ⚠首次请求冷启动 — 用 edge config 保持热状态
- ⚠环境间配置漂移 — 使用基础设施即代码(Terraform/Pulumi)保持 dev/staging/prod 一致
最佳实践
- ✓中间件保持最小 — 每次请求都运行
- ✓特性开关用 edge config — 无需重新部署即可更新
- ✓设置健康检查和优雅关闭 — 处理 SIGTERM 以在退出前排空进行中的请求