
Full Route Caching in NextJS
π Full Route Caching in Next.js
Full Route Caching in Next.js improves performance by storing entire pages in memory or on the edge, reducing server processing and speeding up page loads.
π 1. How Next.js Caches Routes
Next.js automatically caches statically generated pages (SSG) and revalidates them based on configuration.
Static Generation (SSG) β Cached at build time
Incremental Static Regeneration (ISR) β Cached and updated periodically
Server-Side Rendering (SSR) β No caching by default
Client-Side Rendering (CSR) β Handled by the browser
π 2. Enabling Full Route Caching
πΉ Using getStaticProps
(SSG)
Pages generated at build time are cached indefinitely unless manually revalidated.
export async function getStaticProps() { return { props: { data: "Cached at build time" }, };}
β Pages are cached and served instantly
πΉ Using Incremental Static Regeneration (ISR)
Update cached pages without a full rebuild by adding revalidate
:
export async function getStaticProps() { return { props: { data: "This page is cached and updates every 10 seconds" }, revalidate: 10, // Revalidate after 10 seconds };}
β Reduces server load while keeping content fresh
π 3. Full Route Caching for API Routes
By default, API routes donβt cache responses. Use Edge Middleware or a caching header:
export default function handler(req, res) { res.setHeader("Cache-Control", "s-maxage=3600, stale-while-revalidate"); res.json({ message: "Cached API response" });}
β
Caches API response for 1 hour (s-maxage=3600
)
π 4. Middleware-Based Caching
You can use Edge Middleware to cache routes dynamically:
import { NextResponse } from "next/server";export function middleware(req) { const res = NextResponse.next(); res.headers.set("Cache-Control", "s-maxage=3600, stale-while-revalidate"); return res;}
β Useful for caching dynamic routes
π 5. Optimizing with next.config.js
Modify next.config.js
for better caching control:
module.exports = { async headers() { return [ { source: "/:path*", headers: [ { key: "Cache-Control", value: "s-maxage=3600, stale-while-revalidate" }, ], }, ]; },};
β Applies cache headers to all routes
π 6. Best Practices for Full Route Caching
βοΈ Use ISR (revalidate
) to avoid unnecessary rebuilds
βοΈ Leverage API caching (s-maxage
, stale-while-revalidate
)
βοΈ Use Edge Middleware for dynamic caching
βοΈ Avoid caching user-specific or private pages