0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 课时

缓存与重新验证

了解 Next.js 强大的缓存机制,以及如何重新验证缓存数据以获取最新内容

缓存与重新验证 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 3 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Caching Matters

Caching is a fundamental technique to improve the performance and responsiveness of web applications.

Imagine fetching the same data repeatedly from a database or an API. This creates unnecessary load and slows down your app.

Caching stores a copy of frequently accessed data, so it can be served faster on subsequent requests, reducing latency and resource usage.

Built-in Data Cache

Next.js 15, especially with the App Router, comes with powerful built-in caching mechanisms.

  • It intelligently caches data fetched using the native fetch API within Server Components.
  • This cache is stored on the server, ensuring faster responses for repeat visitors or multiple requests for the same data.
  • It helps your application deliver content quickly without constant re-fetching.

`fetch` Defaults in Server Components

When you use the standard fetch API inside a Next.js Server Component, Next.js automatically caches the data.

This means if the same fetch request is made again, Next.js will serve the data from its cache instead of hitting the external API.

This behavior is optimized for scenarios where data doesn't change frequently and can significantly boost performance.

Try Default Caching

Here's a simple example of a Server Component fetching data. Notice how Next.js caches the result implicitly.

If you were to run this and refresh, the fetch call might not hit the external API again immediately, depending on the cache lifetime.

// app/page.js
async function getUserData() {
  // This fetch request is automatically cached by Next.js
  const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
  if (!res.ok) {
    throw new Error('Failed to fetch user data');
  }
  return res.json();
}

export default async function HomePage() {
  const user = await getUserData();
  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: {user.name}</p>
      <p>Email: {user.email}</p>
      <p>Fetched at: {new Date().toLocaleTimeString()}</p>
    </div>
  );
}

Bypassing the Cache

Sometimes, you need to ensure data is always fresh and not served from the cache. For instance, when displaying real-time stock prices or user-specific data that changes often.

You can opt out of caching for a specific fetch request by setting the cache option to 'no-store'.

  • fetch('...', { cache: 'no-store' }) tells Next.js to always re-fetch data.
  • This ensures you get the latest information every time.

Try Bypassing Cache

This example demonstrates how to explicitly bypass the cache. Each time this component renders, a new request will be made to the API.

// app/live-data/page.js
async function getLiveTime() {
  // This fetch request explicitly opts out of caching
  const res = await fetch('https://worldtimeapi.org/api/ip', {
    cache: 'no-store', // Always re-fetch
  });
  if (!res.ok) {
    throw new Error('Failed to fetch live time');
  }
  return res.json();
}

export default async function LiveDataPage() {
  const timeData = await getLiveTime();
  return (
    <div>
      <h1>Live Time</h1>
      <p>Current time in your timezone:</p>
      <p><b>{new Date(timeData.datetime).toLocaleTimeString()}</b></p>
      <p>Last fetched: {new Date().toLocaleTimeString()}</p>
    </div>
  );
}

Revalidating Data Over Time

What if you want data to be cached but refresh after a certain period? Next.js supports time-based revalidation, similar to Incremental Static Regeneration (ISR).

You can specify a revalidate option within the next property of your fetch call:

  • fetch('...', { next: { revalidate: 60 } }) will cache the data for 60 seconds.
  • After 60 seconds, the next request will trigger a re-fetch in the background, serving stale data first, then fresh data.

Try Time-based Revalidation

In this example, the data will be cached for 10 seconds. If you refresh the page within 10 seconds, you'll see the cached time. After 10 seconds, a new fetch will occur.

// app/revalidated-data/page.js
async function getRevalidatedData() {
  // Data will be revalidated every 10 seconds
  const res = await fetch('https://worldtimeapi.org/api/timezone/Etc/UTC', {
    next: { revalidate: 10 }, // Revalidate after 10 seconds
  });
  if (!res.ok) {
    throw new Error('Failed to fetch revalidated data');
  }
  return res.json();
}

export default async function RevalidatedPage() {
  const data = await getRevalidatedData();
  return (
    <div>
      <h1>Revalidated UTC Time</h1>
      <p>Current UTC Time: <b>{new Date(data.datetime).toLocaleTimeString()}</b></p>
      <p>This data revalidates every 10 seconds.</p>
      <p>Last rendered: {new Date().toLocaleTimeString()}</p>
    </div>
  );
}

Manual Revalidation

Beyond time-based revalidation, Next.js also allows you to revalidate cached data manually, or "on-demand".

  • revalidatePath('/path'): Revalidates the cache for a specific page path.
  • revalidateTag('tag'): Revalidates all fetch requests that were tagged with a specific string (e.g., fetch('...', { next: { tags: ['products'] } })).

This is useful when data changes due to a user action (e.g., updating a product) and you want to ensure the UI shows the latest information immediately.

Test Your Knowledge

Which of the following Next.js fetch options ensures that data is ALWAYS fetched from the origin server on every request, bypassing any cache?

Caching & Revalidation Recap

In this lesson, you learned about Next.js's powerful data caching mechanisms.

  • Next.js caches fetch requests in Server Components by default.
  • You can bypass the cache with { cache: 'no-store' } for real-time data.
  • Time-based revalidation (ISR) is achieved with { next: { revalidate: N } }.
  • On-demand revalidation uses revalidatePath or revalidateTag to manually refresh cached data.

Mastering these techniques is crucial for building high-performance Next.js applications!

常见问题解答

「缓存与重新验证」课时是免费的吗?

是的 — 「缓存与重新验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 3 节课。

「缓存与重新验证」这节课中我会学到什么?

了解 Next.js 强大的缓存机制,以及如何重新验证缓存数据以获取最新内容 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「缓存与重新验证」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 服务端数据获取
  2. 缓存与重新验证
  3. 并行、串行与流式数据获取
← 返回 Next.js 15 Fullstack (App Router + Server Actions)