Next.js handles data fetching differently because it mixes server and client work to make websites faster and easier to build.
Why data fetching differs in Next.js
export async function getServerSideProps(context) { // fetch data here const data = await fetchData(); return { props: { data } }; } export async function getStaticProps() { // fetch data here const data = await fetchData(); return { props: { data } }; } // Client-side fetching inside a React component import { useEffect, useState } from 'react'; function Component() { const [data, setData] = useState(null); useEffect(() => { fetch('/api/data') .then(res => res.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; }
getServerSideProps runs on the server on every request.
getStaticProps runs at build time to create static pages.
export async function getServerSideProps(context) { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; }
export async function getStaticProps() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; }
import { useEffect, useState } from 'react'; function Page() { const [data, setData] = useState(null); useEffect(() => { fetch('/api/data') .then(res => res.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; }
This example shows data fetched at build time for the post content, making the page fast to load. Comments are fetched on the client after the page loads, so users see the post immediately and comments appear shortly after.
import { useState, useEffect } from 'react'; export async function getStaticProps() { const res = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const post = await res.json(); return { props: { post } }; } export default function PostPage({ post }) { const [comments, setComments] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/posts/1/comments') .then(res => res.json()) .then(setComments); }, []); return ( <main> <h1>{post.title}</h1> <p>{post.body}</p> <section aria-label="Comments"> <h2>Comments</h2> {comments ? ( <ul> {comments.map(c => ( <li key={c.id}> <strong>{c.name}:</strong> {c.body} </li> ))} </ul> ) : ( <p>Loading comments...</p> )} </section> </main> ); }
Server-side fetching helps with SEO and fast first load.
Client-side fetching is good for data that changes often or depends on user actions.
Static generation is best for pages that don't change often.
Next.js uses different ways to fetch data depending on when and how you want it.
Server-side and static fetching happen before the page shows, client-side fetching happens after.
Choosing the right method helps your site load faster and work better for users.