Next JS (SSG) Static Generation
Static Generation (SSG) in Next.js is a method of pre-rendering pages at build time. This means that when you build your Next.js application, it generates HTML for each page that is specified to use SSG, allowing for fast loading times and optimal performance when users request those pages. SSG is especially useful for content that doesn’t change often, such as blog posts, documentation, or landing pages.
1. What is Static Generation (SSG)?
Static Generation allows you to generate HTML pages during the build process, which can be served directly from a CDN. This contrasts with Server-Side Rendering (SSR), where pages are generated on each request. SSG provides a faster experience for users because the HTML files are already generated and ready to be served.
2. When to Use Static Generation
- Content That Does Not Change Frequently: Ideal for blog posts, marketing pages, and documentation.
- Performance-Critical Pages: SSG pages load quickly because they can be served from a CDN.
- SEO Requirements: SSG provides fully rendered HTML for search engines to index, improving SEO.
3. How to Implement Static Generation in Next.js
To use Static Generation in Next.js, you can export a function called getStaticProps
from your page component. This function fetches data at build time and passes it to the page as props.
a. Basic Example of Static Generation
// pages/blog/[id].js
import { useRouter } from 'next/router';
export default function BlogPost({ post }) {
const router = useRouter();
// If the page is not yet generated, this will be displayed until it becomes available.
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
// This function is called at build time
export async function getStaticProps({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return {
props: {
post, // Will be passed to the page component as props
},
};
}
// This function specifies which dynamic paths to pre-render at build time
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() }, // Must be a string for dynamic routes
}));
return { paths, fallback: true }; // Enable fallback for dynamic routes
}
4. Breaking Down the Example
getStaticProps
: This function fetches data (in this case, a blog post) during the build time. The data fetched is passed to the page component as props.getStaticPaths
: This function tells Next.js which dynamic routes to pre-render at build time. It fetches a list of blog posts and returns an array of paths.- The
fallback
key ingetStaticPaths
determines what happens if a user requests a path that hasn't been generated yet.- If set to
false
, any requests to paths that were not returned bygetStaticPaths
will result in a 404 page. - If set to
true
, Next.js will serve a fallback version of the page while it is being generated on the server.
- If set to
- The
5. Fallback Pages
When using fallback: true
, you can handle loading states in your component. If the requested page hasn’t been generated yet, it will show the fallback UI until the page is built.
6. Benefits of Static Generation
Performance: Pre-rendered pages are fast because they can be served directly from a CDN.
SEO Optimization: Since the pages are rendered as static HTML, they are easily indexed by search engines.
Reduced Server Load: Because the pages are generated at build time, they reduce the number of requests to your server at runtime.
7. Limitations of Static Generation
Build Time: For large sites with many pages, the build time can increase significantly. You may need to consider incremental static generation (ISR) to handle this.
Data Freshness: SSG is not suitable for pages that need to be updated frequently since the content is generated at build time. To address this, you can use Incremental Static Regeneration (ISR).
8. Incremental Static Regeneration (ISR)
Next.js also supports ISR, which allows you to update static content after the site has been built without having to rebuild the entire site. You can specify a revalidate
period in your getStaticProps
function to determine how often the page should be regenerated.
a. Example of ISR
export async function getStaticProps() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
return {
props: {
posts,
},
revalidate: 10, // Re-generate the page every 10 seconds if a request comes in
};
}
Summary
Static Generation (SSG) in Next.js allows you to pre-render pages at build time, providing fast performance and better SEO for content that does not change frequently. Key points about SSG include:
Performance: Pre-rendered HTML is served quickly, improving load times.
SEO: Search engines can easily crawl and index fully rendered HTML.
Data Fetching: Use
getStaticProps
for data fetching at build time.Dynamic Routes: Use
getStaticPaths
to specify which dynamic routes to pre-render.Fallback Handling: Handle fallback UI for paths that are not pre-rendered.
Incremental Static Regeneration (ISR): Update static content after the build without a full rebuild by using revalidation.
By effectively utilizing Static Generation, you can create high-performance, SEO-friendly Next.js applications that serve static content efficiently.