Concept Flow - Cache invalidation strategies
Start: Data Cached
Check Cache Validity
Use Cache
Fetch Fresh Data
Update Cache
End
This flow shows how cache is checked for validity, used if valid, or invalidated and refreshed if not.
export async function getStaticProps() { const data = await fetchData() return { props: { data }, revalidate: 10, } }
| Step | Action | Cache State | Condition | Result |
|---|---|---|---|---|
| 1 | Initial build | Cache empty | No cache | Fetch data and cache it |
| 2 | Request at 5s | Cache valid | 5 < 10 seconds | Use cached data |
| 3 | Request at 12s | Cache expired | 12 > 10 seconds | Invalidate cache and fetch fresh data |
| 4 | Request at 15s | Cache valid | 3 seconds since last fetch < 10 | Use cached data |
| 5 | Request at 25s | Cache expired | 10 seconds since last fetch | Invalidate cache and fetch fresh data |
| 6 | End | Cache updated | N/A | Stop |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|---|---|
| cacheTimestamp | null | 0s (build time) | 0s (still valid) | 12s (updated) | 12s (valid) | 25s (updated) | 25s |
| cacheData | null | data fetched | data reused | data refreshed | data reused | data refreshed | data refreshed |
Cache Invalidation Strategies in Next.js: - Use revalidate in getStaticProps to set cache lifetime. - Cache is valid until revalidate seconds pass. - After expiry, cache is invalidated and fresh data fetched. - This keeps data fresh without rebuilding every request. - Helps balance speed and data accuracy.
getStaticProps generates static pages at build time, but with revalidate, it can update pages after a set interval.getServerSideProps fetches fresh data on every request but does not use caching or revalidation intervals.getStaticProps with revalidate -> Option DgetStaticProps + revalidate [OK]getServerSideProps with revalidationgetStaticProps?revalidate as the property to set seconds for incremental static regeneration.getStaticProps must include props and optionally revalidate with a number value.revalidate [OK]export async function getStaticProps() {
return {
props: { time: Date.now() },
revalidate: 5
};
}revalidate: 5 means Next.js will regenerate the page at most every 5 seconds.export async function getStaticProps() {
return {
props: { data: await fetchData() },
revalidate: '10'
};
}revalidaterevalidate property expects a number representing seconds, not a string.revalidate must be a number, not a string -> Option AgetServerSideProps runs on the server for every page request, ensuring fresh data.getStaticProps generates static pages at build time or with revalidation intervals, so it does not guarantee fresh data every request.getServerSideProps because it runs on every request -> Option CgetServerSideProps [OK]Pass the test and this pattern moves unknown