Static Site Generation (Next.js)

Loading

Static Site Generation (SSG) is a powerful feature provided by Next.js that allows you to generate HTML at build time rather than on each request. This approach enables faster load times and a better user experience, especially for content that doesn’t change frequently.

In Next.js, SSG can be used to pre-render pages at build time, which means that the HTML for each page is generated when you run the build command (next build) and served as static files. These pages are then available for fast and efficient delivery by a CDN (Content Delivery Network).

1. What is Static Site Generation (SSG)?

SSG refers to the process where HTML files are generated at build time and then served as static assets. This method ensures that the content is pre-rendered and doesn’t rely on the server for each request, leading to:

  • Improved performance: Since the HTML is generated ahead of time, pages load almost instantly.
  • Better SEO: Static pages are fully rendered when served, so search engines can crawl them without issues.
  • Reduced server load: No need to re-render pages on every request, which reduces the load on your server.

2. How SSG Works in Next.js

In Next.js, Static Site Generation is implemented using the getStaticProps function. This function is run at build time to fetch data, render the page to HTML, and then save it as a static file. When the user requests the page, the pre-rendered HTML is served instantly.

2.1 Using getStaticProps in Next.js

Here’s an example of how to use getStaticProps to generate a static page with data fetched at build time.

// pages/index.js
import React from 'react';

const Home = ({ data }) => {
  return (
    <div>
      <h1>Static Site Generation with Next.js</h1>
      <p>{data}</p>
    </div>
  );
};

// getStaticProps runs at build time to fetch the data
export async function getStaticProps() {
  // Fetching data from an API or other source
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();

  // Returning data as props to be used by the component
  return {
    props: {
      data: data.message, // Pass the fetched data as a prop to the component
    },
  };
}

export default Home;
  • getStaticProps: This function fetches data and returns it as props. It is called only at build time. When the build is triggered, Next.js pre-renders the page with the data and serves it as static HTML.
  • The data is fetched from an external API (or any other source) and passed as a prop to the React component.

3. Benefits of Static Site Generation (SSG)

3.1 Performance

SSG ensures that HTML is pre-built, which results in extremely fast page loads since the browser can directly render static files without waiting for JavaScript or data fetching. Static files can be served from a CDN, reducing the load time significantly.

3.2 SEO Benefits

Static pages are easily crawlable by search engines. Since the HTML is pre-generated, search engines can index the content effectively, leading to better SEO rankings for your website.

3.3 Lower Server Costs

SSG reduces the load on your server, as there is no need for server-side processing on each page request. The pages are simply served as static files, which can be hosted on a CDN or static file hosting services.

3.4 Content that Doesn’t Change Frequently

SSG is ideal for pages that don’t need to change frequently or don’t depend on user data, such as blogs, documentation, marketing pages, portfolios, or product landing pages.


4. Dynamic Routes with Static Site Generation

Next.js allows you to use dynamic routes with Static Site Generation. To do so, you can use getStaticPaths alongside getStaticProps.

4.1 Using getStaticPaths for Dynamic Routes

When building a page with dynamic content (like blog posts or product details), you need to specify which pages should be generated at build time. This is done using getStaticPaths, which tells Next.js which dynamic routes should be pre-rendered.

// pages/posts/[id].js
import React from 'react';

const Post = ({ post }) => {
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
};

// Fetch data and generate static paths at build time
export async function getStaticPaths() {
  // Simulating fetching available post IDs
  const response = await fetch('https://api.example.com/posts');
  const posts = await response.json();

  // Generating paths for each post
  const paths = posts.map((post) => ({
    params: { id: post.id.toString() },  // Use dynamic parameter (id)
  }));

  return {
    paths,
    fallback: false,  // If a path is not found, show 404 page
  };
}

// Fetch data for a specific post based on the id
export async function getStaticProps({ params }) {
  const { id } = params;
  const response = await fetch(`https://api.example.com/posts/${id}`);
  const post = await response.json();

  return {
    props: {
      post,
    },
  };
}

export default Post;
  • getStaticPaths: This function fetches the list of dynamic routes (like blog post IDs). Next.js uses this data to know which routes to pre-render at build time.
  • getStaticProps: It fetches the data for the specific page (post) based on the dynamic parameter (id in this case).
  • fallback: false: If a page is not generated during build time, a 404 error page is displayed. You can also use true or 'blocking' for fallback behavior, depending on whether you want to show a loading state or wait for the page to be generated.

5. Incremental Static Regeneration (ISR)

Next.js offers a feature called Incremental Static Regeneration (ISR), which allows you to update static content after the site is built. This is especially useful for pages that don’t need to be updated on every request but require periodic updates (e.g., news articles or product prices).

With ISR, you can specify a revalidate time in getStaticProps that determines how often the static page should be re-rendered.

// pages/index.js
export async function getStaticProps() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();

  return {
    props: {
      data: data.message,
    },
    revalidate: 60,  // Re-generate the page every 60 seconds
  };
}
  • revalidate: After the specified number of seconds (60 seconds in the example above), Next.js will regenerate the page in the background on the next request, ensuring the content stays fresh.

6. Static Site Generation vs Server-Side Rendering (SSR)

Both SSG and SSR allow you to render pages dynamically, but they serve different use cases:

  • SSG (Static Site Generation):
    • Content is generated at build time.
    • Ideal for pages that don’t change often, such as blogs, portfolios, or documentation.
    • Pages load faster since they are pre-generated and cached.
    • Great for SEO as content is available immediately for search engine crawlers.
  • SSR (Server-Side Rendering):
    • Content is generated on each request.
    • Suitable for pages that need dynamic data (e.g., dashboards, user profiles, or content that changes frequently).
    • Slightly slower than SSG because the server has to render the page on every request.

7. When to Use Static Site Generation (SSG)

SSG is ideal for pages that:

  • Don’t require frequent updates.
  • Don’t depend on user-specific data.
  • Benefit from fast load times and SEO (e.g., marketing pages, blogs, landing pages).
  • Can be pre-rendered ahead of time during the build process.

Some examples include:

  • Blogs
  • Documentation websites
  • Landing pages
  • E-commerce product listings (when the product data doesn’t change frequently)

Leave a Reply

Your email address will not be published. Required fields are marked *