Table of Contents#
- What is Data Fetching in Next.js?
- Quiz Questions
- Question 1: What is the purpose of
getStaticProps? - Question 2: When should you use
getServerSideProps? - Question 3: Can you use both
getStaticPropsandgetServerSidePropsin the same page? - Question 4: How do you fetch data from an API in
getStaticProps? - Question 5: What is the role of
fallbackingetStaticPaths?
- Question 1: What is the purpose of
- Common Practices and Best Practices
- Example Usage
- Reference
What is Data Fetching in Next.js?#
In Next.js, data fetching refers to the process of retrieving data from external sources (such as APIs, databases) and making it available to your React components. This data can be used to populate the UI, for example, showing a list of blog posts or user profiles. Next.js provides two main methods for data fetching at build - time (getStaticProps) and at request - time (getServerSideProps).
Quiz Questions#
Question 1: What is the purpose of getStaticProps?#
getStaticProps is a function in Next.js that is used to fetch data at build - time. This means that the data is fetched once when the application is built (during the npm run build or yarn build process). The fetched data is then used to generate static HTML pages. This is ideal for data that doesn't change frequently, such as blog posts, product catalogs (unless the catalog is updated very often).
Question 2: When should you use getServerSideProps?#
getServerSideProps is used when you need to fetch data on every request. This is useful for data that changes frequently, such as user - specific data (e.g., a user's shopping cart, which can change with every interaction), or real - time data (like stock prices that update constantly). Since the data is fetched on each request, the latest data is always served to the user.
Question 3: Can you use both getStaticProps and getServerSideProps in the same page?#
No, you cannot use both getStaticProps and getServerSideProps in the same page. Each page can have either getStaticProps (for static generation) or getServerSideProps (for server - side rendering).
Question 4: How do you fetch data from an API in getStaticProps?#
In getStaticProps, you can use the fetch API (or libraries like axios). Here is an example:
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: {
data
}
};
}In this example, we are fetching data from an API and then passing it as props to the page component.
Question 5: What is the role of fallback in getStaticPaths?#
The fallback option in getStaticPaths is used for dynamic routes. When you have a dynamic route (e.g., pages/posts/[id].js), and you want to handle cases where a certain id is not pre - rendered at build - time. If fallback: true, when a user requests a page with an un - rendered id, Next.js will first show a fallback UI (by default, it will show a loading state), then fetch the data and re - render the page. If fallback: false, an error page will be shown for un - rendered id values.
Common Practices and Best Practices#
Error Handling#
- In
getStaticProps: If the data fetching ingetStaticPropsfails (e.g., the API is down), you can handle the error gracefully. For example:
export async function getStaticProps() {
try {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: {
data
}
};
} catch (error) {
return {
props: {
data: null,
error: 'Failed to fetch data'
}
};
}
}Then, in your page component, you can check for the error prop and display an appropriate error message to the user.
- In
getServerSideProps: Similar error handling can be done. SincegetServerSidePropsruns on every request, you can also log the error on the server - side for debugging purposes.
Caching#
- For
getStaticProps: The data fetched ingetStaticPropsis cached at build - time. However, if you want to invalidate the cache (e.g., when the data source is updated), you need to re - build the application. - For
getServerSideProps: Since the data is fetched on every request, there is no built - in caching. But you can implement your own caching mechanism (e.g., using in - memory caches on the server if appropriate for your use - case).
Performance Optimization#
- For
getStaticProps: Minimize the amount of data fetched. Only fetch the data that is actually needed by the page component. Also, if possible, use static site generation (SSG) for as many pages as you can, as it can lead to faster page load times (since the pages are pre - rendered). - For
getServerSideProps: Optimize your API calls. For example, use pagination if you are fetching large datasets. Also, consider using caching (as mentioned above) if it makes sense for your data.
Example Usage#
Using getStaticProps#
Let's say we have a blog application. We can use getStaticProps to fetch a list of blog posts at build - time.
// pages/blog.js
import React from'react';
const Blog = ({ posts }) => {
return (
<div>
<h1>Blog Posts</h1>
{posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
))}
</div>
);
};
export async function getStaticProps() {
const res = await fetch('https://api.example.com/blog/posts');
const posts = await res.json();
return {
props: {
posts
}
};
}
export default Blog;Using getServerSideProps#
Suppose we have a user - specific dashboard page.
// pages/dashboard.js
import React from'react';
const Dashboard = ({ userData }) => {
return (
<div>
<h1>Welcome, {userData.username}</h1>
<p>Your balance: {userData.balance}</p>
</div>
);
};
export async function getServerSideProps(context) {
// Here, we can use the context (e.g., to get user ID from cookies or URL parameters)
const userId = context.req.cookies.userId;
const res = await fetch(`https://api.example.com/users/${userId}`);
const userData = await res.json();
return {
props: {
userData
}
};
}
export default Dashboard;Reference#
- Next.js Documentation on Data Fetching
- MDN Web Docs on the Fetch API
- [Axios Documentation](https://axios - http.com/docs/intro)