Caching and Revalidation

πŸ“˜ Next.js πŸ‘ 37 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

Next.js provides powerful caching and revalidation mechanisms to improve performance, reduce server load, and ensure fresh data. These are especially important in the App Router where server-side rendering and static generation are heavily used.


1. Default Caching Behavior

By default, fetch() in Next.js caches requests for static generation.

const res = await fetch('https://api.example.com/posts');
  • Cached at build time for static pages.

  • Suitable for content that doesn’t change often.


2. Static Rendering with next: { revalidate }

Use Incremental Static Regeneration (ISR) to revalidate data at intervals.

const res = await fetch('https://api.example.com/posts', { next: { revalidate: 60 }, // revalidate every 60 seconds });
  • Page regenerates in the background after specified seconds.

  • Combines the speed of static pages with freshness.


3. Dynamic Rendering (cache: 'no-store')

Fetch fresh data on every request.

const res = await fetch('https://api.example.com/posts', { cache: 'no-store', });
  • Always returns up-to-date data.

  • Ideal for dashboards, user-specific content, or real-time apps.


4. Revalidation After a Request

const res = await fetch('https://api.example.com/posts', { next: { revalidate: 0 }, // immediate revalidation });
  • Forces rebuild on every request but still benefits from static caching when possible.


5. Server-Side Caching Headers

Set HTTP caching headers in API responses:

export async function GET() { const posts = await fetchPosts(); return new Response(JSON.stringify(posts), { headers: { 'Cache-Control': 's-maxage=60, stale-while-revalidate=30', }, }); }
  • s-maxage: Cache on CDN/edge

  • stale-while-revalidate: Serve stale content while revalidating


6. Caching Strategies Summary

StrategyNext.js SettingUse Case
StaticDefault fetchBlog, landing pages
ISRnext: { revalidate: seconds }Frequently updated content
Dynamiccache: 'no-store'Dashboards, user-specific pages
Edge cachingCache-Control headersAPI responses, CDNs

7. Best Practices

  • Use ISR for pages that update often but not every second.

  • Use dynamic rendering for user-specific or sensitive data.

  • Combine server-side caching headers with Next.js revalidation.

  • Minimize unnecessary re-fetching for performance.


Conclusion

Caching and revalidation in Next.js help build fast, scalable, and fresh web applications. By understanding static, ISR, and dynamic caching, you can optimize both performance and user experience.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes