Next.js - Router Caching



In this chapter, we will learn Client-Side Router Caching in Next.js, how it works, and how to revalidate client-side cache.

What is Router Caching?

Router caching is a feature in Next.js that allows you to cache pages and data in the client browser. This is used to improve performance and reduce load times by storing data in the client browser so that it can be accessed quickly.

How it Works?

  • When a page is loaded, Next.js stores the page in the client browser.
  • Subsequent requests for the same page return the cached page instead of making new requests.
  • The cache is maintained in the client browser, meaning it's cleared when the browser is closed or the cache is cleared manually.

Router Cache Duration

The router cache is stored in the browser's temporary memory. There are two factors that determine how long the cache is stored:

  • Current Session: The cache persists across page until the browser tab is reloaded or closed.
  • Automatic Invalidation Period: We can manually set to invalidate cache of layouts and loading states after a specific time. The default duration depends on how the resource was prefetched, and if the resource was statically generated. For default pre-fetching (ie, prefetch={null} or unspecified ), 5 minutes is the cache invalidation period static pages, and dynamic pages are not cached. For full pre-fetching (ie, prefetch={true}), the invalidation period is 5 minutes for both static pages and dynamic pages.

Time-based Cache Revalidation

Time-based revalidation is a technique used to revalidate the cache after a specific time period. This is used to ensure that the cache is up-to-date and that the data is not stale. In the code snippet below, we have a page that revalidates every 5 seconds.

export const revalidate = 5 // revalidate every 5 seconds

async function getData() {
  // Simulate API call
  return {
    timestamp: new Date().toISOString(),
    randomValue: Math.random(),
    message: 'This page revalidates every 5 seconds'
  }
}

export default async function Page() {
  const data = await getData()
  
  return (
    <main>
        <h1>5 Second Revalidation</h1>
        <p>Timestamp: {data.timestamp}</p>
        <p>Random Value: {data.randomValue}</p>
        <p>{data.message}</p>
        <p>
            Next revalidation will occur 5 seconds after the last 
            revalidation
        </p>
    </main>
  )
}

Output

The image below shows output of the code snippet above. When we continuously refresh the page, we can see that the page revalidated (the new random number generated) only after every 5 seconds.

Next.js Time-based Revalidation

Revalidation by Path

Revalidation by path is a technique used to revalidate the cache of a specific path. In the code below, we have a page that revalidates the cache of the home page when a button is clicked.

import { revalidatePath } from 'next/cache'

async function getData() {
  return {
    timestamp: new Date().toISOString(),
    randomNumber: Math.random(),
    message: 'This data will update when revalidated'
  }
}

// Server Action for revalidation
async function handleRevalidate() {
  'use server'
  revalidatePath('/')
}

export default async function Home() {
  const data = await getData()
  
  return (
    <main>
        <h1>Path Revalidation Demo</h1>
        <div>
            <p>Timestamp: {data.timestamp}</p>
            <p>Random Number: {data.randomNumber}</p>
            <p>{data.message}</p>
        </div>
        
        <form action={handleRevalidate}>
            <button type="submit">Revalidate</button>
        </form>

        <br />
    </main>
  )
}

Output

The image below shows the output of the code snippet above. When we reload the page, the random number is not revalidated (as cache is stored), but when we click the "Revalidate" button, the cache of the home page is revalidated, and the random number is updated.

Next.js Path Revalidation
Advertisements