Next.js has become one of the most popular frameworks for building React applications, and for good reason. One of its most powerful features is the ability to generate static sites that are blazingly fast and SEO-friendly.
Why Static Site Generation?
Static Site Generation (SSG) offers several advantages:
- Performance - Pre-rendered HTML served directly from a CDN
- SEO - Search engines can easily crawl and index your content
- Security - No server-side code execution means fewer attack vectors
- Cost-effective - Host for free on platforms like GitHub Pages, Netlify, or Vercel
How It Works
Next.js can generate static HTML at build time. Here's a simple example:
// pages/blog/[slug].tsx
import { GetStaticProps, GetStaticPaths } from 'next';
export const getStaticPaths: GetStaticPaths = async () => {
const posts = await getAllPosts();
return {
paths: posts.map((post) => ({
params: { slug: post.slug }
})),
fallback: false
};
};
export const getStaticProps: GetStaticProps = async ({ params }) => {
const post = await getPostBySlug(params.slug);
return {
props: { post }
};
};
Configuration for Static Export
To enable static export, update your next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
images: {
unoptimized: true,
},
};
export default nextConfig;
Deployment
Once configured, building your static site is simple:
npm run build
This generates an out/ directory containing your complete static site, ready to deploy anywhere.
Conclusion
Next.js makes static site generation incredibly straightforward while still providing the full power of React. Whether you're building a blog, documentation site, or marketing pages, SSG with Next.js is a fantastic choice.