0
0
NextJSframework~5 mins

Why data fetching differs in Next.js

Choose your learning style9 modes available
Introduction

Next.js handles data fetching differently because it mixes server and client work to make websites faster and easier to build.

When you want your page to load faster by fetching data on the server before showing it.
When you need to update data on the client side after the page loads.
When you want to pre-build pages with data for better search engine results.
When you want to fetch data only when a user visits a page, not before.
When you want to combine server and client data fetching for a smooth experience.
Syntax
NextJS
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.

Examples
This fetches data on the server every time someone visits the page.
NextJS
export async function getServerSideProps(context) {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  return { props: { data } };
}
This fetches data once when building the site, making the page very fast but data may be outdated.
NextJS
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  return { props: { data } };
}
This fetches data on the client after the page loads, useful for user interactions.
NextJS
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>;
}
Sample Program

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.

NextJS
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>
  );
}
OutputSuccess
Important Notes

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.

Summary

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.