Caching und Revalidierung
Verstehen Sie die leistungsfähigen Caching-Mechanismen von Next.js und erfahren Sie, wie Sie gecachte Daten für aktuelle Inhalte revalidieren.
Caching und Revalidierung ist eine kostenlose Next.js 15 Fullstack (App Router + Server Actions)-Lektion auf CoddyKit. Dies ist Lektion 2 von 3. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Next.js 15 Fullstack (App Router + Server Actions)-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack (App Router + Server Actions)-Kurs umfasst insgesamt 3 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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
fetchAPI 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 allfetchrequests 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
fetchrequests 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
revalidatePathorrevalidateTagto manually refresh cached data.
Mastering these techniques is crucial for building high-performance Next.js applications!
Häufig gestellte Fragen
Ist die Lektion „Caching und Revalidierung“ kostenlos?
Ja — der vollständige Text von „Caching und Revalidierung“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Next.js 15 Fullstack (App Router + Server Actions)-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack (App Router + Server Actions)-Kurs umfasst insgesamt 3 Lektionen.
Was lerne ich in „Caching und Revalidierung“?
Verstehen Sie die leistungsfähigen Caching-Mechanismen von Next.js und erfahren Sie, wie Sie gecachte Daten für aktuelle Inhalte revalidieren. Du übst Next.js 15 Fullstack (App Router + Server Actions) mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Next.js 15 Fullstack (App Router + Server Actions) zu starten?
Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack (App Router + Server Actions) auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 3.
Wie lange dauert die Lektion „Caching und Revalidierung“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Next.js 15 Fullstack (App Router + Server Actions)-Lektion Code schreiben und ausführen?
Ja. Jede Next.js 15 Fullstack (App Router + Server Actions)-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Serverseitiger Datenabruf
- Caching und Revalidierung
- Paralleles, sequenzielles und gestreamtes Abrufen von Daten