Bird
Raised Fist0
NextJSframework~15 mins

Why data fetching differs in Next.js - Why It Works This Way

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Why data fetching differs in Next.js
What is it?
Data fetching in Next.js means getting information from a server or database to show on a web page. Unlike traditional websites where data is fetched only on the client side (in the browser), Next.js can fetch data in different ways, including on the server before the page loads. This makes pages faster and better for search engines. Next.js uses special methods and patterns to decide when and where to get data.
Why it matters
Without Next.js's flexible data fetching, websites might load slower or show empty pages while waiting for data. This can frustrate users and hurt search engine rankings. Next.js solves this by letting developers choose the best way to get data for each page, improving speed, user experience, and SEO. It also helps build modern web apps that feel fast and smooth.
Where it fits
Before learning this, you should understand basic React components and how web pages load data in browsers. After this, you can learn about Next.js routing, server components, and advanced performance optimizations. This topic connects React knowledge with server-side rendering and static site generation concepts.
Mental Model
Core Idea
Next.js changes when and where data is fetched to balance speed, SEO, and user experience by mixing server and client fetching.
Think of it like...
Imagine ordering food at a restaurant: you can either prepare some dishes in the kitchen before the customer arrives (server-side), or cook everything after they order (client-side). Next.js lets you choose the best way to serve food so customers get it fresh and fast.
┌─────────────────────────────┐
│        Next.js Page          │
├─────────────┬───────────────┤
│ Server Side │ Client Side   │
│ Fetching    │ Fetching     │
│ (Before    │ (After page   │
│ rendering) │ loads)        │
└─────────────┴───────────────┘
       ↑                  ↑
       │                  │
  Faster load         Interactive
  and SEO             updates
