In this tutorial, we aim to understand how to use getStaticProps
for static generation in Next.js. This is a built-in function provided by Next.js that runs at build time and fetches data which is then used to generate a static HTML page.
By the end of this tutorial, you will learn:
getStaticProps
and its purposePrerequisites:
getStaticProps
is a data fetching method that runs only on the server-side, and it never runs on the client-side. It is used to fetch data at build time and generate a static HTML page out of it.
Below is a step-by-step guide on how to use getStaticProps
:
npx create-next-app<your-app-name>
.pages
directory.getStaticProps
function and export it.The getStaticProps
function should return an object like this:
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
Here, props
is the data fetched which will be passed to the page component.
Example 1: Fetching a list of posts
import fetch from 'node-fetch'
export async function getStaticProps() {
const res = await fetch('https://api.example.com/posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
export default function Blog({ posts }) {
// Render posts...
}
In the above example, we fetch a list of posts from an API at build time. The fetched posts are passed to the Blog component as a prop.
In this tutorial, we have learned:
getStaticProps
is and its purposeNext, you can learn about other data fetching methods provided by Next.js like getServerSideProps
and getInitialProps
.
You can refer to the official Next.js documentation for more details: https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
Fetch a list of users from the JSONPlaceholder API and display them on a page. API Endpoint: https://jsonplaceholder.typicode.com/users
Fetch a single user's details from the JSONPlaceholder API based on a user ID and display it on a page. You should create a dynamic route for this. API Endpoint: https://jsonplaceholder.typicode.com/users/{id}
Solutions:
1. You can use getStaticProps
to fetch the list of users and pass them as props to your page.
2. For fetching a single user's details, you would need to use getStaticPaths
along with getStaticProps
. In getStaticPaths
, you define the list of IDs that should be pre-rendered at build time.
Remember to always test your code and understand what each part of the code does. Happy coding!