Next.js 缓存深入解析:用法与原理
本文由原文机器翻译。
正在加载文章...
正在加载文章...
本文由原文机器翻译。
Next.js 16 在缓存方面引入了重大范式转变:
Next.js 16 的缓存系统包括以下层级:
这是 React 18+ 的内置功能,可在同一渲染周期内自动对相同请求去重。
// app/page.js
async function getUser(id) {
// This function is called multiple times in the same render
const res = await fetch(`{{Cache Components 是 Next.js 16 中最重要的新功能,通过 "use cache" 指令实现显式缓存。
首先,在配置文件中启用它:
// next.config.ts
export default {
experimental: {
cacheComponents: true,
ppr: true // Optional: Enable Partial Prerendering
}
}// app/blog/page.js
"use cache"
export default async function BlogPage() {
const posts = await fetch('// components/product-list.js
"use cache"
export async function ProductList({ category }) {
const products = await fetch(`{{// lib/data.js
"use cache"
export async function getUser(userId) {
const user = await db.user.findUnique({ where: { id: userId } });
return user;
}使用 cacheLife配置缓存时长和重新验证策略:
"use cache"
export const cacheLife = {
stale: 3600, // Seconds before content is considered stale
revalidate: 900, // Background revalidation frequency
expire: 86400 // Time until content expires and is removed from cache
}
export async function getProducts() {
const products = await fetch('预设缓存生命周期配置:
// Using preset configurations
import { cacheLife } from 'next/cache';
"use cache"
export const config = {
cacheLife: 'hours' // Presets: hours, days, weeks, max
}
export async function getData() {
// ...
}Next.js 16 引入了新的缓存管理 API,以实现更细粒度的控制。
updateTag() 是一个仅限 Server Actions 的 API,提供“read-your-writes”语义,使用户能够立即看到自己的更改:
// app/actions.js
'use server'
import { updateTag } from 'next/cache';
export async function updateUserProfile(formData) {
const userId = formData.get('userId');
const name = formData.get('name');
// Update database
await db.user.update({
where: { id: userId },
data: { name }
});
// Immediately refresh cache, user sees updates in the same request
updateTag('user-profile');
return { success: true };
}// app/profile/page.js
"use cache"
export const tags = ['user-profile'];
export default async function ProfilePage() {
const user = await getCurrentUser();
return (
<form action={updateUserProfile}>
<input name="userId" value={refresh() 刷新未缓存的实时数据,而不影响已缓存内容:
// app/actions.js
'use server'
import { refresh } from 'next/cache';
export async function refreshNotifications() {
// Refresh notification counts and other real-time data
refresh();
// Cached page shell remains unchanged, only dynamic parts update
return { success: true };
}// components/notification-badge.js
export default async function NotificationBadge() {
// This part is not cached, always real-time
const count = await getUnreadCount();
return (
<button onClick={refreshNotifications}>
Notifications {count > 0 && <span>({count})</span>}
</button>
);
}revalidateTag() 现在可与 cacheLife 配置配合使用,支持 stale-while-revalidate(SWR)行为:
// app/actions.js
'use server'
import { revalidateTag } from 'next/cache';
export async function publishPost(postId) {
await // app/blog/page.js
"use cache"
export const tags = ['blog-posts'];
export const cacheLife = {
stale: 60,
revalidate: 30,
expire: 3600
}
export default async function BlogPage() {
const posts = await getPosts();
return <div>{/* Render posts */}</div>;
}'use server'
import { revalidatePath } from 'next/cache';
export async function updateContent() {
// Update data...
// Revalidate specific path
revalidatePath('/blog');
// Or revalidate specific page type
revalidatePath('/blog/[slug]', 'page');
}在 Next.js 16 中,所有动态代码默认在请求时执行。你需要使用 "use cache" 来显式启用缓存。
虽然 "use cache" 是推荐的, fetch 缓存选项仍然有效:
// Force cache
const data = await fetch('"use cache"
export const cacheLife = {
stale: 3600,
revalidate: 900
}
export async function getData() {
// All fetch requests automatically inherit cache configuration
const data1 = await fetch('
}// app/about/page.js
"use cache"
export default function About() {
return <div>About Us</div>;
}// app/blog/[slug]/page.js
"use cache"
export async function generateStaticParams() {
const posts = await fetch('// app/dashboard/page.js
// Force dynamic rendering (default behavior)
export const dynamic = 'force-dynamic';
// Or force static
export const dynamic = 'force-static';
// Set revalidation time
export const revalidate = 60;
export default function Dashboard() {
return <div>Dashboard</div>;
}客户端路由缓存行为保持不变。
'use client'
import Link from 'next/link';
export default function Navigation() {
return (
<nav>
<Link href="/about">About</Link>
<Link href="/blog" prefetch={true}>Blog</Link>
<Link href="/contact" prefetch={false}>Contact</Link>
</nav>
);
}// app/product/[id]/page.js
"use cache"
import { Suspense } from 'react';
import DynamicPrice from './dynamic-price';
export default async function ProductPage({ params }) {
const { id } = await params;
const product = await getProduct(id);
return (
<div>
<h1>{// app/product/[id]/dynamic-price.js
// Don't use "use cache", keep it dynamic
export default async function DynamicPrice({ productId }) {
const price = await getCurrentPrice(productId);
return <div>Current Price: ${price}</div>;
}// app/posts/[id]/page.js
"use cache"
export const tags = ['post'];
export default async function PostPage({ params }) {
const post = await getPost(// components/like-button.js
'use client'
import { likePost } from '@/app/actions';
export default function LikeButton({ postId, likes }) {
return (
<form action={likePost}>
<input type="hidden" name="postId" value={postId} />
<button>❤️ {likes}</button>
</form>
);
}// app/actions.js
'use server'
import { updateTag } from 'next/cache';
export async function likePost(formData) {
const postId = formData.get('postId');
await // app/dashboard/page.js
"use cache"
export const cacheLife = {
stale: 300, // 5 minutes
revalidate: 60
}
export default async function Dashboard() {
// Static config: long-term cache
const config = await getConfig(); // Uses page-level cache
return (
<div>
<header>{config.title}</header>
{/* Real-time data: no cache */}
<Suspense fallback={<div>Loading...</div>}>
<LiveMetrics />
</Suspense>
</div>
);
}// components/live-metrics.js
// Don't use "use cache"
export default async function LiveMetrics() {
const metrics = await fetch('// app/api/webhook/route.js
import { updateTag } from 'next/cache';
export async function POST(request) {
const payload = await request.json();
// Verify webhook source
if (!verifyWebhook(payload)) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
// Update corresponding cache tags based on event type
switch (payload.event) {
case 'post.published':
updateTag('blog-posts');
break;
case 'product.updated':
updateTag(`product-${
}Route Handlers 默认不缓存,需要显式启用:
// app/api/products/route.js
"use cache"
export const cacheLife = {
stale: 3600,
revalidate: 900
}
export async function GET() {
const products = await fetch('
}// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
logging: {
fetches: {
fullUrl: true,
},
},
};
module.exports = nextConfig;"use cache"
export const tags = ['data'];
export default async function Page() {
console.log('[Server]', 'Page render time:', new Date().toISOString());
const data = await fetch('npm run build构建输出会显示每个路由的渲染方式:
为什么: "use cache" 提供了更清晰、统一的缓存语义,并且编译器可以自动优化缓存键生成。
// ✅ Recommended: Use "use cache"
"use cache"
export const cacheLife = { stale: 3600, revalidate: 900 }
export async function getData() {
const data = await fetch('// ❌ Not Recommended: Mixing approaches (though still valid)
export async function getData() {
const data = await fetch('
}最佳实践:使用分层结构建立清晰的标签命名约定。
// ✅ Good tag naming: Use hierarchical naming
"use cache"
export const tags = ['content', 'content:blog', 'content:blog:posts'];
export const cacheLife = { stale: 3600 }
export async function getBlogPosts() {
return await // This allows flexible cache invalidation at different granularities
import { revalidateTag } from 'next/cache';
// Only revalidate blog posts
revalidateTag('content:blog:posts');
// Revalidate all blog content
revalidateTag('content:blog');
// Revalidate all content
revalidateTag('content');标签命名约定示例:
// Categorize by functional modules
const CACHE_TAGS = {
// User-related
USER: 'user',
USER_PROFILE: 'user:profile',
USER_SETTINGS: 'user:settings',
// Content-related
CONTENT: 'content',
CONTENT_POSTS: 'content:posts',
CONTENT_COMMENTS: 'content:comments',
// E-commerce-related
SHOP: 'shop',
SHOP_PRODUCTS: 'shop:products',
SHOP_CART: 'shop:cart',
};
// Usage example
"use cache"
export const tags = [CACHE_TAGS.CONTENT, CACHE_TAGS.CONTENT_POSTS];### 3. Combine PPR for Optimal Performance策略:将页面拆分为静态外壳和动态内容,利用 Partial Prerendering 获得最佳初始加载性能。
// app/dashboard/page.js
"use cache"
export const cacheLife = { stale: 300, revalidate: 60 }
export default async function DashboardPage() {
// This part will be cached
const layoutConfig = await getLayoutConfig();
<div>
{/* Static navigation - cached */}
<Navigation config={layoutConfig} />
{/* User welcome message - dynamic, not cached */}
<UserWelcome />
</Suspense>
{/* Stats cards - partially static, partially dynamic */}
<div className="grid grid-cols-3 gap-4">
<StaticCard title="Total Users" icon="users" />
{/* Real-time data - not cached */}
<Suspense fallback={<CardSkeleton />}>
<RealtimeMetrics />
{/* Historical data - short-term cache */}
<Suspense fallback={<CardSkeleton />}>
<HistoricalData />
</Suspense>
{/* Static footer - cached */}
<Footer />
</div>
);
}// components/realtime-metrics.js
// Don't use "use cache" - keep it real-time
export default async function RealtimeMetrics() {
const metrics = await fetch('性能提示:使用 PPR 时,静态外壳会立即显示,而动态部分会流式传输,从而显著减少用户感知的加载时间。
决策树:
| 数据类型 | 更新频率 | 推荐策略 | cacheLife 配置 |
|---|---|---|---|
| 静态内容(关于页面、FAQ) | 很少 | "use cache" | { stale: 86400 } |
| 博客文章、产品列表 | 每日/每周 | "use cache" + ISR | { stale: 3600, revalidate: 900 } |
| 用户生成内容 | 频繁 | "use cache" + tags | { stale: 300, revalidate: 60 } |
| 用户资料 | 中等 |
示例:电商产品页面混合策略
// app/products/[id]/page.js
"use cache"
export const tags = ['product'];
export const cacheLife = {
stale: 3600, // Fresh data within 1 hour
revalidate: 900, // Background revalidation every 15 minutes
expire: 86400 // Expires after 24 hours
}
export default async function ProductPage({ params }) {
const { id } = await params;
const product = await getProduct(id);
return (
{/* Static product info */}
<ProductInfo product={product} />
{/* Real-time inventory and price - not cached */}
<Suspense fallback={<PriceSkeleton />}>
</Suspense>
{/* Reviews - short-term cache */}
<Suspense fallback={<ReviewsSkeleton />}>
<ProductReviews productId={id} />
{/* Recommended products - medium-term cache */}
<Suspense fallback={<RecommendationsSkeleton />}>
<Recommendations productId={id} />
</Suspense>
);
}// components/realtime-price.js
export default async function RealtimePrice({ productId }) {
// No cache - always get latest price
const price = await fetch(
`{{// components/product-reviews.js
"use cache"
export const tags = ['product-reviews'];
export const cacheLife = { stale: 300 }; // 5-minute cache
export default async function ProductReviews({ productId }) {
const reviews = await getReviews(productId);
return <ReviewList reviews={reviews} />;
}}
<empty-block/>场景: 用户执行操作并期望立即看到结果(表单提交、点赞、评论等)。
// app/actions.js
'use server'
import { updateTag } from 'next/cache';
// ✅ User form submission - use updateTag
export async function updateProfile(formData) {
const userId = formData.get('userId');
const name = formData.get('name');
await db.user.update({
where: { id: userId },
data: { name }
});
// Immediately update cache, user sees latest data
updateTag('user-profile');
return { success: true };
}
// ✅ Like action - use updateTag
export async function likePost(postId) {
await 场景: 数据更新不需要立即对用户可见,可以在后台异步重新验证。
'use server'
import { revalidateTag } from 'next/cache';
// ✅ Scheduled tasks or webhook triggers - use revalidateTag
export async function syncDataFromAPI() {
const data = await fetchFromExternalAPI();
await
}场景: 仅更新页面的动态部分,不影响已缓存的静态外壳。
// app/actions.js
'use server'
import { refresh } from 'next/cache';
// ✅ Refresh notification count
export async function refreshNotifications() {
refresh();
return { success: true };
}
// ✅ Polling updates
export async function pollStatus() {
refresh();
}// components/notification-bell.js
'use client'
import { refreshNotifications } from '@/app/actions';
import { useEffect } from 'react';
export default function NotificationBell() {
// Auto-refresh every 30 seconds
useEffect(() => {
const interval = setInterval(() => {
refreshNotifications();
}, 30000);
return () => clearInterval(interval);
}, []);
return (
<button onClick={() => refreshNotifications()}>
🔔
</button>
);
}安全原则: 敏感数据和用户特定数据应谨慎缓存。
// ❌ Dangerous: Caching sensitive user data
"use cache"
export const cacheLife = { stale: 3600 };
export async function getUserFinancialData(userId) {
// Financial data should not be cached long-term
return await db.financialData.findUnique({ where: { userId } });
}// ✅ Safe: No cache or very short-term cache for sensitive data
export async function getUserFinancialData(userId) {
const data = await fetch(`{{// ✅ Compromise: Only cache non-sensitive aggregate data
"use cache"
export const cacheLife = { stale: 60 }; // 1-minute short-term cache
export const tags = ['user-dashboard'];
export async function getUserDashboardSummary(userId) {
// Only return aggregate stats, no sensitive details
return await db.summary.findUnique({ where: { userId } });
}策略: 根据数据层级和访问模式建立多级缓存。
// lib/cache-config.js
export const CACHE_PROFILES = {
// L1: Very short-term cache (real-time data)
REALTIME: { stale: 5, revalidate: 2 },
// L2: Short-term cache (frequently changing data)
SHORT: { stale: 60, revalidate: 30 },
// L3: Medium-term cache (periodically updated data)
MEDIUM: { stale: 300, revalidate: 120 },
// L4: Long-term cache (rarely changing data)
LONG: { stale: 3600, revalidate: 900 },
// L5: Very long-term cache (static content)
STATIC: { stale: 86400, revalidate: 3600 },
};// Usage example
"use cache"
import { CACHE_PROFILES } from '@/lib/cache-config';
export const cacheLife = CACHE_PROFILES.MEDIUM;工具: 添加缓存性能监控。
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(request) {
const start = // app/api/cache-stats/route.js
// Cache statistics API
export async function GET() {
const stats = await getCacheStats();
return Response.json({
hitRate: stats.hits / (stats.hits + stats.misses),
avgResponseTime: stats.totalTime / stats.requests,
mostCachedRoutes: stats.topRoutes
});
}策略: 为开发、预览和生产环境使用不同的缓存策略。
// lib/cache-config.js
const isDevelopment = process.env.NODE_ENV === 'development';
const isPreview = process.env.VERCEL_ENV === 'preview';
export function getCacheLife(profile) {
// Development: Disable or very short cache for debugging
if (isDevelopment) {
return { stale: 5, revalidate: 2 };
}
if (isPreview) {
return { stale: 60, revalidate: 30 };
}
// Production: Full caching strategy
}// Usage example
"use cache"
import { getCacheLife, CACHE_PROFILES } from '@/lib/cache-config';
export const cacheLife = getCacheLife(CACHE_PROFILES.LONG);
return await fetchData();
}策略: 部署后主动为关键路由预热缓存。
// scripts/warm-cache.js
const routes = [
'/',
'/about',
'/products',
'/blog'
];
async function warmCache() {
console.log('Starting cache warming...');
for (const route of routes) {
try {
const response = await fetch(`{{// package.json
{
"scripts": {
"postbuild": "node scripts/warm-cache.js"
}
}解决方案:逐步采用 "use cache":
// Old code (Next.js 15)
export const revalidate = 3600;
export default async function Page() {
const data = await fetch('答案:
'use server'
import { updateTag, revalidateTag } from 'next/cache';
// User needs to see changes immediately
export async function likePost(postId) {
await 答案:不可以。 "use cache" 只能在服务器组件和服务器函数中使用。客户端数据获取应使用 React Query 等库。
解决方案:
"use cache"
export const tags = ['debug'];
export default async function Page() {
// Add timestamp to check caching
const timestamp = new Date().toISOString();
console.log('Page rendered at:', timestamp);
return <div>Render time: {timestamp}</div>;
}在生产环境中测试:
npm run start
1. 启用 Cache Components
// next.config.ts
export default {
experimental: {
cacheComponents: true
}
}2. 更新缓存策略
// Before (Next.js 15)
export const revalidate = 3600;
// Now (Next.js 16)
"use cache"
export const cacheLife = {
stale: 3600,
revalidate: 900
}3. 使用新的缓存 API
// Before
import { revalidateTag } from 'next/cache';
revalidateTag('posts');
// Now (for instant updates)
import { updateTag } from 'next/cache';
updateTag('posts'); // In Server ActionsNext.js 16 的 Cache Components 带来革命性的缓存体验:
关键要点:
通过掌握这些新特性,你可以构建具有卓越性能和出色用户体验的现代 Web 应用。
| "use cache" + updateTag |
| { stale: 600, revalidate: 120 } |
| 实时数据(股票价格、通知) | 实时 | 不缓存或非常短期 | cache: 'no-store' 或 { stale: 5 } |
| 计算密集型数据 | 中等 | "use cache" + 长期 | { stale: 7200, revalidate: 1800 } |