服务器端缓存策略
学习使用 `fetch` 选项和重新验证在服务器上缓存数据,以提升性能。
服务器端缓存策略 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Server-Side Caching?
In Next.js, server-side caching is crucial for building fast and efficient web applications. It helps reduce load times and server strain.
- Performance: Delivers content faster to users.
- Cost Reduction: Less frequent data fetches mean fewer API calls, potentially saving money.
- Scalability: Handles more users without overloading your backend.
We'll explore how Next.js leverages the native fetch API for powerful caching.
Next.js `fetch` & Caching Defaults
When you use the native fetch API in Next.js Server Components, it automatically caches data by default. This is like having a built-in data store.
By default, fetch requests are cached using the 'force-cache' strategy. This means Next.js will look for a cached response first and use it if available, only fetching new data if no cache entry exists.
Disabling Cache: `cache: 'no-store'`
Sometimes, you need to ensure data is always fresh, like for real-time dashboards or sensitive user information. For these cases, you can disable caching for specific fetch requests.
Using cache: 'no-store' tells Next.js to always fetch fresh data from the origin server and never store it in the cache. This is useful for highly dynamic or frequently changing content.
`no-store` in Action
Here's how you'd use cache: 'no-store' in a Server Component to ensure you always get the latest user data.
async function getUserProfile(userId) {
const res = await fetch(`https://api.example.com/users/${userId}`, {
cache: 'no-store' // Always fetch fresh data
});
if (!res.ok) {
throw new Error('Failed to fetch user profile');
}
return res.json();
}
export default async function ProfilePage({ params }) {
const user = await getUserProfile(params.userId);
return (
<div>
<h1>Welcome, {user.name}</h1>
<p>Email: {user.email}</p>
</div>
);
}Time-Based Revalidation
For data that changes periodically but not constantly, you can use time-based revalidation. This strategy is also known as "stale-while-revalidate".
You can specify a revalidate option within fetch's next property. It tells Next.js how often (in seconds) to re-fetch data in the background, serving cached data in the meantime.
next: { revalidate: 60 }: Data will be re-fetched at most every 60 seconds.
Revalidate Option Example
Let's say you have a blog post that updates every few minutes. You can use revalidate to keep it fresh without hitting the API on every single request.
async function getBlogPost(slug) {
const res = await fetch(`https://api.example.com/posts/${slug}`, {
next: { revalidate: 3600 } // Revalidate every hour
});
if (!res.ok) {
throw new Error('Failed to fetch blog post');
}
return res.json();
}
export default async function BlogPostPage({ params }) {
const post = await getBlogPost(params.slug);
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}On-Demand Revalidation
What if you want to update cached data immediately after a change, like when a user publishes a new post? This is where on-demand revalidation comes in.
Next.js provides two functions for this:
revalidatePath('/path'): Invalidates the cache for a specific path.revalidateTag('tag'): Invalidates the cache for all fetches associated with a specific tag.
These are typically used in Server Actions or API Routes after a data mutation.
Using `revalidateTag`
To use revalidateTag, you first need to tag your fetch requests. Then, from a Server Action or API Route, you can trigger a revalidation for that tag.
This allows fine-grained control over your cache, only clearing what's necessary when data actually changes.
async function getProducts() {
const res = await fetch('https://api.example.com/products', {
next: { tags: ['products'] } // Tag this fetch request
});
if (!res.ok) {
throw new Error('Failed to fetch products');
}
return res.json();
}
// In a Server Action or API Route after adding/updating a product:
// import { revalidateTag } from 'next/cache';
// revalidateTag('products'); // Invalidate all fetches tagged 'products'
export default async function ProductsPage() {
const products = await getProducts();
return (
<div>
<h1>Our Products</h1>
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}Choosing the Right Strategy
Selecting the best caching strategy depends on your data's volatility:
cache: 'no-store': For highly dynamic, real-time, or sensitive data that must always be fresh.next: { revalidate: N }: For data that updates periodically (e.g., news articles, blog posts) where some staleness is acceptable.revalidatePath/revalidateTag: For data that changes unpredictably, often due to user actions (e.g., comments, e-commerce inventory), requiring immediate updates after mutation.
Caching Strategy Check
You are building a social media feed where posts are created and updated frequently. You want to ensure users see the latest posts without excessive API calls. Which caching strategy is most suitable for fetching the main feed?
Recap: Server-Side Caching
We've explored key server-side caching strategies in Next.js using the fetch API:
- Default Caching:
fetchuses'force-cache'by default. - Disabling Cache: Use
cache: 'no-store'for always-fresh data. - Time-Based Revalidation: Use
next: { revalidate: N }for stale-while-revalidate. - On-Demand Revalidation: Use
revalidatePath()orrevalidateTag()in Server Actions/API Routes for immediate cache updates.
Mastering these techniques allows you to build highly performant and responsive Next.js applications!
常见问题解答
「服务器端缓存策略」课时是免费的吗?
是的 — 「服务器端缓存策略」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
「服务器端缓存策略」这节课中我会学到什么?
学习使用 `fetch` 选项和重新验证在服务器上缓存数据,以提升性能。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「服务器端缓存策略」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。