캐싱 및 재검증
Next.js의 강력한 캐싱 메커니즘과 최신 콘텐츠를 제공하기 위해 캐시된 데이터를 재검증하는 방법을 이해합니다.
캐싱 및 재검증은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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
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!
자주 묻는 질문
“캐싱 및 재검증” 강의는 무료인가요?
네 — “캐싱 및 재검증” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 3개의 강의가 포함되어 있습니다.
“캐싱 및 재검증”에서 뭘 배우나요?
Next.js의 강력한 캐싱 메커니즘과 최신 콘텐츠를 제공하기 위해 캐시된 데이터를 재검증하는 방법을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.
“캐싱 및 재검증” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 서버 측 데이터 가져오기
- 캐싱 및 재검증
- 병렬·순차·스트리밍 데이터 가져오기