Static Site Generation (SSG) is a modern web development technique that pre-render pages at build time, allowing for fast page loads and better performance. Next.js, a popular React framework, provides excellent support for SSG out of the box. In this article, we’ll explore how to implement Static Site Generation with Next.js and provide code examples to help you get started.
What is Static Site Generation?
Static Site Generation is a method where HTML pages are generated at build time and served to a client at request time. Unlike Server-Side Rendering (SSR), where pages are generated on each request, SSG improves performance by serving pre-rendered static pages and reducing the server load.
Why Use Next.js for Static Site Generation?
Next.js is a React framework that offers hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more. Next.js allows developers to create both static and dynamic web applications efficiently. It makes implementing SSG straightforward thanks to its built-in capabilities.
Steps to Implement SSG in Next.js
1. Setting up a Next.js project
First, you’ll need to create a new Next.js application. You can quickly set up a new project using create-next-app
. If you haven't already, install Node.js on your machine and run the following command:
npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
2. Create Pages with getStaticProps
To generate static pages, use the getStaticProps
function provided by Next.js. This function fetches data at build time and passes it as props to the page component. Let's create a simple page that displays a list of articles.
In the pages
directory, create a new file named articles.tsx
:
import { GetStaticProps } from 'next';
type Article = {
id: number;
title: string;
content: string;
};
type ArticlesProps = {
articles: Article[];
};
export default function Articles({ articles }: ArticlesProps) {
return (
<div>
<h1>Articles</h1>
{articles.map((article) => (
<article key={article.id}>
<h2>{article.title}</h2>
<p>{article.content}</p>
</article>
))}
</div>
);
}
export const getStaticProps: GetStaticProps = async () => {
// Simulating an API call or database query
const articles: Article[] = [
{ id: 1, title: 'First Article', content: 'This is the content of the first article.' },
{ id: 2, title: 'Second Article', content: 'This is the content of the second article.' },
];
return {
props: {
articles,
},
};
};
3. Dynamic Routes and getStaticPaths
For dynamic routes, such as individual article pages, you need to use getStaticPaths
along with getStaticProps
. This combination allows you to define which dynamic pages should be generated at build time.
Create a new file in the pages
directory: articles/[id].tsx
.
import { GetStaticProps, GetStaticPaths } from 'next';
type Article = {
id: number;
title: string;
content: string;
};
type ArticleProps = {
article: Article;
};
export default function Article({ article }: ArticleProps) {
return (
<div>
<h1>{article.title}</h1>
<p>{article.content}</p>
</div>
);
}
export const getStaticPaths: GetStaticPaths = async () => {
// Simulating an API call or database query to get article ids
const articles: Article[] = [
{ id: 1, title: 'First Article', content: 'This is the content of the first article.' },
{ id: 2, title: 'Second Article', content: 'This is the content of the second article.' },
];
const paths = articles.map((article) => ({
params: { id: article.id.toString() },
}));
return { paths, fallback: false };
};
export const getStaticProps: GetStaticProps = async (context) => {
const { id } = context.params!;
// Simulating an API call or database query
const article: Article = { id: Number(id), title: `Article ${id}`, content: `This is the content of article ${id}.` };
return {
props: {
article,
},
};
};
4. Build and Export the Static Site
Once you have completed your pages and configured static generation, you can build your static site with the following command:
npm run build
After building, use:
npm run export
To export the website as a static HTML application into the out
directory.
Conclusion
Static Site Generation with Next.js is a powerful feature that enhances the performance and SEO of your application by serving pre-rendered, static pages. By leveraging the getStaticProps
and getStaticPaths
functions, you can efficiently create both static and dynamic pages.
Next.js, with its robust ecosystem, simplifies many aspects of web development including SSG, while also allowing you to write clean and type-safe code with TypeScript. Now that you know how to implement Static Site Generation, you can start building blazing-fast websites with Next.js.