ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Data Caching in NextJS

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='21' AND `tutorial_submenu`='1761' AND `tutorial_status`=1 LIMIT 1

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

javascript

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

javascript

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 MethodBest ForPerformance
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 SWRFrequently changing UI data⚡ Optimized
Redis CachingHigh-traffic, persistent caching🔥 Very fast
Edge MiddlewareIntelligent caching at the edge🌍 Global speed

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql