Lesson 16 +10 XP

Extended fetch() & Request Memoization

Extended fetch() & Request Memoization

Next.js extends the native Web fetch() API to automatically manage caching, revalidation, and request deduplication at the server layer.

The Four Caching Layers of Next.js

  1. Request Memoization: Deduplicates identical fetch requests with the same URL and options within a single component render tree.
  2. Data Cache: Persists HTTP fetch response data across server requests and deployments.
  3. Full Route Cache: Caches HTML and RSC payload on the server for static routes.
  4. Router Cache: In-memory client-side cache storing RSC payloads during user sessions.

Controlling fetch Caching

By default, Next.js caches fetch requests that specify a static URL. You can control this behavior using the cache option:

// 1. Default Cached Fetch (Data Cache Enabled)
const staticData = await fetch('https://api.example.com/data', {
  cache: 'force-cache', // Default behavior
});

// 2. Uncached Fetch (Always fetch fresh data)
const freshData = await fetch('https://api.example.com/live-stock', {
  cache: 'no-store',
});

// 3. Time-based Revalidation Fetch
const periodicData = await fetch('https://api.example.com/news', {
  next: { revalidate: 3600 }, // Cache for 1 hour
});

Request Memoization in Action

If three separate components inside the same request render tree call the exact same fetch URL, Next.js executes the network request only once:

async function getUser() {
  // Executed ONLY ONCE per render pass!
  const res = await fetch('https://api.example.com/user/me');
  return res.json();
}

export default async function Page() {
  const user = await getUser();
  return (
    <div>
      <Header /> {/* Header calls getUser() -> Cached instantly */}
      <Sidebar /> {/* Sidebar calls getUser() -> Cached instantly */}
    </div>
  );
}

Fetch Cache Options Summary

Cache OptionData Cache BehaviorUse Case
{ cache: 'force-cache' }Store in Data Cache indefinitelyImmutable data, public blog posts
{ cache: 'no-store' }Skip Data Cache completelyReal-time prices, user notifications
{ next: { revalidate: N } }Cache for N seconds, then revalidateNews feeds, stock catalogs
{ next: { tags: ['item'] } }Tagged cache entry for on-demand purgingE-commerce items, CMS content

TL;DR

  • Next.js extends native fetch() with built-in caching and revalidation features.
  • Request memoization prevents duplicate HTTP calls during a single render pass.
  • Use { cache: 'no-store' } to bypass caching for real-time or private user data.
  • Use { next: { revalidate: N } } to refresh cached data every N seconds.