Static Site Generation (SSG) is a method in Next.js where the HTML pages are generated at build time and reused for each request. This technique is particularly efficient for content that does not change frequently.
With static generation, Next.js generates HTML for each page during the build process. The result is a collection of static files, including HTML, JavaScript and CSS, which can be hosted on a server or a CDN (Content Delivery Network).
2 Reliability: Static pages are less prone to server downtime because they don’t require database queries or server-side processing.
SSG is implemented in Next.js using the getStaticProps
function. This function runs during the build process and generates
static content for each page.
export async function getStaticProps() {
// Retrieve static data
const data = await fetchStaticData();
return { props: { data } };
}
function MyStaticPage({ data }) {
// Render logic of the page
}
Next.js also supports the static generation of pages with dynamic
routes through the use of getStaticPaths
. This function
defines which instances of a dynamic route should be generated at build
time.
export async function getStaticPaths() {
// Define paths for static generation
return {
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
fallback: false,
;
}
}
export async function getStaticProps({ params }) {
// Retrieve data based on the path
const data = await fetchData(params.id);
return { props: { data } };
}
While SSR generates the content on the server side for each request, SSG generates the pages once at build time. This reduces the server load and improves loading times, but limits the dynamics of the content.
Next.js 9.5 introduced Incremental Static Regeneration, a method that allows static content to be updated in the background after initial generation without restarting the entire build process.
Develop a simple blog application with Next.js that uses static page generation (SSG). The application should have the following functions:
Use a simple JSON structure for the blogposts. For example:
[
{
"id": "1",
"title": "First blog post",
"excerpt": "This is the beginning of my first blog post...",
"content": "Here is the full content of the first blog post..."
},
{
"id": "2",
"title": "Second blog post",
"excerpt": "This is the beginning of my second blog post...",
"content": "Here is the full content of the second blog post..."
}
]