Day 25 — Caching Deep Dive: Understanding the Layers
🧭 Day 25 — Caching Deep Dive: Understanding the Layers
Zero to Hero — Hands-on Next.js Tutorial
“Why is my data not updating?” “Why is my page hitting the DB on every refresh?”
Next.js has four distinct caching layers. Understanding them is key to debugging.
🟦 1. Request Memoization (Per Request)
Scope: Single Request (Server) Goal: Avoid duplicate fetches in React Tree.
If you call fetchUser() in Layout, Page, and Sidebar…
Next.js actually calls the API once. It stores the result in memory for the duration of that single render pass.
No configuration needed.
🟩 2. Data Cache (Persistent)
Scope: Across Requests (Server) Goal: Store data permanently until revalidated.
This is the fetch cache.
- Results persist across user sessions and deployments (if configured).
- Controlled by
revalidatePath,revalidateTag, orrevalidate: 3600.
🟧 3. Full Route Cache (Build Time)
Scope: Across Requests (Server) Goal: Serve static HTML instantly.
If a route is Static, Next.js stores the HTML and RSC Payload at build time.
This is what makes SSG fast.
It is opted out if you use Dynamic Functions (cookies(), no-store).
🟥 4. Router Cache (Client)
Scope: User Session (Browser) Goal: Instant navigation (Back/Forward).
Next.js stores visited route segments in the browser’s memory for 30 seconds (dynamic) or 5 minutes (static). This is why clicking “Back” is instant. You cannot effectively clear this cache (mostly). It clears on page reload.
🧪 Challenge: Day 25
- Create a page that fetches a random number.
- Add a
console.log('Fetching')inside the fetch function. - Refresh the page.
- If you see ‘Fetching’ every time: You are dynamic (Layer 3 disabled).
- If you never see it (after build): You are static (Layer 2/3 active).
- Navigate away and back.
- If the number is the same and NO log: You hit the Client Router Cache (Layer 4).
See you tomorrow for Internationalization (i18n)! 🌍