Published on

NextJS getStaticProps() vs getServerSideProps()

Authors
  • avatar
    Name
    Kieran Hauser
    Twitter

Understanding the Difference Between getStaticProps() and getServerSideProps() in Next.js

Next.js is a popular framework for building server-side rendered React applications. When building a Next.js application, you'll often need to fetch data from an external API or database to render your pages. Next.js provides two methods for fetching data: getStaticProps() and getServerSideProps(). In this article, we'll explain the difference between these two methods.

getStaticProps()

getStaticProps() is used for generating static pages at build time. When you use getStaticProps(), Next.js will pre-render your page at build time, and the resulting HTML will be reused for each request. This is great for pages that don't need to be updated frequently and have content that can be pre-rendered.

Here's an example of using getStaticProps() to fetch data from an external API:

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 use getStaticProps() to fetch data from an external API and return it as a prop. The resulting HTML will be generated at build time, and the data prop will be available on each page request.

getServerSideProps()

getServerSideProps() is used for generating dynamic pages on each request. When you use getServerSideProps(), Next.js will pre-render your page on each request, and the resulting HTML will be generated on the server and sent to the client. This is great for pages that need to be updated frequently and have content that can't be pre-rendered.

Here's an example of using getServerSideProps() to fetch data from an external API:

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

  return {
    props: {
      data
    }
  };
}

In this example, we use getServerSideProps() to fetch data from an external API and return it as a prop. The resulting HTML will be generated on each page request, and the data prop will be available on each page request.

Conclusion

In summary, getStaticProps() is used for generating static pages at build time, while getServerSideProps() is used for generating dynamic pages on each request. By understanding the differences between these two methods, you can choose the best approach for fetching data in your Next.js application.