
Router Caching in NextJS
🚀 Router Caching in Next.js
Router Caching in Next.js helps optimize navigation and improve page load speeds by storing previously visited pages, reducing redundant network requests, and minimizing re-renders.
📌 1. Why Use Router Caching?
✔️ Improves navigation speed by avoiding unnecessary data fetching
✔️ Reduces API calls when switching between pages
✔️ Enhances performance by caching pre-rendered pages
📌 2. Automatic Caching in Next.js
By default, Next.js caches pre-rendered pages for optimization.
🔹 Static Pages are Cached Automatically
Pages built with
getStaticProps()
are cached and served instantly.No re-fetching unless manually invalidated.
<nav> import useSWR from "swr";const fetcher = (url) => fetch(url).then((res) => res.<p>Error loading data<p>Loading...<pre>{JSON.stringify(data, null, 2)}</pre>;}
✅ Caches API responses for faster page loads
✅ Avoids re-fetching data when revisiting the page
📌 5. Full Route Caching with Middleware
Use middleware caching to intercept requests and serve cached pages.
🔹 Example: Implementing Router Cache in Middleware
import { NextResponse } from "next/server";const cache = new Map();export function middleware(req) { const { pathname } = req.nextUrl; if (cache.has(pathname)) { return NextResponse.json(cache.get(pathname)); // Return cached response } const response = NextResponse.next(); cache.set(pathname, response.clone()); // Store response in cache return response;}
✅ Caches full pages for quick responses
✅ Prevents redundant requests to the server
📌 6. Custom Cache-Control Headers
Manually control router caching using HTTP headers.
🔹 Example: Setting Cache Headers in API Routes
export default function handler(req, res) { res.setHeader("Cache-Control", "s-maxage=3600, stale-while-revalidate=600"); res.status(200).json({ message: "Cached for 1 hour" });}
✅ Caches response for 1 hour (s-maxage=3600
)
✅ Allows stale data while fetching new data (stale-while-revalidate
)
📌 7. Router Caching in next.config.js
Define custom caching rules for your Next.js app.
🔹 Example: Cache API Responses Globally
module.exports = { async headers() { return [ { source: "/api/:path*", headers: [ { key: "Cache-Control", value: "s-maxage=600, stale-while-revalidate" }, ], }, ]; },};
✅ Caches all API requests for 10 minutes
✅ Prevents unnecessary re-fetching
🚀 Summary: Router Caching Methods
Method | Use Case | Cache Type |
---|---|---|
getStaticProps() | Cache pre-rendered pages | ISR (Static) |
next/link prefetching | Preloads linked pages | Client-side |
SWR | Cache API requests | Client-side |
Middleware Cache | Full page caching | Server-side |
Cache-Control Headers | Fine-grained caching | Server-side |
next.config.js Headers | Global caching rules | Server-side |