Static Site Generation (SSG) & Static Exports

▲ Next.js Lesson 5 Intermediate

Static Site Generation (SSG) pre-renders pages at build time, optimizing load performance. Next.js also supports fully static exports, allowing projects to be hosted on simple static servers.

1 generateStaticParams and output export

Key concepts for static generation in Next.js include:

  • Static Pre-rendering: Renders pages to static HTML during the build process, reducing runtime server overhead.
  • generateStaticParams(): Used with dynamic routes to pre-generate paths at build time (e.g. generating static pages for a list of blog post IDs).
  • Static Exports: Generates static assets (HTML, CSS, JS) that can be hosted on any static hosting provider (e.g. Netlify, GitHub Pages) without needing a Node.js server.
2 Defining Dynamic Parameters in Code

Let's check how to pre-render dynamic blog routes statically:

React — generateStaticParams
// Pre-generate dynamic routes at build time
export async function generateStaticParams() {
  const posts = await fetch('https://api.example.com/posts').then(res => res.json());

  // Return list of dynamic param values (e.g. [{ id: '1' }, { id: '2' }])
  return posts.map(post => ({
    id: post.id.toString()
  }));
}

export default function PostPage({ params }) {
  return (
    <article>
      <h1>Post ID: {{ params.id }}</h1>
      <p>Pre-rendered static article page.</p>
    </article>
  );
}
3 Code Challenge
Challenge: Research Next.js configuration settings. Update your next.config.js file to export static files by adding the line output: 'export', and run npm run build to check the generated output.