Article image Static Site Generation (SSG) with Next.js

38. Static Site Generation (SSG) with Next.js

Page 82 | Listen in audio

Static Site Generation (SSG) is a powerful feature of Next.js that allows developers to build optimized and highly performant web applications by pre-rendering pages at build time. This approach contrasts with traditional server-side rendering, where pages are generated on each request, and client-side rendering, where content is loaded dynamically in the browser. By generating static HTML files upfront, SSG can significantly improve load times and reduce server load, making it an ideal choice for many web projects.

Next.js, a popular React framework, offers robust support for SSG, making it easy for developers to implement in their applications. With Next.js, you can create static pages that are pre-rendered at build time, ensuring that users receive fully rendered HTML pages when they visit your site. This approach not only enhances performance but also improves SEO, as search engines can easily crawl and index pre-rendered content.

To get started with SSG in Next.js, you need to understand how the framework handles page rendering. In Next.js, pages are defined as React components within the pages directory. Each file in this directory corresponds to a route in your application. For example, a file named about.js in the pages directory would be accessible at /about in the browser.

To enable Static Site Generation for a page, you can use the getStaticProps function. This function allows you to fetch data at build time and pass it as props to your page component. Here's a simple example:

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

  return {
    props: {
      data,
    },
  };
}

export default function Page({ data }) {
  return (
    <div>
      <h1>Static Site Generation with Next.js</h1>
      <p>Data: {JSON.stringify(data)}</p>
    </div>
  );
}

In this example, the getStaticProps function fetches data from an external API and returns it as props to the Page component. The data is then rendered on the page, and the HTML is generated at build time. This means that when a user visits the page, they receive a fully rendered HTML document with the data already embedded.

One of the key benefits of SSG is its ability to handle dynamic routes. In Next.js, you can create dynamic routes by using square brackets in the file name, such as [id].js. To generate static pages for these dynamic routes, you need to use the getStaticPaths function in conjunction with getStaticProps. Here's an example:

export async function getStaticPaths() {
  const res = await fetch('https://api.example.com/items');
  const items = await res.json();

  const paths = items.map((item) => ({
    params: { id: item.id.toString() },
  }));

  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  const res = await fetch(`https://api.example.com/items/${params.id}`);
  const item = await res.json();

  return {
    props: {
      item,
    },
  };
}

export default function ItemPage({ item }) {
  return (
    <div>
      <h1>Item: {item.name}</h1>
      <p>Description: {item.description}</p>
    </div>
  );
}

In this example, getStaticPaths fetches a list of items and returns an array of paths based on their IDs. For each path, getStaticProps fetches the corresponding item data and passes it to the ItemPage component. This approach allows you to pre-render pages for each item at build time, resulting in a static version of each page.

Next.js also supports Incremental Static Regeneration (ISR), which allows you to update static pages after they have been built. This feature is useful for applications that require fresh content without a full rebuild. To use ISR, you can add a revalidate property to the return object of getStaticProps:

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

  return {
    props: {
      data,
    },
    revalidate: 10, // Re-generate the page every 10 seconds
  };
}

export default function Page({ data }) {
  return (
    <div>
      <h1>Incremental Static Regeneration</h1>
      <p>Data: {JSON.stringify(data)}</p>
    </div>
  );
}

In this example, the page will be regenerated at most once every 10 seconds, ensuring that users receive updated data without a full rebuild of the site. This approach combines the benefits of SSG with the flexibility of server-side rendering, allowing you to create highly performant applications that can adapt to changing data.

Static Site Generation with Next.js offers numerous advantages for developers and users alike. By pre-rendering pages at build time, you can deliver fast, SEO-friendly web applications that scale efficiently. Whether you're building a blog, an e-commerce site, or a documentation portal, SSG provides a solid foundation for creating high-quality web experiences.

In conclusion, understanding and leveraging Static Site Generation in Next.js can transform how you build and deploy web applications. By combining the power of React with the performance benefits of static rendering, Next.js empowers developers to create modern, scalable, and efficient web applications that meet the demands of today's users.

Now answer the exercise about the content:

What is one of the key benefits of using Static Site Generation (SSG) in Next.js?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Deploying React Apps to Netlify

Next page of the Free Ebook:

83Deploying React Apps to Netlify

6 minutes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text