
Caching in NextJS
π Caching in Next.js
Next.js provides multiple caching mechanisms to optimize performance and reduce server load. These include Static Generation (SSG), Incremental Static Regeneration (ISR), API Response Caching, Image Optimization, and Edge Caching.
π 1. Static Page Caching (SSG)
Static Site Generation (SSG) pre-builds pages at build time and serves them as static files.
πΉ Example: Static Caching with getStaticProps
export async function getServerSideProps({ res }) { res.setHeader("Cache-Control", "s-maxage=60, stale-while-revalidate=30"); const resData = await fetch("https://api.example.com/data"); const data = await resData.json(); return { props: { data } };}
s-maxage=60
: Cache for 60 seconds.stale-while-revalidate=30
: Serve stale content for 30 seconds while updating the cache in the background.
π 4. API Response Caching
Next.js API routes donβt cache responses by default. However, you can use CDN caching or Redis for better performance.
πΉ Example: API Response with Cache Headers
export default async function handler(req, res) { res.setHeader("Cache-Control", "public, s-maxage=300, stale-while-revalidate=60"); const data = await fetch("https://api.example.com/data").then((res) => res.import redis from "redis";const client = redis.createClient();export default async function handler(req, res) { const cacheKey = "api:data"; client.get(cacheKey, async (err, cachedData) => { if (cachedData) { return res.status(200).json(JSON.parse(cachedData)); } const data = await fetch("https://api.example.com/data").then((res) => res.import Image from "next/image";export default function Home() { return <Image src="/image.jpg" width={500} height={300} quality={75} priority />;}
CDN cached automatically.
Supports lazy loading and automatic resizing.
π 6. Edge & CDN Caching
Vercelβs Edge Network caches pages and API responses globally.
Can be configured with Cache-Control headers.
πΉ Example: Full-Page Edge Caching
export async function getServerSideProps({ res }) { res.setHeader("Cache-Control", "public, s-maxage=86400, stale-while-revalidate=3600"); return { props: { time: new Date().toISOString() } };}
Caches the response at the edge for 1 day (
s-maxage=86400
).Serves stale content while revalidating for 1 hour (
stale-while-revalidate=3600
).
π Summary
Feature | Type | When to Use | Cache Duration |
---|---|---|---|
SSG (getStaticProps ) | Build Time | Static content | Until next build |
ISR (getStaticProps with revalidate ) | Build Time | Dynamic but cacheable content | Configurable |
SSR (getServerSideProps ) | Request Time | Per-user content | Can be cached via headers |
API Response Caching | Request Time | API optimization | Can use Redis/CDN |
Image Caching (next/image ) | Build Time | Optimized images | CDN cached |
Edge Caching (Vercel) | Request Time | Full-page caching | Configurable |