Next.js Tutorial – Part 8 | Static Site Generation (SSG) | getStaticProps and getStaticPaths

In this video, we will build an e-commerce website and learn how to use getStaticProps and getStaticPaths in Next.js to statically generate our website.

—-
Repository: https://github.com/bmvantunes/youtube-2020-april-nextjs-part8
—-
Next.js documentation: https://nextjs.org/docs/basic-features/data-fetching
Next.js Blog: https://nextjs.org/blog/next-9-3#next-gen-static-site-generation-ssg-support
—-
Timeline:
00:00 Introduction to SSG
03:35 Setup SQLite
06:15 Using getStaticProps to create the Landing page
13:55 Using getStaticProps and getStaticPaths for the Details page
29:21 Styling with Material-UI
43:34 Adding pagination to the Landing page using getStaticProps and getStaticPaths
56:39 A challenge for you and conclusion
—-

The next description is a “Copy-paste” from Next.js Blog Post + Documentation:

You should use getStaticProps if:
1. The data required to render the page is available at build time ahead of a user’s request.
2. The data comes from headless CMS.
3. The data can be publicly cached (not user-specific).
4. 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.

Because getStaticProps runs at build time, it does not receive data that’s only available during request time, such as query parameters or HTTP headers as it generates static HTML.

Write server-side code directly
Note that getStaticProps runs only on the server-side. It will never be run on the client-side. It won’t even be included in the JS bundle for the browser. That means you can write code such as direct database queries without them being sent to browsers. You should not fetch an API route from getStaticProps — instead, you can write the server-side code directly in getStaticProps.

Statically Generates both HTML and JSON
When a page with getStaticProps is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running getStaticProps.

This JSON file will be used in client-side routing through next/link (documentation) or next/router (documentation). When you navigate to a page that’s pre-rendered using getStaticProps, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will not call getStaticProps as only the exported JSON is used.

—-
Follow me on:
Twitter: https://twitter.com/bmvantunes
Dev.to: https://dev.to/bmvantunes
Website: https://brunoantunes.net
Github: https://github.com/bmvantunes
LinkedIn: https://www.linkedin.com/in/bmvantunes

Source: https://www.youtube.com/watch?v=MxlmfI9IxVs

Leave a Reply

Your email address will not be published. Required fields are marked *