Edge Functions 边缘计算前端实践:就近渲染、个性化与TTFB优化技术背景边缘计算将代码部署至靠近用户的边缘节点(PoP),通过就近渲染与缓存协同显著降低 TTFB 并支持个性化逻辑。前端与边缘函数协作可实现动态内容预处理、A/B 分流与安全校验,减少主源站压力。核心内容Cloudflare Workers:就近个性化与缓存协同export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const country = request.headers.get('cf-ipcountry') || 'US';
// 个性化:按地区注入配置
const config = await env.KV.get(`config:${country}`);
// 缓存协同:静态资源边缘缓存
if (url.pathname.startsWith('/assets/')) {
const cacheKey = new Request(url.toString(), request);
let res = await caches.default.match(cacheKey);
if (!res) {
res = await fetch(request);
res = new Response(res.body, res);
res.headers.set('Cache-Control', 'public, max-age=3600, s-maxage=86400');
ctx.waitUntil(caches.default.put(cacheKey, res.clone()));
}
return res;
}
// 动态 HTML:就近注入配置并下发
const html = `<!doctype html><html><head><meta charset="utf-8"/><title>Edge</title></head>
<body><script>window.__EDGE_CONFIG__=${config || '{}'};</script><div id="app"></div></body></html>`;
return new Response(html, { headers: { 'Content-Type': 'text/html; charset=utf-8' } });
}
};
Vercel Edge Middleware:A/B 分流与地域路由import { NextResponse } from 'next/server';
export const config = { matcher: '/' };
export function middleware(req) {
const url = req.nextUrl.clone();
const country = req.geo?.country || 'US';
const variant = Math.random() < 0.5 ? 'a' : 'b';
// 路由到不同变体
url.pathname = `/variants/${variant}`;
const res = NextResponse.rewrite(url);
// 注入地理信息头,前端可读取以做个性化
res.headers.set('x-geo-country', country);
return res;
}
边缘性能监控与指标采集async function measureTTFBEndpoint(endpoint: string) {
const start = performance.now();
const res = await fetch(endpoint, { cache: 'no-store' });
const ttfb = performance.now() - start;
return { ttfb, region: res.headers.get('x-edge-region') || 'unknown' };
}
function markEdgeNavigation(region: string) {
performance.mark(`edge-start-${region}`);
}
技术验证参数在 Cloudflare/Vercel 边缘(Chrome 128/Edge 130,全球多地区)下:首字节时间 TTFB:主源 320–580ms → 边缘 90–220ms(P95)动态个性化注入:无额外重渲染成本,首屏保持稳定资源边缘缓存命中率:≥ 85%A/B 分流开销:边缘重写延迟 P95 < 15ms应用场景按地理或用户分群进行个性化引导与默认设置边缘缓存与资源就近分发,降低首屏延迟动态路由与试验平台(A/B、多变体测试)最佳实践边缘与前端协同:注入配置、降级逻辑与监控标记合理 `Cache-Control` 与 `ETag`,兼顾一致性与命中率跨地区监控 TTFB 与命中率,动态调整策略保护隐私与安全,边缘层不暴露敏感数据与密钥

发表评论 取消回复