Next.js Caching & Revalidation — Keeping Data Fresh
Next.js, fetch() results ని automatic గా cache చేస్తుంది — same URL కి request వచ్చినప్పుడు, network call చేయకుండా cached response return చేస్తుంది. Idి production sites ni chాలా fast చేస్తుంది, kani "stale data" (పాత data) చూపించే risk కూడా ఉంటుంది.
Data ని oka fixed time interval తర్వాత automatic గా refresh చేయాలంటే, revalidate option వాడతారు — దీన్నే ISR (Incremental Static Regeneration) అంటారు:
async function getProducts() {
const res = await fetch("https://api.example.com/products", {
next: { revalidate: 60 },
});
return res.json();
}
next: {"{"}revalidate: 60{"}"} — cached data ni 60 seconds వరకు reuse చేస్తుంది. 60 seconds దాటిన తర్వాత next request వచ్చినప్పుడు, background లో fresh data fetch అయ్యి cache update అవుతుంది.
Content update అయినప్పుడు (example: admin ఒక product edit చేసినప్పుడు) వెంటనే cache clear చేయాలంటే, revalidatePath లేదా revalidateTag వాడతారు — usually Server Action లేదా Route Handler లోపల:
"use server";
import { revalidatePath } from "next/cache";
export async function updateProduct(id: string) {
// ... update database logic here
revalidatePath("/products");
}
revalidatePath("/products"), /products route cache ni immediately invalidate చేస్తుంది — next visit లో fresh data fetch అవుతుంది.
| Function | Use When |
|---|---|
revalidatePath("/products") | Specific route/page ni target చేయాలి |
revalidateTag("products") | Multiple pages లో same tagged data ni ఒకేసారి invalidate చేయాలి |
Tags వాడాలంటే, fetch call లో {"{"}next: {"{"}tags: ["products"]{"}"}{"}"} add చేయాలి.
Database update చేసిన తర్వాత revalidatePath/revalidateTag call చేయకపోతే, users కి పాత (stale) data కనిపిస్తూనే ఉంటుంది — cache manual గా clear అయ్యే వరకు (leda time-based revalidate వరకు) update కనిపించదు.
Write a fetch call for a 'blog posts' list that revalidates every 300 seconds (5 minutes).
async function getPosts() {
const res = await fetch("https://api.example.com/posts", {
next: { revalidate: 300 },
});
return res.json();
}
Q revalidate: 0 అంటే ఏమిటి?
revalidate: 0, cache ని పూర్తిగా disable చేసి, prathi request కి fresh data fetch చేస్తుంది (SSR laాంటి behavior). Real-time data (stock prices, live scores) కి useful.
Q revalidatePath ఏ context లో వాడాలి?
ఇది Server Actions లేదా Route Handlers లోపల matrame వాడాలి — regular Server Component render logic లో వాడకూడదు.
Q Time-based, on-demand revalidation కలిపి వాడొచ్చా?
Avunu. Common pattern: fetch కి baseline revalidate (e.g., 3600 seconds/1 hour) pెట్టి, content update అయినప్పుడు revalidatePath తో వెంటనే fresh చేయడం — best of both worlds.