Client Router Cache

The Next.js client-side Router Cache stores route segments' RSC payloads, including layouts, loading states, and pages. It enables:

  1. Instant navigation between routes without full-page reloads.
  2. State preservation (React and browser state) during navigation.
  3. Cached layouts and loading states for quicker transitions.
  4. Prefetched routes for expected user navigation.
While pages are not cached by default, they can be reused for back/forward navigation or explicitly cached with the staleTimes option. This cache is specific to Next.js, separate from the browser's bfcache, though with similar benefits.

next.config.js:
module.exports = {
  experimental: {
    staleTimes: {
      "/your-route": 300000, // Cache this route for 5 minutes (in milliseconds)
      "/another-route": 60000, // Cache this route for 1 minute
    }
  }
};

Duration

The Next.js router cache is stored in the browser's temporary memory and is affected by:

  1. Session: Cache persists through navigation but clears on page refresh.
  2. Automatic Invalidation: Cache for layouts and loading states auto-expires based on how and if the resource was pre-fetched:
    • Default Prefetching (prefetch={null} or unspecified): No cache for dynamic pages, 5 minutes for static.
    • Full Prefetching (prefetch={true} or router.prefetch): 5 minutes for both static and dynamic pages.
The staleTimes option can be used to adjust these invalidation times.

Revalidation

You can invalidate the Router Cache in two ways:

  1. In a Server Action: Use revalidatePath() or revalidateTag() to refresh data on-demand. Modify cookies with cookies.set() or cookies.delete to ensure routes relying on cookies, like authentication, remain up-to-date.
  2. In the Client Router: Call router.refresh to clear the Router Cache and trigger a new request to the server for the current route.

Opting Out

Starting with Next.js 15, page segments are excluded from caching by default.

Tip: To disable prefetching, set the prefetch prop on the <Link> component to false.


import Link from 'next/link';

export default function MyComponent() {
  return (
    <Link href="/your-route" prefetch={false}>
      Go to Your Route
    </Link>
  );
}