Static Site Generation (SSG) is a powerful rendering strategy in Next.js that allows you to pre-render your pages at build time. This means that when a user requests a page, the HTML for that page is already generated and ready to be served by a CDN. This results in incredibly fast page load times and a better user experience, especially for content that doesn't change frequently.
The core idea behind SSG is to fetch your data at build time, not at request time. Next.js achieves this by providing special asynchronous functions that you can export from your page files. The most common one for SSG is getStaticProps.
When you export an async function named getStaticProps from a page file, Next.js will execute this function at build time. The object returned by getStaticProps will be passed as props to your page component. This is where you'll fetch your data from an API, a database, or any other source.
export async function getStaticProps() {
// Fetch data from an API or database
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
// Pass data to the page via props
return {
props: {
posts,
},
};
}In this example, getStaticProps fetches a list of posts from an external API. The posts data is then made available to the PostListPage component through its props.
function PostListPage({ posts }) {
// Render posts
return (
<div>
<h1>Blog Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}When you run next build, Next.js will execute getStaticProps for each page that uses it. The generated HTML, along with the pre-fetched data, will be placed in the .next/out directory (or served by a Next.js server when using SSR). This means that for every build, you get a fully static version of your website.
graph TD
A[User Request] --> B{Next.js Server}
B -- Page Not Found --> C[Build Time: getStaticProps Executes]
C -- Fetches Data --> D[External Data Source]
D -- Returns Data --> C
C -- Generates HTML --> E[Pre-rendered HTML]
B -- Serves Pre-rendered HTML --> A