1
Static Site Generation (SSG)
Pre-render pages at build time for maximum performance and scalability
Beginner
What It Does
- Force Static Generation
Forces Static Generation even though this page uses dynamic route segments ([[...slug]]) and server-side functions like getData() and getTemplateType(), Next.js will pre-render all possible routes at build time instead of generating them on-demand. - Overrides Default Behavior
Normally, pages with dynamic segments like[[...slug]]would be rendered on each request (Server-Side Rendering). - Build-Time Execution
All the async functions (getData, getTemplateType) will be executed during the build process, and the results will be cached as static HTML files.
Why We Use It
- Performance
Static pages load much faster than server-rendered pages - Scalability
No server processing needed for each request - Better SEO
Better crawling and indexing by search engines - Reduced Costs
Lower server load and hosting costs
How it works
- 1Build process starts
When you run
npm run build - 2Generate all routes
Next.js identifies pages with generateStaticParams
- 3Fetch data for each route
All async functions execute during build
- 4Generate static HTML files
Each page is rendered and saved to disk
- 5Serve pre-built files
Users get instant HTML from CDN
Code
// app/blog/[slug]/page.tsx
// Force static generation
export const dynamic = 'force-static'
// Optional: Revalidate every 5 minutes (ISR)
export const revalidate = 300
export async function generateStaticParams() {
// Fetch all possible slugs at build time
const posts = await fetch('https://api.example.com/posts')
.then(res => res.json())
return posts.map((post) => ({
slug: post.slug,
}))
}
export default async function BlogPost({ params }) {
const { slug } = params
// This data is fetched at BUILD TIME
const post = await fetch(`https://api.example.com/posts/${slug}`)
.then(res => res.json())
return (
<article>
<h1>{post.title}</h1>
<div>{post.content}</div>
</article>
)
}