Note: this post is valid as of Next 13 (not beta).
Next.js provides two methods to fetch data which is intended to be passed as props to a page: getStaticProps and getServerSideProps. In this blog post, we will explain the differences between these two methods and when to use each one.
getStaticProps is used to fetch data at build time and generate static HTML files for each page. This approach is used when the data is static or updated infrequently. When you use getStaticProps, the data is fetched during the build process and is included in the HTML files that are served to the client. This means that the data is available immediately, and the page can be loaded quickly.
Example:
export async function getStaticProps() { const res = await fetch("https://api.example.com/data"); const data = await res.json(); return { props: { data, }, }; }
getServerSideProps is used to fetch data at request time, and the data is not included in the HTML file that is served to the client. Instead, the data is fetched on each request and used to render the page. This approach is used when the data is dynamic and changes frequently. getServerSideProps can also be used to authenticate users and restrict access to certain pages.
Example (almost the same as getStaticProps):
export async function getServerSideProps(context) { const res = await fetch("https://api.example.com/data"); const data = await res.json(); return { props: { data, }, }; }
The primary difference between getStaticProps and getServerSideProps is when the data is fetched. getStaticProps fetches data at build time and generates static HTML files, while getServerSideProps fetches data at request time and does not generate static HTML files. Therefore, if the data is static or updated infrequently, use getStaticProps. If the data is dynamic or changes frequently, use getServerSideProps.
For instance, when building a blog site and all of the blog articles are known and stored in a database, it would make sense to use getStaticProps to incldue the data in the html files, without having to fetch it when the page is loaded.
One thing to keep in mind is that by using getServerSideProps in a component, your web app can no longer be exported as a static site (and for instance be hosted somewhere like S3). That request is handled on the server each time dynamically, which requires your application to be run with next start
.
getStaticProps and getServerSideProps are two important methods for fetching data in Next.js. Understanding the differences between them and their use cases is essential to building fast, efficient, and dynamic applications.