Blog>
Snippets

Static Generation with getStaticProps

Use getStaticProps to demonstrate how to perform static generation in Next.js, fetching data at build time for a Next.js page.
export async function getStaticProps() {
  // Fetch data from external API or any other source
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}
This is a getStaticProps function that fetches data from an external API at build time and passes the fetched data into a Next.js page as props.
import Head from 'next/head'
import styles from '../styles/Home.module.css'

export default function Home({ data }) {
  return (
    <div className={styles.container}>
      <Head>
        <title>Static Generation Example</title>
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Static Generation with getStaticProps
        </h1>

        <ul>
          {data.map(item => (
            <li key={item.id}>{item.title}</li>
          ))}
        </ul>
      </main>
    </div>
  )
}
This is a React component for a Next.js page named Home. It uses the data fetched by getStaticProps to render a list of items.
.container {
  padding: 0 2rem;
}

.main {
  min-height: 100vh;
  padding: 4rem 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.title {
  margin: 0;
  line-height: 1.15;
  font-size: 4rem;
}

ul {
  list-style: none;
}

li {
  margin: 1rem 0;
}
CSS styles for the Home component layout and elements, like the container, main content area, title, and list of items.