Next.js Data Fetching
Next.js provides several data fetching methods that allow you to fetch data from various sources and render it in your components.
Quick note
getStaticProps
is used to fetch data at build time. This method is ideal for pages that don't require frequently updated data.getStaticPaths
is used in combination withgetStaticProps
to generate static pages for dynamic routes. It specifies the paths that should be pre-rendered at build time.getServerSideProps
is used to fetch data on each request. This method is suitable for pages that require real-time data or depend on user authentication.- supports client-side data fetching using APIs like
fetch
or libraries likeaxios
.
getStaticProps
The getStaticProps
is used to fetch data at build time. It runs on the server-side
and generates static HTML pages with the fetched data.
- This method is ideal for pages that don’t require frequently updated data.
function BlogPostsPage({ posts }) {
return (
<div>
<h1>Blog Posts</h1>
{posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
}
export async function getStaticProps() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
return {
props: {
posts,
},
};
}
export default BlogPostsPage;
The getStaticProps
fetches a blog post from an API and passes it as a prop to the BlogPostPage component. The fetched data is used to generate a static HTML page at build time.
getStaticPaths
The getStaticPaths
* is used in combination with getStaticProps
to generate static pages for dynamic routes. It specifies the paths that should be pre-rendered at build time.
function ProductPage({ product }) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
</div>
);
}
export async function getStaticPaths() {
const response = await fetch('https://api.example.com/products');
const products = await response.json();
const paths = products.map((product) => ({
params: { id: product.id.toString() },
}));
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
const response = await fetch(`https://api.example.com/products/${params.id}`);
const product = await response.json();
return {
props: {
product,
},
};
}
export default ProductPage;
The getStaticPaths
fetches a list of product IDs from an API and generates the paths for each product page. getStaticProps
then fetches the data for each individual product based on the id parameter.
getServerSideProps
getServerSideProps
is used to fetch data on each request. It runs on the server-side
and generates HTML pages dynamically. * This method is suitable for pages that require real-time data or depend on user authentication.
function UserProfilePage({ user }) {
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
export async function getServerSideProps({ req, res }) {
const { userId } = req.session;
const response = await fetch(`https://api.example.com/users/${userId}`);
const user = await response.json();
return {
props: {
user,
},
};
}
export default UserProfilePage;
Client-side Data Fetching
Next.js also supports client-side data fetching using APIs like fetch or libraries like axios. You * can fetch data directly in your components using React’s useEffect hook or other lifecycle methods.
import { useState, useEffect } from 'react';
function ProductList() {
const [products, setProducts] = useState([]);
useEffect(() => {
async function fetchProducts() {
const response = await fetch('https://api.example.com/products');
const data = await response.json();
setProducts(data);
}
fetchProducts();
}, []);
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
export default ProductList;
The ProductList
component fetches a list of products from an API using the useEffect
hook and updates the component's state with the fetched data.
More detail about getStaticPaths
and getStaticProps
using simple example
This code represents a basic Next.js page that displays product details, along with two key functions (getStaticPaths
and getStaticProps
) for handling static site generation (SSG)
.
ProductPage Component
function ProductPage({ product }) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
</div>
);
}
This is a simple functional React component that renders the product’s name and description on the page. The product object is passed as a prop to this component. It’s expected to have at least two fields: name
and description
.
getStaticPaths Function
export async function getStaticPaths() {
const response = await fetch('https://api.example.com/products');
const products = await response.json();
const paths = products.map((product) => ({
params: { id: product.id.toString() },
}));
return { paths, fallback: false };
}
This function is used to tell Next.js
which product pages need to be statically generated. It defines the dynamic routes ([id] pages) that should be created at build time.
The function fetches a list of products from https://api.example.com/products
. The products array is mapped into a new array of paths, where each path contains a params object. The params object has an id key, which is the product's ID (converted to a string). Each id corresponds to a dynamic route (e.g., /products/1
, /products/2
, etc.).
In Return value:
paths: This array informs Next.js
which pages to generate. fallback: false
: This setting means that any paths not returned by this function will result in a 404 page.
getStaticProps Function
export async function getStaticProps({ params }) {
const response = await fetch(`https://api.example.com/products/${params.id}`);
const product = await response.json();
return {
props: {
product,
},
};
}
This function fetches the data for an individual product (based on the dynamic id in the URL) and passes that data as props to the ProductPage component.
- Params: The params object is passed to this function, which contains the route parameters, specifically the id of the product. Fetching product data: The product data is fetched by calling the API
https://api.example.com/products/${params.id}
, whereparams.id
is the dynamic value from the route. - Return value: The function returns an object with a props key, which contains the product data. This product object is passed as a prop to the ProductPage component, which will render it on the page.
Next.js will:
- Use
getStaticPaths
to know which product pages to pre-render at build time. It maps product IDs to dynamic routes. - Use
getStaticProps
to fetch the data for each specific product when building the static pages. This ensures that the product data is available to the component when the page is rendered.
The ProductPage component will receive the product data and display it on the page.
- Static Site Generation (SSG): The combination of
getStaticPaths
andgetStaticProps
allows you to generate static pages for each product at build time, meaning the content is pre-rendered, improving performance. - Dynamic Routes: In Next.js, you can create dynamic pages by using a file structure like
pages/products/[id].js
, where[id]
is a dynamic segment. The getStaticPaths function provides the paths that should correspond to each id, andgetStaticProps
fetches the data for each page.
#daily_dev_note