Day 10 β Static Site Generation (SSG): Building for Speed
π§ Day 10 β Static Site Generation (SSG): Building for Speed
Zero to Hero β Hands-on Next.js Tutorial
By default, Next.js tries to be Static. If your page doesnβt use dynamic data (like headers or cookies), Next.js renders it ONCE at build time. This is Static Site Generation (SSG). Itβs fast, cheap, and scalable (CDN friendly).
π¦ 1. The Dynamic Problem
If we have a blog src/app/blog/[slug]/page.tsx, Next.js doesnβt know which slugs exist at build time.
Does /blog/1 exist? /blog/cool-post?
So, by default, it waits until a user visits to render it (Dynamic Rendering). This is slower.
π© 2. generateStaticParams
We can tell Next.js exactly which routes to build in advance using generateStaticParams.
This replaces the old getStaticPaths.
// src/app/blog/[slug]/page.tsx
// 1. Tell Next.js which slugs to build
export async function generateStaticParams() {
const posts = await fetch('https://api.example.com/posts').then(res => res.json());
// Return an array of objects matching the [slug] param
return posts.map((post) => ({
slug: post.slug,
}));
}
// 2. The Main Page Component
export default async function Page({ params }: { params: { slug: string } }) {
const { slug } = params;
// ... fetch and render ...
}
The Magic:
When you run npm run build:
- Next.js runs
generateStaticParams. - It gets the list (e.g.,
['hello-world', 'nextjs-14']). - It renders HTML for each of those pages and saves them to disk.
- When a user visits, they get the instant HTML file. No DB call!
π§ 3. What about new posts?
If you add a new post to the DB after the build, what happens when someone visits /blog/new-post?
- If
dynamicParams = true(default): Next.js will generate it on-demand (SSR) the first time, cache it, and then serve it statically for everyone else. - If
dynamicParams = false: Next.js will return a 404 (useful for strict content like documentation).
π§ͺ Challenge: Day 10
- Create a dynamic route
/users/[id]. - Implement
generateStaticParamsto return IDs['1', '2', '3']. - Run
npm run build. - Read the console output. Look for the
β(Static) symbol next to your routes. - Check the
.next/server/app/usersfolder. You will see1.html,2.html, etc. PHYSICAL FILES!
See you tomorrow for Dynamic Rendering & SSR (when Static isnβt enough)! π