ELEVATE YOUR BUSINESS WITH

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

Caching in NextJS

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

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

javascript

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

javascript

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

javascript

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

FeatureTypeWhen to UseCache Duration
SSG (getStaticProps)Build TimeStatic contentUntil next build
ISR (getStaticProps with revalidate)Build TimeDynamic but cacheable contentConfigurable
SSR (getServerSideProps)Request TimePer-user contentCan be cached via headers
API Response CachingRequest TimeAPI optimizationCan use Redis/CDN
Image Caching (next/image)Build TimeOptimized imagesCDN cached
Edge Caching (Vercel)Request TimeFull-page cachingConfigurable

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