ReviseAlgo Logo

Data Fetching

fetch()

Learn how Next.js extends fetch for server data fetching, caching, revalidation, and request-time freshness.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Use fetch() inside Server Components.
  • Choose between cached, revalidated, and uncached requests.
  • Explain how fetch behavior affects rendering strategy.
  • Handle loading and error states around data fetching.
  • Difficulty: Beginner.

    2. Prerequisites

  • Server Components.
  • SSR, SSG, and ISR basics.
  • Promises and async/await.
  • 3. Overview

    Next.js builds on the standard Web fetch() API with server-aware caching and revalidation options. In Server Components, you can fetch data before rendering and let Next.js decide whether the result should be cached, revalidated, or fetched fresh.

    4. Why This Topic Matters

    Most Next.js pages are shaped by data fetching decisions. The same UI can behave like SSG, ISR, or SSR depending on how its data is fetched and cached.

    5. Real-World Analogy

    Using fetch() in Next.js is like choosing how a store restocks shelves. Some items are pre-stocked, some refresh every hour, and some are fetched from the back room only when a customer asks.

    6. Core Concepts

    OptionMeaning
    Default fetchMay be cached depending on route and framework behavior.
    cache: 'no-store'Fetch fresh data for each request.
    next: { revalidate: n }Cache and refresh after n seconds.
    Error handlingNon-2xx responses should be checked explicitly.
    Parallel fetchStart independent requests together to reduce waiting.

    7. Syntax & API Reference

    Always check important responses:

    8. Visual Diagram

    9. Live Example - Full Working Code

    What just happened? Posts can be cached and refreshed every five minutes instead of fetched fresh for every request.

    10. Interactive Playground

    Try this:

  • Switch from next: { revalidate: 300 } to cache: 'no-store'.
  • Add Promise.all for two independent requests.
  • Throw an error when res.ok is false and observe the route error boundary.
  • 11. Common Mistakes

    MistakeWhy It HappensCorrect Approach
    Not checking res.okfetch only rejects on network failures.Throw for bad HTTP responses.
    Fetching sequentially when requests are independentAsync code is written top-down.Use Promise.all for independent requests.
    Using no-store everywhereFreshness feels safest.Cache public data when freshness allows.

    12. Best Practices

  • Fetch in Server Components for initial render data.
  • Choose caching based on product freshness requirements.
  • Handle non-2xx responses explicitly.
  • Use parallel fetching for independent data.
  • Keep private data uncached or user-scoped.
  • 13. Browser Compatibility

    FeatureBrowser ImpactNotes
    Server fetchNo direct browser dependencyRuns on server.
    Browser fetchModern browser APIUsed in Client Components.
    Cache/revalidate optionsNext.js server featureFramework-specific behavior.

    14. Interview Questions

    Easy: Can you use fetch() directly in a Server Component?

    Answer: Yes.

    Medium: What does cache: 'no-store' mean?

    Answer: Fetch fresh data instead of using a shared cached response.

    Hard: Why does fetch configuration affect rendering strategy?

    Answer: Cached fetches can support static or revalidated output, while uncached request-time fetches make the route dynamic.

    15. Debugging Exercise

    Bug report: "The page shows broken data but no error boundary appears."

    Solution

    Check res.ok and throw an error for failed HTTP statuses. fetch() does not automatically throw for 404 or 500 responses.

    16. Practice Exercises

  • Easy: Fetch a public list in a Server Component.
  • Medium: Add a five-minute revalidation window.
  • Hard: Parallelize three independent fetches and handle failures cleanly.
  • 17. Scenario-Based Challenge

    A homepage fetches hero copy, trending products, and user-specific recommendations. How should caching differ?

    Walkthrough

    Cache or revalidate public hero and trending product data. Fetch user-specific recommendations per request or in a private client/server path.

    18. Quick Quiz

    1. Does fetch throw on HTTP 500 automatically? Answer: No. 2. What option forces fresh data? Answer: cache: 'no-store'. 3. What option refreshes after time? Answer: next: { revalidate: n }. 4. Where should initial SEO data usually be fetched? Answer: On the server. 5. What helps independent fetches finish faster? Answer: Promise.all.

    19. Summary & Key Takeaways

  • Next.js extends fetch() with caching and revalidation.
  • Fetch choices shape rendering behavior.
  • no-store favors freshness.
  • revalidate balances static speed and freshness.
  • Always handle bad HTTP responses.
  • 20. Cheat Sheet

    NeedFetch Option
    Always freshcache: 'no-store'
    Refresh every 5 minnext: { revalidate: 300 }
    Public stable dataCached/static-friendly fetch
    Private user dataRequest-scoped fetch
    Independent requestsPromise.all

    21. Further Reading

  • Next.js Docs: Fetching, Caching, and Revalidating.
  • MDN: fetch API.
  • Next.js Docs: Data Fetching Patterns.
  • 22. Next Lesson Preview

    Next, you will learn Route Handlers for building server endpoints inside the App Router.