Build-Up - 7 Steps
1
FoundationWhat is data fetching in web apps
🤔
Concept: Data fetching means getting information from somewhere to show on a webpage.
When you visit a website, it often needs to get data like user info, posts, or products. This data can come from a server or database. In simple web apps, the browser asks for this data after the page loads.
Result
You see the page content filled with real data after it loads.
Understanding data fetching basics helps you see why timing and location of fetching matter for speed and user experience.
2
FoundationClient-side data fetching basics
🤔
Concept: Fetching data in the browser after the page loads using JavaScript.
In React apps, data is often fetched inside components using hooks like useEffect. The browser asks the server for data after showing the page shell. This can cause a delay before data appears.
Result
Page loads quickly but shows empty or loading states until data arrives.
Knowing client-side fetching shows why pages might feel slow or incomplete initially.
3
IntermediateServer-side rendering data fetching
🤔Before reading on: do you think fetching data on the server makes pages load faster or slower? Commit to your answer.
Concept: Next.js can fetch data on the server before sending the page to the browser.
Next.js uses functions like getServerSideProps to get data on the server. The server builds the full page with data and sends it to the browser. This means users see the complete page immediately.
Result
Page loads with all data visible right away, improving speed and SEO.
Understanding server-side fetching reveals how Next.js improves user experience and search engine visibility.
4
IntermediateStatic generation with data fetching
🤔Before reading on: do you think static generation fetches data once or every time a user visits? Commit to your answer.
Concept: Next.js can fetch data at build time to create static pages served to all users.
Using getStaticProps, Next.js fetches data when building the site, creating static HTML pages. These pages load very fast because they are pre-built, but data updates require rebuilding the site.
Result
Pages load instantly with fixed data, great for content that changes rarely.
Knowing static generation helps you choose when to trade data freshness for speed.
5
IntermediateClient-side fetching in Next.js
🤔
Concept: Next.js also supports fetching data in the browser for dynamic updates.
Even with server or static fetching, some data needs to update after page load. Next.js lets you fetch data client-side using React hooks or libraries like SWR. This keeps pages interactive and fresh.
Result
Page updates smoothly with new data without full reloads.
Understanding client-side fetching in Next.js shows how to balance initial load and interactivity.
6
AdvancedIncremental Static Regeneration (ISR)
🤔Before reading on: do you think ISR rebuilds pages on every request or only some? Commit to your answer.
Concept: ISR lets Next.js update static pages after deployment without full rebuilds.
With ISR, you set a time interval for Next.js to regenerate static pages in the background. Users get fast static pages, and data stays fresh without manual rebuilds.
Result
Pages load fast and update automatically over time.
Knowing ISR reveals how Next.js combines static speed with dynamic freshness.
7
ExpertServer Components and data fetching
🤔Before reading on: do you think Server Components fetch data on client or server? Commit to your answer.
Concept: Next.js Server Components fetch data on the server and send only rendered HTML to the client.
Server Components run on the server, fetching data and rendering UI before sending to the browser. This reduces JavaScript sent to the client and improves performance and security.
Result
Pages load faster with less client work and better SEO.
Understanding Server Components changes how you think about data fetching and rendering balance.
Under the Hood
Next.js uses special functions that run on the server during page rendering or build time to fetch data. For server-side rendering, the server waits for data before sending HTML. For static generation, data is fetched once during build. Client-side fetching uses browser JavaScript after page load. ISR uses background processes to update static pages without blocking users. Server Components fetch data on the server and send minimal code to the client.
Why designed this way?
Next.js was designed to solve slow page loads and poor SEO in React apps by mixing server and client data fetching. Traditional React fetches data only in the browser, causing delays and empty pages. Next.js adds server-side and static options to improve speed and search rankings. ISR was created to keep static sites fresh without full rebuilds. Server Components reduce client JavaScript for better performance.
┌───────────────────────────────┐
│          Next.js Page          │
├───────────────┬───────────────┤
│ Server Side   │ Client Side   │
│ Fetching      │ Fetching      │
│ ┌───────────┐ │ ┌───────────┐ │
│ │ getServer │ │ │ useEffect │ │
│ │ SideProps │ │ │ or SWR    │ │
│ └───────────┘ │ └───────────┘ │
│               │               │
│ Static Build  │ Incremental   │
│ ┌───────────┐ │ Static Regen  │
│ │ getStatic │ │ (ISR)        │
│ │ Props     │ │               │
│ └───────────┘ │               │
└───────────────┴───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does getServerSideProps run on the client or server? Commit to your answer.
Common Belief:getServerSideProps fetches data in the browser after the page loads.
Tap to reveal reality
Reality:getServerSideProps runs only on the server before sending the page to the browser.
Why it matters:Thinking it runs on the client leads to confusion about page speed and SEO benefits.
Quick: Does getStaticProps fetch data on every user request? Commit to your answer.
Common Belief:getStaticProps fetches data every time a user visits the page.
Tap to reveal reality
Reality:getStaticProps fetches data once at build time, not on every request.
Why it matters:Misunderstanding this causes wrong expectations about data freshness and rebuild needs.
Quick: Is client-side fetching always slower than server-side? Commit to your answer.
Common Belief:Client-side fetching is always slower and worse for SEO.
Tap to reveal reality
Reality:Client-side fetching can be faster for dynamic updates and is necessary for interactivity, but not good for initial SEO.
Why it matters:Ignoring client-side fetching limits app interactivity and user experience.
Quick: Does ISR rebuild pages synchronously blocking users? Commit to your answer.
Common Belief:ISR rebuilds pages synchronously, making users wait during regeneration.
Tap to reveal reality
Reality:ISR rebuilds pages in the background without blocking users, serving old pages until new ones are ready.
Why it matters:Misunderstanding ISR can cause developers to avoid it, missing performance benefits.
Expert Zone
1
Server-side data fetching can increase server load and latency if not cached properly, requiring careful optimization.
2
ISR timing is approximate; regeneration may not happen exactly at the interval, affecting data freshness expectations.
3
Server Components reduce client JavaScript but require careful data fetching to avoid unnecessary server work and delays.
When NOT to use
Avoid server-side rendering for pages that do not need fresh data on every request; use static generation instead for better performance. Do not use client-side fetching for SEO-critical content. For highly dynamic data, consider client-side fetching or API routes. Avoid ISR if data must be instantly fresh; use server-side rendering instead.
Production Patterns
In production, Next.js apps often use static generation for marketing pages, server-side rendering for user dashboards, ISR for blogs or product catalogs, and client-side fetching for user interactions. Server Components are emerging for reducing bundle size and improving performance in complex apps.
Connections
Server-Side Rendering (SSR)
Next.js builds on SSR by adding static generation and ISR to improve performance and flexibility.
Understanding SSR helps grasp why Next.js fetches data on the server and how it improves SEO and load speed.
Caching Strategies
Data fetching in Next.js often relies on caching to balance freshness and speed, especially with ISR.
Knowing caching principles helps optimize Next.js data fetching to reduce server load and improve user experience.
Restaurant Kitchen Workflow
Like preparing food before or after customer orders, Next.js chooses when to fetch data to serve pages efficiently.
This cross-domain view clarifies trade-offs between speed, freshness, and resource use in data fetching.
Common Pitfalls
#1Fetching data only client-side for SEO pages
Wrong approach:export default function Page() { const [data, setData] = React.useState(null); React.useEffect(() => { fetch('/api/data').then(res => res.json()).then(setData); }, []); return
{data ? data.title : 'Loading...'}
; }
Correct approach:export async function getStaticProps() { const res = await fetch('https://example.com/api/data'); const data = await res.json(); return { props: { data } }; } export default function Page({ data }) { return
{data.title}
; }
Root cause:Misunderstanding that client-side fetching delays content visibility and hurts SEO.
#2Using getStaticProps for frequently changing data without ISR
Wrong approach:export async function getStaticProps() { const res = await fetch('https://example.com/api/live-data'); const data = await res.json(); return { props: { data } }; } // No revalidation set
Correct approach:export async function getStaticProps() { const res = await fetch('https://example.com/api/live-data'); const data = await res.json(); return { props: { data }, revalidate: 60 }; }
Root cause:Not using ISR leads to stale data and poor user experience.
#3Calling server-only data fetching functions inside client components
Wrong approach:function ClientComponent() { const data = getServerSideProps(); // Incorrect usage return
{data.title}
; }
Correct approach:export async function getServerSideProps() { const res = await fetch('https://example.com/api/data'); const data = await res.json(); return { props: { data } }; } function Page({ data }) { return
{data.title}
; }
Root cause:Confusing server-side functions with client-side code causes runtime errors.
Key Takeaways
Next.js offers multiple ways to fetch data: server-side, static generation, client-side, and incremental regeneration.
Choosing the right data fetching method balances speed, SEO, data freshness, and user experience.
Server-side and static fetching improve initial page load and SEO by sending fully rendered pages.
Client-side fetching is essential for dynamic updates and interactivity after the page loads.
Advanced features like ISR and Server Components combine the best of static and dynamic data fetching for modern web apps.

