三种缓存策略
1. 永久缓存
// 显式启用永久缓存
const res = await fetch("https://api.example.com/posts", {
cache: "force-cache",
});
注意:在 Next.js 13/14 中,
force-cache是fetch的默认行为。但在 Next.js 15+ 中,默认行为已改为no-store(不缓存),需要显式声明force-cache才会启用永久缓存。
效果:类似 SSG(静态站点生成)
graph LR
Build[构建时] --> Fetch[请求 API]
Fetch --> Store[存储到文件]
Store --> Forever[永久使用<br/>直到重新构建]
style Forever fill:#9f9,stroke:#333,stroke-width:2px
适用场景:
- ✅ 博客文章(很少更新)
- ✅ 产品文档
- ✅ 静态内容
2. 从不缓存(Next.js 15+ 默认)
// Next.js 15+ 的默认行为,也可以显式声明
const res = await fetch("https://api.example.com/posts", {
cache: "no-store",
});
效果:类似 SSR(服务端渲染)
graph LR
U1[用户1请求] --> API[请求 API]
U2[用户2请求] --> API
U3[用户3请求] --> API
style API fill:#f99,stroke:#333,stroke-width:2px
适用场景:
- ✅ 实时数据(股票价格)
- ✅ 用户个人信息
- ✅ 购物车