Blog>
Snippets

Incremental Static Regeneration

Demonstrate Incremental Static Regeneration using getStaticProps and revalidate. Show fetching data at build time and updating it periodically.
export async function getStaticProps(context) {
  // Fetch data from an API at build time
  const res = await fetch('https://myapi.com/data');
  const data = await res.json();

  return {
    props: { data }, // Pass data to the page via props
    revalidate: 10, // Regenerate the page every 10 seconds
  };
}
This piece of code is meant to be used inside a Next.js page. It uses getStaticProps to fetch data at build time from an API. It passes the fetched data to the page's props. The revalidate property set to 10 seconds allows the page to be regenerated (or updated with new data) every 10 seconds, enabling Incremental Static Regeneration. This feature allows pages to be updated periodically without the need for a full rebuild.
<html>
<head>
  <title>Incremental Static Regeneration Example</title>
</head>
<body>
  <div id="data-container"></div>
  <script>
    // Assume 'data' is the prop passed from getStaticProps
    function displayData(data) {
      const container = document.getElementById('data-container');
      container.textContent = JSON.stringify(data);
    }

    // Fetching initial data at build time via props would be handled by Next.js
    // displayData(props.data);
  </script>
</body>
</html>
This HTML structure includes a simple script tag where you would define a function to handle the display of the data on the page. Notably, in a real-world Next.js application, the prop 'data' passed from getStaticProps would be handled by the framework, and the display function would be part of the component's logic.
body {
  background-color: #f0f0f0;
  font-family: Arial, sans-serif;
}

#data-container {
  margin: 20px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  border: 1px solid #dcdcdc;
}
This CSS provides basic styling for the body and a div container designed to display the data on the page. It sets the background color, font, and styles for a simple container with some margin, padding, border, and rounded corners.