Introduction
While Server-Side Rendering (SSR) excels at delivering fresh data on every request, many web pages don't require such real-time updates. For content that can be pre-rendered at build time, Next.js offers Static Site Generation (SSG). SSG is a powerful optimization strategy that generates HTML files during the build process, serving them as static assets. This lesson will dive into SSG, explaining how it works with getStaticProps and getStaticPaths. You'll learn when to leverage SSG for maximum performance and cost efficiency, making your applications lightning-fast and highly scalable.
Key Concepts
What is Static Site Generation (SSG)?
SSG means that the HTML for a page is generated once at build time and then reused for every request.
-
Process: During the build process (
next build), Next.js runs the page's data fetching functions (getStaticProps,getStaticPaths), generates static HTML files, and saves them. When a user requests the page, the pre-built HTML is served directly from a CDN. -
Use Cases: Ideal for content that doesn't change frequently, such as blog posts, documentation, marketing pages, e-commerce product listings (when product data isn't volatile).
-
Incremental Static Regeneration (ISR): A hybrid approach where static pages can be regenerated in the background after deployment, allowing content updates without a full rebuild. This is achieved using the
revalidateoption ingetStaticProps.
getStaticProps Function
-
This is an asynchronous function that runs exclusively on the server-side, at build time.
-
It must be exported from a page file.
-
It fetches data required to render the page and passes it as
propsto the page component. -
It cannot be used with
getServerSidePropson the same page.
Signature: javascript export async function getStaticProps(context) { // ... your build-time logic (e.g., fetch from API, read markdown files) return { props: { // will be passed to the page component as props }, revalidate: 60, // Optional: enable ISR, revalidate every 60 seconds }; }
getStaticPaths Function (for Dynamic SSG)
-
When using
getStaticPropswith a dynamic route (e.g.,pages/posts/[id].js), Next.js needs to know which paths to pre-render at build time. This is wheregetStaticPathscomes in. -
It must be exported from a dynamic page file.
-
It returns an object with a
pathsarray (specifying all possible dynamic paths) and afallbackkey (true,false, or'blocking'). -
fallback: false: Only paths returned bygetStaticPathsare pre-rendered. Other paths result in a
-
fallback: true: Paths not pre-rendered will be rendered on the first request (SSR-like), then cached for subsequent requests. Shows a loading state.
fallback: 'blocking': Similar totrue, but blocks until the page is generated, no loading state.
Code Example: SSG with getStaticProps and getStaticPaths
jsx // pages/posts/[id].js import Layout from '../../components/Layout';
export default function Post({ post }) { if (!post) return <div>Loading...</div>; // For fallback: true
return ( <Layout> <h1>{post.title}</h1> <p>{post.body}</p> </Layout> ); }
export async function getStaticPaths() { // Fetch a list of all possible post IDs const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const posts = await res.json();
// Get the paths we want to pre-render based on posts const paths = posts.map((post) => ({ params: { id: post.id.toString() }, }));
return { paths, fallback: false }; // 'fallback: false' means other routes 404 }
export async function getStaticProps({ params }) {
// Fetch individual post data based on the 'id' parameter
const res = await fetch(https://jsonplaceholder.typicode.com/posts/${params.id});
const post = await res.json();
return { props: { post } }; }
Key Takeaways
-
SSG pre-renders pages at build time, serving static HTML files for extreme performance.
-
Use
getStaticPropsto fetch data at build time for static pages. -
For dynamic routes using SSG,
getStaticPathsis required to specify which paths to pre-render. -
fallbackingetStaticPathscontrols behavior for paths not pre-rendered. -
ISR with
revalidateallows static pages to be updated in the background post-deployment.