Practice

(1/5)
1. Why does Next.js use different methods for data fetching?
easy
A. Because Next.js only works with static data
B. Because Next.js does not support client-side data fetching
C. Because all data must be fetched only on the server
D. Because data can be fetched at different times for better performance

Solution

  1. Step 1: Understand data fetching timing in Next.js

    Next.js allows fetching data before the page loads (server-side or static) or after the page loads (client-side).
  2. Step 2: Recognize the reason for multiple methods

    Using different methods helps improve performance and user experience by choosing the best time to fetch data.
  3. Final Answer:

    Because data can be fetched at different times for better performance -> Option D
  4. Quick Check:

    Data fetching timing = A [OK]
Hint: Think when data is needed: before or after page loads [OK]
Common Mistakes:
  • Assuming Next.js only fetches data on the server
  • Believing client-side fetching is not supported
  • Thinking all data must be static
2. Which of the following is the correct way to fetch data at build time in Next.js?
easy
A. export async function getStaticProps() { return { props: {} } }
B. export async function getServerSideProps() { return { props: {} } }
C. export async function fetchData() { return { props: {} } }
D. export async function getClientSideProps() { return { props: {} } }

Solution

  1. Step 1: Identify build-time data fetching method

    Next.js uses getStaticProps to fetch data at build time for static generation.
  2. Step 2: Compare options with Next.js conventions

    getServerSideProps is for server-side rendering, not build time; others are invalid function names.
  3. Final Answer:

    export async function getStaticProps() { return { props: {} } } -> Option A
  4. Quick Check:

    Build-time fetch = getStaticProps A [OK]
