0
0
NextJSframework~5 mins

Cache invalidation strategies in NextJS

Choose your learning style9 modes available
Introduction

Cache invalidation strategies help keep your app's data fresh by deciding when to update or remove stored data. This avoids showing old information to users.

When you fetch data that changes often, like user profiles or news feeds.
When you want to improve app speed but still show up-to-date content.
When you use Next.js data fetching methods like <code>getStaticProps</code> or <code>getServerSideProps</code>.
When you cache API responses or images and need to refresh them after updates.
When you want to balance between fast loading and accurate data.
Syntax
NextJS
export async function getStaticProps() {
  const data = await fetchData()
  return {
    props: { data },
    revalidate: 60 // seconds
  }
}

The revalidate key tells Next.js to update the cached page after the given seconds.

This is called Incremental Static Regeneration (ISR) in Next.js.

Examples
This example fetches posts and refreshes the cache every 10 seconds.
NextJS
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/posts').then(res => res.json())
  return {
    props: { posts: data },
    revalidate: 10 // update cache every 10 seconds
  }
}
This fetches fresh data on every request, so no caching is needed.
NextJS
export async function getServerSideProps() {
  const data = await fetch('https://api.example.com/user').then(res => res.json())
  return { props: { user: data } }
}
This generates a static page at build time. It stays the same until you redeploy the app. No automatic cache regeneration.
NextJS
export async function getStaticProps() {
  const data = await fetchData()
  return {
    props: { data }
  }
}
Sample Program

This Next.js page fetches a post and caches it. The cache updates every 30 seconds, so users see fresh content without slowing down the page.

NextJS
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 // refresh cache every 30 seconds
  }
}

export default function Post({ post }) {
  return (
    <main>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </main>
  )
}
OutputSuccess
Important Notes

Use revalidate in getStaticProps for automatic cache updates.

getServerSideProps always fetches fresh data on each request, so no caching is done.

Choose cache times based on how often your data changes and how fresh it needs to be.

Summary

Cache invalidation keeps your app data fresh and fast.

Next.js uses revalidate in getStaticProps for incremental updates.

Use getServerSideProps for always fresh data without caching.