如何优化 Vercel 应用的性能?
核心答案:Vercel 应用的性能优化可以从四个维度入手——渲染策略选择、构建产物瘦身、缓存配置、以及 Edge 能力利用。
渲染策略:选对模式比什么都重要
Vercel 上最影响性能的决策是渲染方式。SSG(静态生成)最快,ISR 兼顾更新和速度,SSR 只在需要实时数据时使用。大多数页面应该优先 SSG + ISR:
jsexport async function getStaticProps() { const data = await fetchData(); return { props: { data }, revalidate: 60 }; // ISR: 60秒后台重新生成 }
Next.js App Router 默认就是 Server Component,不要滥用 'use client',每个客户端组件都会增加 JS 体积。
构建优化:砍掉不必要的 JS
动态导入:非首屏组件用 dynamic() 按需加载。
jsconst Chart = dynamic(() => import('./Chart'), { ssr: false });
Tree Shaking:用 import { debounce } from 'lodash' 而非 import _ from 'lodash'。用 @next/bundle-analyzer 定位大包。
图片和字体:next/image 自动输出 WebP/AVIF 并按设备尺寸裁剪;next/font 消除字体布局偏移(CLS)。
缓存:Vercel 上最容易被忽视的杠杆
在 vercel.json 中配置 Cache-Control 头:
json{ "headers": [{ "source": "/static/:path*", "headers": [{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }] }] }
客户端用 SWR 做请求去重和后台刷新;服务端用 @vercel/kv 缓存计算结果。Vercel 默认对 HTML 响应设置 max-age=0, must-revalidate,静态资源则自动长期缓存。
Edge Runtime:把计算推到离用户最近的地方
Edge Function 冷启动在毫秒级,适合认证、重定向、A/B 测试等轻量逻辑:
jsexport const runtime = 'edge'; export default function handler(req) { return new Response('Hello from Edge'); }
Edge Middleware 可以在请求到达源站之前拦截,做地理路由或权限校验,减少回源延迟。但注意 Edge 环境不支持 Node.js API,Prisma 等库无法直接使用。
数据库连接:别让连接池成为瓶颈
Serverless 环境下每次请求可能创建新的数据库连接。用全局单例复用 Prisma Client:
jsconst globalForPrisma = globalThis; export const prisma = globalForPrisma.prisma ?? new PrismaClient(); if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
高并发场景考虑连接池服务(如 Vercel Postgres 自带的 pgBouncer)。
追问方向:ISR 的 revalidate 时间怎么定?Edge Runtime 和 Serverless Function 的选型边界在哪?Vercel Analytics 的 Web Vitals 指标(LCP/FID/CLS)分别对应哪些优化手段?Fluid Compute 如何缓解冷启动?