
Data Caching in NextJS
🚀 Data Caching in Next.js
Caching in Next.js improves performance by reducing redundant data fetching and speeding up page loads. Next.js offers multiple caching strategies depending on your use case.
📌 1. Caching with getStaticProps
(SSG)
getStaticProps
fetches data at build time and caches it. The page remains static unless manually revalidated.
🔹 Example: Static Page with Cached API Data
export async function getServerSideProps({ res }) { res.setHeader("Cache-Control", "s-maxage=60, stale-while-revalidate=300"); const data = await fetch("https://api.example.com/data").then((res) => res.export default async function handler(req, res) { res.setHeader("Cache-Control", "s-maxage=60, stale-while-revalidate=300"); const data = await fetch("https://api.example.com/data").then((res) => res.import useSWR from "swr";const fetcher = (url) => fetch(url).then((res) => res.<p>Error loading data<p>Loading...<pre>{JSON.stringify(data, null, 2)}import Redis from "ioredis";const redis = new Redis(process.env.REDIS_URL);export default async function handler(req, res) { const cachedData = await redis.get("myData"); if (cachedData) { return res.status(200).json(JSON.parse(cachedData)); } const data = await fetch("https://api.example.com/data").then((res) => res.json()); await redis.set("myData", JSON.stringify(data), "EX", 60); // Cache for 60 seconds res.status(200).json(data);}
✅ Speeds up API responses
✅ Ideal for high-traffic applications
📌 7. Next.js Middleware for Edge Caching
Next.js Edge Middleware can modify requests before reaching the origin server, enabling smarter caching.
🔹 Example: Middleware with Cache-Control
import { NextResponse } from "next/server";export function middleware(req) { const res = NextResponse.next(); res.headers.set("Cache-Control", "s-maxage=600, stale-while-revalidate=3600"); return res;}
✅ Improves performance by caching requests
✅ Runs at the edge (near users)
📌 Summary: Choosing the Right Caching Strategy
Caching Method | Best For | Performance |
---|---|---|
SSG (getStaticProps ) | Static pages, blogs | ⚡ Super fast |
ISR (revalidate ) | Semi-static content (news, articles) | 🚀 Fast |
SSR (getServerSideProps ) | Dynamic, always fresh data | ⏳ Slower |
API Route Caching (Cache-Control ) | Server-side caching | 🚀 Fast |
Client-Side SWR | Frequently changing UI data | ⚡ Optimized |
Redis Caching | High-traffic, persistent caching | 🔥 Very fast |
Edge Middleware | Intelligent caching at the edge | 🌍 Global speed |