Loading Blog Article...
Loading Blog Article...
Loading Blog Article...
Next.js 16 introduces a major paradigm shift in caching:
Next.js 16's caching system includes the following layers:
This is a built-in feature of React 18+ that automatically deduplicates identical requests during the same render cycle.
// app/page.js
async function getUser(id) {
// This function is called multiple times in the same render
const res = await fetch(`{{Cache Components is the most important new feature in Next.js 16, implementing explicit caching through the "use cache" directive.
First, enable it in the configuration file:
// 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;
}Configure cache duration and revalidation strategies using 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('Preset Cache Life Profiles:
// 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 introduces new cache management APIs for more granular control.
updateTag() is a Server Actions-only API that provides "read-your-writes" semantics, allowing users to immediately see their changes:
// 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() refreshes uncached real-time data without affecting cached content:
// 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() now works with cacheLife configuration, supporting stale-while-revalidate (SWR) behavior:
// 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');
}In Next.js 16, all dynamic code executes at request time by default. You need to use "use cache" to explicitly enable caching.
While "use cache" is recommended, fetch cache options are still valid:
// 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>;
}Client-side route caching behavior remains unchanged.
'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 don't cache by default, requiring explicit enablement:
// 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 buildBuild output shows rendering method for each route:
Why: "use cache" provides clearer, unified caching semantics, and the compiler can automatically optimize cache key generation.
// ✅ 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('
}Best Practice: Establish clear tag naming conventions using hierarchical structure.
// ✅ 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');Tag Naming Convention Example:
// 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 PerformanceStrategy: Separate pages into static shells and dynamic content, leveraging Partial Prerendering for best initial load performance.
// 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('Performance Tip: With PPR, the static shell displays immediately while dynamic parts stream, significantly reducing user-perceived load time.
Decision Tree:
| Data Type | Update Frequency | Recommended Strategy | cacheLife Config |
|---|---|---|---|
| Static content (About page, FAQ) | Rarely | "use cache" | { stale: 86400 } |
| Blog posts, Product listings | Daily/Weekly | "use cache" + ISR | { stale: 3600, revalidate: 900 } |
| User-generated content | Frequently | "use cache" + tags | { stale: 300, revalidate: 60 } |
Example: E-commerce Product Page Mixed Strategy
// 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/>Scenario: User performs an action and expects to see results immediately (form submission, likes, comments, etc.).
// 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 Scenario: Data updates don't need to be immediately visible to users, can be revalidated asynchronously in the background.
'use server'
import { revalidateTag } from 'next/cache';
// ✅ Scheduled tasks or webhook triggers - use revalidateTag
export async function syncDataFromAPI() {
const data = await fetchFromExternalAPI();
await
}Scenario: Only update dynamic parts of the page without affecting cached static shell.
// 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>
);
}Security Principle: Sensitive data and user-specific data should be cached cautiously.
// ❌ 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 } });
}Strategy: Establish multi-level caching based on data hierarchy and access patterns.
// 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;Tools: Add cache performance monitoring.
// 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
});
}Strategy: Use different caching strategies for development, preview, and production environments.
// 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();
}Strategy: Proactively warm cache for critical routes after deployment.
// 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"
}
}Solution: Gradually adopt "use cache":
// Old code (Next.js 15)
export const revalidate = 3600;
export default async function Page() {
const data = await fetch('Answer:
'use server'
import { updateTag, revalidateTag } from 'next/cache';
// User needs to see changes immediately
export async function likePost(postId) {
await Answer: No. "use cache" can only be used in Server Components and Server Functions. Client-side data fetching should use libraries like React Query.
Solution:
"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>;
}Test in production:
npm run start
1. Enable Cache Components
// next.config.ts
export default {
experimental: {
cacheComponents: true
}
}2. Update Caching Strategy
// Before (Next.js 15)
export const revalidate = 3600;
// Now (Next.js 16)
"use cache"
export const cacheLife = {
stale: 3600,
revalidate: 900
}3. Use New Caching APIs
// Before
import { revalidateTag } from 'next/cache';
revalidateTag('posts');
// Now (for instant updates)
import { updateTag } from 'next/cache';
updateTag('posts'); // In Server ActionsNext.js 16's Cache Components bring revolutionary caching experience:
Key Takeaways:
By mastering these new features, you can build modern web applications with excellent performance and outstanding user experience.
| Medium |
| "use cache" + updateTag |
| { stale: 600, revalidate: 120 } |
| Real-time data (Stock prices, Notifications) | Real-time | No cache or very short-term | cache: 'no-store' or { stale: 5 } |
| Compute-intensive data | Medium | "use cache" + long-term | { stale: 7200, revalidate: 1800 } |