SSG (Static Site Generation) generates HTML at build time for fast, cacheable pages; SSR (Server-Side Rendering) generates HTML on each request for dynamic, real-time content.
Static Site Generation (SSG):
Server-Side Rendering (SSR):
Choosing Between Them:
Incremental Static Regeneration (ISR):
// pages/posts/[id].tsx - Pages Router SSG
import { GetStaticProps, GetStaticPaths } from 'next';
// 1. Define which paths to pre-render
export const getStaticPaths: GetStaticPaths = async () => {
const posts = await fetchAllPosts();
return {
paths: posts.map((post) => ({
params: { id: post.id.toString() },
})),
fallback: false, // 404 for unknown paths
};
};
// 2. Fetch data at build time
export const getStaticProps: GetStaticProps = async ({ params }) => {
const post = await fetchPost(params.id);
return {
props: { post },
// Optional: Revalidate every 60 seconds (ISR)
revalidate: 60,
};
};
export default function Post({ post }) {
return <article>{post.title}</article>;
}