Static Site Generation(SSG) in Next.js (Page Router)


Objectives

Learn how Static Site Generation(SSG) works in Next.js.

What is Static Generation?

Static Generation describes the process of compiling and rendering a website or app at build time. The output is a bunch of static files, including the HTML file itself and assets like JavaScript and CSS.

How does Next.js use Static Generation?

Next.js provides a few different APIs to fetch data including getStaticProps and getServerSideProps, which, depending on how they’re used, determines how Next.js will build your app. We will dive into these two APIs in the next two posts. (getStaticProps in this post and getServerSideProps in the next post)

getStaticProps

Implement the function

If you export a function called getStaticProps from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps. To fetch this data on pre-render, Next.js allows you to export an async function called getStaticProps from the same file. This function gets called at build time and lets you pass fetched data to the page's props on pre-render.

Notice that getStaticProps always runs on the server and never on the client.

Let's use our beloved Todo API for example:

Any props will be passed to the page component and can be viewed on the client-side in the initial HTML. To summarize, you should use this function if:

  • The data required to render the page is available at build time ahead of a user’s request
  • The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance

Write server code directly

Our original approach might produce additional requests to the API route if we fetch the data from getStaticProps (it might be called several times when our application scales). Instead of fetching an API route from getStaticProps, you can write the server-side code directly in getStaticProps, which means that the logic for fetching the data from the CMS can be shared by using a lib/ directory. Then it can be shared with getStaticProps. It will make our code more DRY :)

This approach is also useful if you need to provide the data to multiple components on the page. You can also use this approach if you need to fetch data from an external API endpoint at build time.

Conclusion

Static Site Generation(SSG) is a great feature in Next.js. It provides us a way to pre-render our page at build time. It can improve the performance of our website and also help us to improve the SEO. It's definitely a great feature to have in our toolbox 🧰 !

Resources