Static Site Generation (SSG) is a powerful feature of Next.js that allows you to pre-render pages at build time. This approach results in faster page loads, improved SEO, and reduced server load. In this guide, we'll explore how to implement SSG in your Next.js applications.
Static Site Generation involves generating HTML files for each route during the build process. These static files are then served directly by a CDN or web server, eliminating the need for server-side rendering on every request. This makes SSG ideal for content-heavy websites, blogs, and documentation sites.
Next.js provides several ways to implement SSG, including getStaticPaths, getStaticProps, and the export command. Let's dive into each of these methods.
getStaticPathsThe getStaticPaths function is used to specify which paths should be pre-rendered at build time. This is particularly useful for dynamic routes where you need to generate pages based on data fetched from an API or database.
Suppose you have a blog with posts stored in a CMS, and you want to pre-render each post page during the build process.
// pages/posts/[id].js
export async function getStaticPaths() {
// Fetch all post IDs from your CMS
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
// Generate paths for each post
const paths = posts.map(post => ({
params: { id: post.id.toString() }
}));
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
// Fetch the data for a single post by ID
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return {
props: {
post
}
};
}
export default function Post({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
getStaticPropsThe getStaticProps function is used to fetch data that will be passed to the page as props during the build process. This data can then be rendered in your component.
Let's say you have a landing page that displays recent blog posts.
// pages/index.js
export async function getStaticProps() {
// Fetch recent posts from your CMS
const res = await fetch('https://api.example.com/posts/recent');
const recentPosts = await res.json();
return {
props: {
recentPosts
}
};
}
export default function HomePage({ recentPosts }) {
return (
<div>
<h1>Welcome to Our Blog</h1>
<ul>
{recentPosts.map(post => (
<li key={post.id}>
<a href={`/posts/${post.id}`}>{post.title}</a>
</li>
))}
</ul>
</div>
);
}
export CommandFor simpler use cases, you can use the next export command to generate static HTML files for your entire site. This approach is suitable for sites with no server-side rendering needs.
npm run build && npm run export
This will generate a out directory containing static HTML files for your site.
getStaticPaths to handle dynamic routes that may not be available at build time.// pages/posts/[id].js
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
const paths = posts.map(post => ({
params: { id: post.id.toString() }
}));
return { paths, fallback: 'blocking' };
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
// Revalidate every 10 seconds
return {
props: {
post
},
revalidate: 10
};
}
export default function Post({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
Static Site Generation is a powerful feature in Next.js that can significantly improve the performance and scalability of your web applications. By leveraging getStaticPaths, getStaticProps, and the export command, you can pre-render pages at build time, resulting in faster load times and better SEO. Remember to optimize data fetching, implement fallback strategies, and consider using Incremental Static Regeneration for dynamic content.
By following this guide, you should now have a solid understanding of how to implement SSG in your Next.js projects. Happy coding!