#nextjs #ssg #performance #generateStaticParams

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:

  1. Next.js runs generateStaticParams.
  2. It gets the list (e.g., ['hello-world', 'nextjs-14']).
  3. It renders HTML for each of those pages and saves them to disk.
  4. 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

  1. Create a dynamic route /users/[id].
  2. Implement generateStaticParams to return IDs ['1', '2', '3'].
  3. Run npm run build.
  4. Read the console output. Look for the ● (Static) symbol next to your routes.
  5. Check the .next/server/app/users folder. You will see 1.html, 2.html, etc. PHYSICAL FILES!

See you tomorrow for Dynamic Rendering & SSR (when Static isn’t enough)! πŸ”„