Static Site Generation (SSG)
Static Site Generation is a rendering method where pages are generated at build time. Instead of rendering on each request, Next.js creates static HTML files that can be served directly from a CDN.
Think of SSG like printing a book. Once printed, the book can be distributed and read without any additional work. Similarly, static pages are generated once and served instantly to every visitor.
How SSG Works
When you build your Next.js application with SSG, here's the process:
Next.js runs through all your pages that use getStaticProps. It fetches the data for each page and generates the HTML at build time.
The generated HTML files are stored and served directly when users request those pages. No server processing is needed for each request - just file serving.
This makes SSG incredibly fast because the pages are pre-built and can be served from edge locations worldwide.
Implementing SSG
To use SSG, you export a getStaticProps function from your page component. This function runs at build time and returns the props for your page.
// app/blog/[slug]/page.js
export async function getStaticProps({ params }) {
const post = await getPost(params.slug);
return {
props: {
post,
},
};
}
export async function getStaticPaths() {
const posts = await getAllPosts();
const paths = posts.map(post => ({
params: { slug: post.slug },
}));
return {
paths,
fallback: false,
};
}
export default function BlogPost({ post }) {
return (
<article>
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</article>
);
}
The getStaticPaths function tells Next.js which pages to generate at build time. For dynamic routes, you need to specify all possible paths.
Benefits of SSG
Static Site Generation offers several advantages:
Performance: Static files load incredibly fast. Users get instant content without waiting for server processing.
Scalability: Static files can be served from CDNs, handling millions of visitors without breaking a sweat.
Security: No server processing means fewer attack vectors. Static sites are inherently more secure.
Cost: Hosting static files is much cheaper than running servers. You can host on platforms like Vercel or Netlify for free.
When to Use SSG
SSG is perfect for content that doesn't change frequently. Blog posts, documentation, marketing pages, and portfolios are ideal candidates.
If your content updates daily or less often, SSG is usually the best choice. You get blazing fast performance without sacrificing freshness.
However, if your content changes every second or needs personalization, SSR or client-side rendering might be better options.