Stop Using fetch Wrong πŸš€ Next.js Data Fetching Deep Dive #11 || Next.js Anatomy || DeathCode - DeathCode

Next.js fetch() Deep Dive (Caching, Deduplication & Internals) πŸš€

Overview

Next.js App Router mein fetch() normal browser fetch jaisa nahi hota.

Server Components ke andar use kiya gaya fetch() Next.js ke rendering system, caching layer aur revalidation mechanism ke saath tightly integrated hota hai.

Isliye Next.js ka fetch sirf data fetch nahi karta, balki ye bhi decide karta hai:

  • Data cache hoga ya nahi
  • Request repeat hogi ya nahi
  • Page static render hoga ya dynamic
  • Cached data kab refresh hoga
  • Multiple components same request kaise share karenge

Normal Fetch vs Next.js Fetch

Browser Fetch

"use client";
 
import { useEffect, useState } from "react";
 
export default function Page() {
  const [data, setData] = useState(null);
 
  useEffect(() => {
    fetch("/api/data")
      .then(res => res.json())
      .then(setData);
  }, []);
 
  return <div>{data?.title}</div>;
}

Characteristics

  • Browser mein execute hota hai
  • JavaScript load hone ke baad hi run hota hai
  • Built-in request deduplication nahi hoti
  • Next.js rendering system se independent hota hai
  • SEO ke liye ideal nahi hota

Next.js Fetch

export default async function Page() {
  const res = await fetch("https://api.example.com/data");
  const data = await res.json();
 
  return <h1>{data.title}</h1>;
}

Characteristics

  • Server par execute hota hai
  • Rendering system ke saath integrated hota hai
  • Automatic caching support
  • Automatic request deduplication
  • Revalidation support
  • Static aur Dynamic rendering decisions ko influence kar sakta hai

Internal Mental Model

Normal JavaScript mein:

fetch()
    ↓
network request
    ↓
response

Next.js mein:

fetch()
    ↓
cache check
    ↓
deduplication check
    ↓
network request (if needed)
    ↓
response cache
    ↓
rendering system

Analogy

Normal fetch ek waiter jaisa hai jo seedha kitchen mein order bhej deta hai.

Next.js fetch restaurant manager ki tarah kaam karta hai:

  • Order pehle se ready hai ya nahi check karta hai
  • Kisi aur ne same order diya hai ya nahi check karta hai
  • Cache serve karna hai ya fresh request bhejni hai decide karta hai

Request Memoization vs Data Cache

Next.js fetch ke saath do alag concepts kaafi important hain.

1. Request Memoization

Ek hi render cycle mein agar multiple components same request bhejte hain:

await fetch("/api/products");
await fetch("/api/products");

Toh Next.js duplicate network requests nahi bhejta.

Result

2 fetch calls
       ↓
1 network request
       ↓
shared response

Is process ko Request Memoization ya Deduplication kaha jata hai.


2. Data Cache

Request complete hone ke baad response future requests ke liye cache mein store kiya ja sakta hai.

Request
   ↓
Response
   ↓
Cache Storage
   ↓
Future Requests

Ye render cycle se alag mechanism hai.


Default Caching Behaviour

Server Components mein default fetch generally cached behaviour use karta hai.

await fetch(url);

Equivalent mental model:

await fetch(url, {
  cache: "force-cache",
});

Behaviour

First Request:

Request
   ↓
API Call
   ↓
Response Stored

Next Requests:

Request
   ↓
Cache Hit
   ↓
Response Returned

Isliye kai baar lagta hai ki API hit hi nahi ho rahi.

Actually response cache se aa raha hota hai.


Cache Control Options

1. force-cache

Default static behaviour.

await fetch(url, {
  cache: "force-cache",
});

Use Cases

  • Blog posts
  • Documentation
  • Static content
  • Product catalogs

Characteristics

  • Fastest response
  • Maximum cache usage
  • Minimum server load

2. no-store

Har request par fresh data fetch hota hai.

await fetch(url, {
  cache: "no-store",
});

Behaviour

Request
   ↓
Always Network
   ↓
Fresh Response

Use Cases

  • Dashboard
  • User-specific data
  • Admin panels
  • Live statistics

Characteristics

  • No caching
  • Always fresh
  • Higher server load

3. Revalidation

Static aur Dynamic ke beech ka hybrid approach.

await fetch(url, {
  next: {
    revalidate: 60,
  },
});

Meaning

Cache response
      ↓
60 seconds valid
      ↓
Refresh after expiry

Use Cases

  • News websites
  • Product inventory
  • Frequently changing content

Rendering Impact

Fetch configuration rendering behaviour ko influence kar sakti hai.

Static Rendering

await fetch(url);

ya

await fetch(url, {
  cache: "force-cache",
});

Build time ya cached output generate ho sakta hai.


Dynamic Rendering

await fetch(url, {
  cache: "no-store",
});

Har request par fresh render.


Hybrid Rendering

await fetch(url, {
  next: {
    revalidate: 60,
  },
});

Static generation + periodic updates.


Server Fetch vs Client Fetch

Server Component

export default async function Page() {
  const res = await fetch(url);
}

Features

  • Cache support
  • Deduplication support
  • Revalidation support
  • Better SEO
  • Faster initial render

Client Component

"use client";
 
useEffect(() => {
  fetch(url);
}, []);

Features

  • Browser fetch
  • No Next.js cache layer
  • No request deduplication
  • Runs after hydration

Edge Runtime vs Node Runtime

Node Runtime

Features:

  • Full Node.js APIs
  • Database drivers
  • File system access
  • Large memory footprint

Suitable for:

  • Complex backend logic
  • Database operations
  • Heavy processing

Edge Runtime

Features:

  • Lightweight execution
  • Lower latency
  • Globally distributed
  • Limited APIs

Suitable for:

  • Authentication checks
  • Redirects
  • Personalization
  • Lightweight logic

Important

Edge Runtime ka behaviour Node Runtime se different ho sakta hai, especially caching aur available APIs ke context mein.


Common Real-World Issues

Problem: Data Update Nahi Ho Raha

Cause

Cached response serve ho raha hai.

Solution

await fetch(url, {
  cache: "no-store",
});

Problem: API Hit Nahi Ho Rahi

Cause

Request deduplication active hai.

Multiple fetch calls same response share kar rahe hain.


Problem: Old Data Dikh Raha Hai

Cause

Cache expire nahi hua.

Solution

next: {
  revalidate: 60;
}

ya

cache: "no-store";

Performance Strategy

General recommendation:

Data Type Recommended Strategy
Blog Content force-cache
Documentation force-cache
Product Pages revalidate
News Content revalidate
User Dashboard no-store
Admin Data no-store

Final Mental Model

Normal Fetch
    ↓
Network
    ↓
Response
Next.js Fetch
    ↓
Cache Check
    ↓
Deduplication Check
    ↓
Network Request
    ↓
Cache Storage
    ↓
Rendering System

Golden Rule

Next.js fetch sirf data fetch nahi karta.

Ye decide karta hai:

  • Data kab fetch hoga
  • Data kitni baar fetch hoga
  • Data cache hoga ya nahi
  • Page static hoga ya dynamic
  • Response kab refresh hoga

Isi wajah se Next.js ka fetch() App Router architecture ka ek core building block hai.

Β© 2024 DeathCode. All Rights Reserved.