Hint: Remember: Static = getStaticProps, Server = getServerSideProps [OK]
Common Mistakes:
  • Confusing getServerSideProps with getStaticProps
  • Using incorrect function names
  • Thinking client-side fetching uses special props functions
3. What will be the rendered output if you use getServerSideProps to fetch data that changes every second?
medium
A. The page shows the data as it was at build time
B. The page never updates after first load
C. The page shows the latest data on every request
D. The page shows an error because data changes too fast

Solution

  1. Step 1: Understand getServerSideProps behavior

    This function runs on every request, so it fetches fresh data each time the page loads.
  2. Step 2: Apply to data changing every second

    Since data changes frequently, getServerSideProps ensures the page always shows the latest data.
  3. Final Answer:

    The page shows the latest data on every request -> Option C
  4. Quick Check:

    Server-side fetch = fresh data B [OK]
Hint: Server-side fetch updates on every request [OK]
Common Mistakes:
  • Thinking getServerSideProps caches data at build time
  • Assuming data never updates after first load
  • Believing it causes errors with fast-changing data
4. Identify the error in this Next.js data fetching code:
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()
  return { data }
}
medium
A. Missing return of props object wrapping data
B. fetch cannot be used inside getStaticProps
C. Async functions are not allowed in Next.js data fetching
D. The URL must be relative, not absolute

Solution

  1. Step 1: Check return value format in getStaticProps

    Next.js expects an object with a props key containing the data, not just data alone.
  2. Step 2: Identify the missing wrapper

    The code returns { data } but should return { props: { data } } for Next.js to pass props correctly.
  3. Final Answer:

    Missing return of props object wrapping data -> Option A
  4. Quick Check:

    Return props object = C [OK]
Hint: Always return { props: { ... } } in getStaticProps [OK]
Common Mistakes:
  • Returning data directly without props wrapper
  • Thinking fetch is disallowed in getStaticProps
  • Believing async functions are forbidden
5. You want to show user-specific data that updates frequently but also want fast initial page load in Next.js. Which approach best fits this need?
hard
A. Use getStaticProps to fetch data and revalidate every second
B. Use getStaticProps for static data and fetch user data client-side after load
C. Fetch all data client-side only after page loads
D. Use getServerSideProps to fetch data on every request

Solution

  1. Step 1: Analyze requirements for fast initial load and frequent updates

    Static data can be fetched at build time for fast load; user-specific data changes often and should be fetched client-side.
  2. Step 2: Evaluate options

    Use getStaticProps to fetch data and revalidate every second revalidates too frequently and may cause performance issues; Use getServerSideProps to fetch data on every request delays initial load; Fetch all data client-side only after page loads delays all data; Use getStaticProps for static data and fetch user data client-side after load balances fast load and fresh user data.
  3. Final Answer:

    Use getStaticProps for static data and fetch user data client-side after load -> Option B
  4. Quick Check:

    Static + client fetch = D [OK]
Hint: Combine static build with client fetch for user data [OK]
Common Mistakes:
  • Using only server-side fetching causing slow load
  • Fetching everything client-side causing blank initial page
  • Overusing revalidation causing unnecessary server load