Next.js course Β· Module 5: Rendering Strategies

Advanced Caching Strategies in Next.js

8 min read Β·
In this lesson7

In the previous module, we learned the basics of data revalidation. Now it's time to dive deep into the advanced caching mechanisms that the Next.js App Router offers under the hood. Understanding these layers is the key to building applications that run lightning-fast - like the systems in the cyberpunk city of Quantum, where every millisecond of delay can cost lives.

Cache Layer Architecture in Next.js

The Next.js App Router implements a multi-layered caching system. Each layer has a different purpose and different lifetime:

  1. Request Memoization - an in-memory cache for the duration of a single server request. If the same fetch is called multiple times within a single render (e.g., in different components), Next.js will execute it only once.
  2. Data Cache - a persistent cache of data fetched via fetch. It survives between user requests and even between deployments. This is the cache you control through revalidate and cache: 'no-store'.
  3. Full Route Cache - a cache of entire statically generated pages (SSG/ISR). It stores ready-made HTML and React Server Component Payload on the server.
  4. Router Cache - a browser-side cache. It stores visited pages and prefetched segments so that client-side navigation is instant.

How the Layers Work Together

When a user visits a page, Next.js checks the cache in the following order:

Router Cache (browser)
    ↓ miss
Full Route Cache (server)
    ↓ miss
Page rendering β†’ Request Memoization β†’ Data Cache (when fetch opts into caching) β†’ fetch to API

Understanding this flow allows you to precisely control which data is fresh and which can be served from cache.

unstable_cache - Caching Without fetch

Not all data comes from fetch. When you retrieve data from a database (e.g., via Prisma, Drizzle, or direct queries), fetch is not involved and the standard Data Cache doesn't work. That's what unstable_cache is for:

import { unstable_cache } from 'next/cache';

// Caching a database query
const getCachedUser = unstable_cache(
  async (userId: string) => {
    // This query will be cached
    const user = await db.user.findUnique({
      where: { id: userId },
      include: { posts: true, profile: true }
    });
    return user;
  },
  // Cache key - an array of strings identifying this cache
  ['user-data'],
  {
    // Tags for on-demand revalidation
    tags: ['users'],
    // Revalidation time in seconds
    revalidate: 3600
  }
);

// Usage in a Server Component
export default async function UserProfile({ params }: { params: Promise<{ id: string }> }) {
  const user = await getCachedUser((await params).id);

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.profile?.bio}</p>
      <h2>Posts ({user.posts.length})</h2>
    </div>
  );
}

unstable_cache accepts three arguments:

  • An async function - the operation to cache
  • Cache key - an array of strings forming a unique identifier
  • Options - tags (for on-demand revalidation) and revalidate (time in seconds)

Cache Tags - Precise Revalidation Control

Cache tags allow grouping related data and revalidating it together. This is more powerful than revalidatePath because it works independently of URL paths.

Data Tagging Strategy

// Product data - tagged with both a general and specific tag
async function getProduct(id: string) {
  const res = await fetch(`https://api.example.com/products/${id}`, {
    next: {
      tags: [
        'products',           // general tag - revalidates all products
        `product-${id}`       // specific tag - revalidates only this product
      ]
    }
  });
  return res.json();
}

// Category data - related to products
async function getCategory(slug: string) {
  const res = await fetch(`https://api.example.com/categories/${slug}`, {
    next: {
      tags: [
        'categories',
        `category-${slug}`
      ]
    }
  });
  return res.json();
}

On-demand Revalidation with Tags

// app/actions.ts
'use server';

import { revalidateTag, revalidatePath } from 'next/cache';

// After updating a single product
export async function updateProduct(id: string, data: ProductData) {
  await db.product.update({ where: { id }, data });

  // Revalidate only this specific product
  revalidateTag(`product-${id}`, 'max');

  // Also revalidate the product list (e.g., the shop page)
  revalidateTag('products', 'max');
}

// After a bulk price update
export async function bulkUpdatePrices() {
  await db.product.updateMany({ /* ... */ });

  // One command revalidates ALL products across all pages
  revalidateTag('products', 'max');
}

revalidateTag vs revalidatePath - When to Use Which

MethodScopeWhen to use
revalidateTag('products', 'max')All data with the 'products' tag, regardless of pageWhen data appears on multiple pages
revalidatePath('/products')The entire /products page - all data on itWhen you want to refresh a specific page
revalidatePath('/products', 'layout')The page + all subpages with this layoutWhen the layout or shared data has changed

Data Cache vs Full Route Cache vs Router Cache

These three cache layers are often confused. Here are the key differences:

Data Cache

Stores the results of fetch on the server. You control it through:

// Data cached permanently (since Next.js 15 you opt in explicitly)
fetch(url, { cache: 'force-cache' });

// Data cached for 60 seconds
fetch(url, { next: { revalidate: 60 } });

