Edge Runtime边缘计算实战:Vercel Edge Functions vs Cloudflare Workers生产级对比摘要:Edge Computing正在重塑Web应用的部署架构。将代码部署到离用户最近的边缘节点,可以实现毫秒级响应。本文深度对比Vercel Edge Functions和Cloudflare Workers两大主流平台,通过真实代码示例和性能测试,帮你做出最佳选择。什么是 Edge Runtime?传统 Serverless 架构中,代码运行在特定区域的数据中心(如 us-east-1)。用户从亚洲访问,请求需要跨越太平洋,延迟 200ms+。Edge Runtime 将代码部署到全球数百个边缘节点,用户请求在最近的节点处理:传统架构: 用户(上海) → 跨太平洋 → Lambda(us-east-1) → 返回 延迟: ~250ms Edge 架构: 用户(上海) → 上海边缘节点 → 返回 延迟: ~20msEdge vs Serverless vs 传统服务器特性Edge RuntimeServerless传统服务器冷启动1ms100-500ms无全球延迟~20ms100-300ms取决于位置执行时间有限(30s-5min)15分钟无限内存128MB10GB+无限制Node.js API子集完整完整适合场景轻量逻辑重计算任意Vercel Edge Functions 实战基础配置// app/api/hello/route.tsimport{NextRequest,NextResponse}from'next/server';// 指定为 Edge Runtimeexportconstruntime='edge';exportasyncfunctionGET(request:NextRequest){// 获取用户地理位置信息(Vercel 自动注入)constgeo=request.geo;constip=request.ip;returnNextResponse.json({message:'Hello from Edge!',location:{city:geo?.city,country:geo?.country,latitude:geo?.latitude,longitude:geo?.longitude,},ip,timestamp:newDate().toISOString(),});}地理位置路由// middleware.tsimport{NextRequest,NextResponse}from'next/server';exportconstconfig={matcher:'/api/:path*',};exportfunctionmiddleware(request:NextRequest){constcountry=request.geo?.country||'US';constcity=request.geo?.city||'Unknown';// 根据地理位置做 A/B 测试constbucket=hashString(city)%2===0?'A':'B';// 设置响应头constresponse=NextResponse.next();response.headers.set('X-User-Country',country);response.headers.set('X-AB-Bucket',bucket);response.headers.set('X-Edge-Region',request.geo?.region||'unknown');returnresponse;}functionhashString(str:string):number{lethash=0;for(leti=0;istr.length;i++){constchar=str.charCodeAt(i);hash=((hash5)-hash)+char;hash|=0;}returnMath.abs(hash);}Edge Middleware 实现国际化// middleware.tsimport{NextRequest,NextResponse}from'next/server';constLOCALES=['en','zh','ja','ko'];constDEFAULT_LOCALE='en';exportfunctionmiddleware(request:NextRequest){const{pathname}=request.nextUrl;// 检查是否已有语言前缀constpathnameHasLocale=LOCALES.some((locale)=pathname.startsWith(`/${locale}/`)||pathname===`/${locale}`);if(pathnameHasLocale)return;// 从 Accept-Language 头解析首选语言constacceptLanguage=request.headers.get('Accept-Language');constpreferredLocale=parseLocale(acceptLanguage);// 重定向到对应语言路径consturl=request.nextUrl.clone();url.pathname=`/${preferredLocale}${pathname}`;returnNextResponse.redirect(url);}functionparseLocale(header:string|null):string{if(!header)returnDEFAULT_LOCALE;constlocales=header.split(',').map((lang)={const[locale,q]=lang.trim().split(';q=');return{locale:locale.split('-')[0].toLowerCase(),q:q?parseFloat(q):1};}).sort((a,b)=b.q-a.q);for(const{locale}oflocales){if(LOCALES.includes(locale))returnlocale;}returnDEFAULT_LOCALE;}Edge Cache 策略// app/api/data/route.tsexportconstruntime='edge';exportasyncfunctionGET(request:NextRequest){const{searchParams}=newURL(request.url);constkey=searchParams.get('key');// 使用 Edge Cache APIconstcacheKey=newRequest(`