tezvyn:

Next.js SSG: Pre-render Pages for Maximum Speed

AI-drafted, machine-checkedSource: nextjs.orgintermediate

Next.js's Static Site Generation (SSG) pre-renders pages into static HTML at build time, serving them instantly from a CDN. It's ideal for content that rarely changes, like blog posts, ensuring top performance. The main pitfall is serving stale data.

WHY IT EXISTS To deliver web pages at the fastest possible speed while minimizing server load. Traditional server-rendering computes a page on every user request, which can be slow and costly. SSG computes the page just once, ahead of time, so it can be served instantly from a global CDN without any server-side computation per request.

THE MENTAL MODEL SSG is like printing a newspaper. All the articles (data fetching) and layout work (rendering) are done once at the printing press (build time). Readers then receive a finished, static copy. When a user requests a page, the server just hands over a pre-built HTML file, instead of having to dynamically assemble the page from scratch.

HOW IT WORKS During the build process (next build), Next.js looks for pages that export a function called getStaticProps. For dynamic routes like /posts/[id], it first calls getStaticPaths to get a list of all possible paths to generate (e.g., /posts/1, /posts/2). Then, for each path, it runs getStaticProps to fetch data for that specific page. Finally, it uses this data to render the page into a static HTML file. The collection of these HTML files, along with necessary JavaScript, is what you deploy.

WHEN TO USE IT Use SSG for any content that can be determined at build time and doesn't change on a per-user basis. This is perfect for marketing sites, blog posts, documentation, and e-commerce product listings. The result is a site that feels instantaneous to the user and is highly optimized for search engine crawlers.

WHEN NOT TO USE IT Avoid SSG for pages that require live data or are highly personalized. A user dashboard, a social media feed, or a live chat application are poor candidates because the content is unique to the user and the moment. For these cases, Server-Side Rendering (SSR) with getServerSideProps or Client-Side Rendering (CSR) are better choices.

ONE CANONICAL EXAMPLE A blog with multiple posts. The getStaticPaths function would query your database or CMS to get a list of all post slugs. Then, for each slug, getStaticProps would fetch the specific content for that one post. At build time, Next.js generates post-1.html, post-2.html, etc. When a user visits /posts/post-1, they are served the pre-built HTML file instantly.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.