// Data never cached
fetch(url, { cache: 'no-store' });

Lifetime: Survives between requests and deployments (unless revalidated).

Full Route Cache

Stores generated HTML + RSC Payload of static pages. Created during next build.

// This page will be in the Full Route Cache (static)
export default async function AboutPage() {
  return <h1>About Us</h1>;
}

// This page will NOT be in the Full Route Cache (dynamic)
export default async function DashboardPage() {
  const session = await getSession(); // dynamic function
  return <h1>Welcome, {session.user.name}</h1>;
}

// Forcing Full Route Cache revalidation
export const revalidate = 3600; // page revalidated every hour

Lifetime: Until the next next build or revalidation.

Router Cache

Stores visited pages in the user's browser. Thanks to it, navigating back is instant.

'use client';

import { useRouter } from 'next/navigation';

export function RefreshButton() {
  const router = useRouter();

  return (
    <button onClick={() => {
      // Clear the Router Cache and fetch fresh data from the server
      router.refresh();
    }}>
      Refresh data
    </button>
  );
}

Lifetime:

  • Static pages: 5 minutes
  • Dynamic pages: 30 seconds
  • Prefetched: until navigation

Cache Scope - Per-request vs Cross-request

An important distinction that many developers miss:

Per-request (Request Memoization)

Works only within a single server request. If component A and component B call the same fetch, it will be executed only once:

// Both components share the same fetch within a single render
async function Header() {
  const user = await getUser(); // fetch #1
  return <nav>{user.name}</nav>;
}

async function Sidebar() {
  const user = await getUser(); // same fetch - from memoization, not the network!
  return <aside>{user.avatar}</aside>;
}

Cross-request (Data Cache)

Survives between requests from different users:

async function getPopularPosts() {
  // This data is shared between ALL users
  const res = await fetch('https://api.example.com/popular', {
    next: { revalidate: 300 } // cache for 5 minutes
  });
  return res.json();
}

Debugging Cache

Cache problems are among the hardest to diagnose. Here are proven techniques:

1. Logging in Server Components

export default async function Page() {
  console.log('[Page] Rendering at:', new Date().toISOString());

  const data = await getData();
  console.log('[Page] Data fetched, first item:', data[0]?.id);

  return <div>{/* ... */}</div>;
}

If you see the same timestamp when refreshing - the page is served from the Full Route Cache.

2. The x-nextjs-cache Header

In production mode, Next.js adds the x-nextjs-cache header to responses:

  • HIT - page from the Full Route Cache
  • MISS - page rendered live
  • STALE - page from cache, but revalidation was triggered in the background

3. Forcing Dynamic Rendering for Testing

import { headers } from 'next/headers';

export default async function DebugPage() {
  // Using await headers() forces dynamic rendering
  const headersList = await headers();

  return (
    <div>
      <p>Rendered: {new Date().toISOString()}</p>
      <p>This timestamp should change on every refresh</p>
    </div>
  );
}

Summary

Advanced caching strategies in Next.js create a multi-layered system that - when well configured - can radically speed up an application. Key takeaways:

  1. 4 cache layers - Request Memoization, Data Cache, Full Route Cache, Router Cache - each with a different scope and lifetime
  2. unstable_cache - allows caching data from databases and other non-fetch sources
  3. Cache tags - precise revalidation control: revalidateTag for data, revalidatePath for pages
  4. Per-request vs cross-request - Request Memoization works within a single render, Data Cache across requests
  5. Debugging - logging timestamps, x-nextjs-cache headers, forcing dynamic rendering
Code for this lesson: App.tsx
import React, { useState } from 'react';

// Cache layers in the Next.js App Router
// Request Memoization -> Data Cache -> Full Route Cache -> Router Cache

type CacheLayer = 'request-memo' | 'data-cache' | 'full-route' | 'router-cache';

interface LayerInfo {
  id: CacheLayer;
  name: string;
  scope: string;
  lifetime: string;
  description: string;
  invalidation: string;
  example: string;
}

const layers: LayerInfo[] = [
  {
    id: 'request-memo',
    name: 'Request Memoization',
    scope: 'Per-request (server)',
    lifetime: 'Duration of a single render',
    description: 'Deduplicates identical fetches within a single request. If Header and Sidebar both call getUser(), the fetch runs once.',
    invalidation: 'Automatically after rendering finishes',
    example: 'const user = await getUser(); // called 3x, executed 1x',
  },
  {
    id: 'data-cache',
    name: 'Data Cache',
    scope: 'Cross-request (server)',
    lifetime: 'Between requests and deployments',
    description: 'Persistent cache of fetch results. Controlled by revalidate and cache options. Shared between users.',
    invalidation: 'revalidateTag() / revalidatePath() / revalidate: N',
    example: "fetch(url, { next: { revalidate: 60, tags: ['products'] } })",
  },
  {
    id: 'full-route',
    name: 'Full Route Cache',
    scope: 'Static pages (server)',
    lifetime: 'Until the next build or revalidation',
    description: 'Cache of ready-made HTML + RSC Payload for static pages. Created during next build.',
    invalidation: 'revalidatePath() / next build / revalidate on the page',
    example: "export const revalidate = 3600; // entire page every hour",
  },
  {
    id: 'router-cache',
    name: 'Router Cache',
    scope: "User's browser",
    lifetime: 'Static: 5min, Dynamic: 30s',
    description: 'Browser cache for client-side navigation. Prefetched pages load instantly.',
    invalidation: 'router.refresh() / automatically after time passes',
    example: "router.refresh(); // clear the Router Cache",
  },
];

