0
0
NextjsHow-ToBeginner · 4 min read

How Caching Works in Next.js: Simple Explanation and Examples

In Next.js, caching happens automatically for static pages and API routes using Incremental Static Regeneration (ISR) and Static Site Generation (SSG). You can control caching behavior with revalidate in getStaticProps or HTTP headers for API routes to keep content fresh without rebuilding the whole site.
📐

Syntax

Next.js caching mainly uses getStaticProps with a revalidate option for Incremental Static Regeneration (ISR). This tells Next.js how often to update the cached page.

Example parts:

  • getStaticProps: Fetches data at build time.
  • revalidate: Number of seconds before Next.js regenerates the page.
javascript
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json())
  return {
    props: { data },
    revalidate: 60, // Regenerate page every 60 seconds
  }
}
💻

Example

This example shows a Next.js page using ISR to cache data for 30 seconds. The page fetches data at build time and updates the cache every 30 seconds automatically.

javascript
import React from 'react'

export async function getStaticProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')
  const post = await res.json()

  return {
    props: { post },
    revalidate: 30, // Cache page for 30 seconds
  }
}

export default function Post({ post }) {
  return (
    <main>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </main>
  )
}
Output
<h1>sunt aut facere repellat provident occaecati excepturi optio reprehenderit</h1><p>quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto</p>
⚠️

Common Pitfalls

Common mistakes when using caching in Next.js include:

  • Not setting revalidate in getStaticProps, which disables ISR and causes stale content.
  • Using getServerSideProps when static caching would be better for performance.
  • Forgetting to set proper HTTP cache headers on API routes, leading to no caching or excessive caching.

Example of wrong and right usage:

javascript
// Wrong: No revalidate, page never updates after build
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json())
  return { props: { data } }
}

// Right: Revalidate every 60 seconds to update cache
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json())
  return {
    props: { data },
    revalidate: 60,
  }
}
📊

Quick Reference

FeatureDescriptionUsage
Static Site Generation (SSG)Builds pages at build time, cached forever until next buildUse getStaticProps without revalidate
Incremental Static Regeneration (ISR)Updates static pages after build at a set intervalUse getStaticProps with revalidate seconds
Server-Side Rendering (SSR)Generates page on each request, no caching by defaultUse getServerSideProps
API Route CachingControl cache with HTTP headers like Cache-ControlSet headers in API route response

Key Takeaways

Next.js caches static pages automatically using SSG and ISR with the revalidate option.
Set revalidate in getStaticProps to control how often cached pages update.
Avoid SSR if caching static content is possible to improve performance.
Use HTTP cache headers in API routes to manage caching behavior.
Not setting caching options can cause stale content or unnecessary server load.