Next js

Data Fetching In Next Js


Next.js offers multiple ways to fetch data, depending on whether you want static generation, server-side rendering, or client-side fetching.


1. Static Site Generation (SSG) with getStaticProps

  • Fetch data at build time.

  • Great for pages where data doesn’t change often.

  • Pages are pre-rendered to static HTML.

Example:

jsx
export async function getStaticProps() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();

return {
props: {
posts,
},
};
}

export default function PostsPage({ posts }) {
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}


2. Static Generation with Dynamic Routes: getStaticPaths

  • Required for dynamic pages using SSG.

  • Defines which paths to pre-render.

Example:

jsx
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();

const paths = posts.map(post => ({
params: { id: post.id.toString() },
}));

return { paths, fallback: false };
}


3. Server-Side Rendering (SSR) with getServerSideProps

  • Fetch data on every request.

  • Useful when data changes frequently or is user-specific.

Example:

jsx
export async function getServerSideProps(context) {
const res = await fetch('https://api.example.com/data');
const data = await res.json();

return {
props: {
data,
},
};
}

export default function DataPage({ data }) {
return <div>{JSON.stringify(data)}</div>;
}


4. Client-Side Data Fetching

  • Use React hooks like useEffect and fetch to load data after the page loads.

  • Good for interactive components or user-triggered updates.

Example:

jsx
import { useEffect, useState } from 'react';

export default function ClientData() {
const [data, setData] = useState(null);

useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData);
}, []);

if (!data) return <p>Loading...</p>;

return <div>{JSON.stringify(data)}</div>;
}


Summary Table

Method When to Use Data Fetch Timing Usage
getStaticProps Static content, rarely changing Build time SSG
getStaticPaths Dynamic routes with static generation Build time Defines paths for dynamic pages
getServerSideProps Frequently changing or user-specific data On every request SSR
Client-side fetching Interactive, user-triggered updates After page load React hooks (useEffect)

Leave a Reply

Your email address will not be published. Required fields are marked *