export default function CacheLayersDemo() {
  const [selected, setSelected] = useState<LayerInfo>(layers[0]);
  const [requestFlow, setRequestFlow] = useState<{ layer: string; result: 'HIT' | 'MISS' }[]>([]);

  const simulateRequest = () => {
    const flow: { layer: string; result: 'HIT' | 'MISS' }[] = [];
    let resolved = false;

    for (const layer of layers) {
      if (resolved) break;
      const hit = Math.random() > 0.4;
      flow.push({ layer: layer.name, result: hit ? 'HIT' : 'MISS' });
      if (hit) resolved = true;
    }

    if (!resolved) {
      flow.push({ layer: 'Origin API', result: 'MISS' });
    }

    setRequestFlow(flow);
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
      <h1 style={{ color: '#64ffda', fontSize: 18 }}>Cache Layers in Next.js</h1>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', margin: '16px 0' }}>
        {layers.map((l, i) => (
          <button key={l.id} onClick={() => setSelected(l)} style={{
            background: selected.id === l.id ? '#1565c0' : '#1a2744',
            color: '#fff', border: `1px solid ${selected.id === l.id ? '#64ffda' : '#333'}`,
            borderRadius: 6, padding: '8px 12px', cursor: 'pointer', fontSize: 11, fontFamily: 'monospace'
          }}>
            {i + 1}. {l.name}
          </button>
        ))}
      </div>

      <div style={{ background: '#0d1117', borderRadius: 8, padding: 16, marginBottom: 16 }}>
        <div style={{ color: '#64ffda', fontSize: 15, marginBottom: 8 }}>{selected.name}</div>
        <div style={{ display: 'grid', gap: 6, fontSize: 12 }}>
          <div><span style={{ color: '#888' }}>Scope:</span> <span style={{ color: '#ce93d8' }}>{selected.scope}</span></div>
          <div><span style={{ color: '#888' }}>Lifetime:</span> <span style={{ color: '#ffab40' }}>{selected.lifetime}</span></div>
          <div><span style={{ color: '#888' }}>Description:</span> {selected.description}</div>
          <div><span style={{ color: '#888' }}>Invalidation:</span> <span style={{ color: '#ef5350' }}>{selected.invalidation}</span></div>
          <code style={{ color: '#4caf50', background: '#1a2744', padding: '6px 10px', borderRadius: 4, fontSize: 11 }}>
            {selected.example}
          </code>
        </div>
      </div>

      <button onClick={simulateRequest} style={{
        background: '#4caf50', color: '#fff', border: 'none', borderRadius: 6,
        padding: '8px 16px', cursor: 'pointer', fontFamily: 'monospace'
      }}>
        Simulate request
      </button>

      {requestFlow.length > 0 && (
        <div style={{ marginTop: 16 }}>
          <div style={{ color: '#888', fontSize: 12, marginBottom: 8 }}>Request flow through the cache layers:</div>
          <div style={{ display: 'flex', gap: 4, alignItems: 'center', flexWrap: 'wrap' }}>
            {requestFlow.map((step, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span style={{ color: '#555' }}>-&gt;</span>}
                <div style={{
                  background: step.result === 'HIT' ? '#1b5e20' : '#b71c1c',
                  borderRadius: 4, padding: '4px 8px', fontSize: 11
                }}>
                  {step.layer}: {step.result}
                </div>
              </React.Fragment>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is unstable_cache used for in Next.js App Router?

  2. 2. generateStaticParams is used for:

Hands-on tasks in the game

  • Code editor

    Create a page with optimization: lazy loading, Suspense, proper rendering strategy selection

  • Horizontal ordering

    Arrange the dynamic export syntax in Next.js

  • Click in order

    Arrange the Suspense component syntax with fallback in Next.js

  • Code editor

    Create a Server Action for form submission handling with validation and error handling

  1. QuestionThe unstable_cache function in Next.js
  2. QuestiongenerateStaticParams is used for:
  3. Coding taskPractice: Create a page with optimization: lazy loading, Suspense, proper rendering
  4. Put in orderDynamic export syntax in Next.js
  5. Click in orderSuspense with fallback syntax
  6. Coding taskPractice: Create a Server Action for form submission handling

Useful articles