Course contentsShow
← Web Development
Lesson 1772 of 2,98233. Static Site Generation and JamstackFree lesson

getStaticProps Pattern

Understanding the pattern of fetching data for a page during build time, as seen in frameworks like Next.js.

getStaticProps Pattern

You'll learn how the getStaticProps pattern enables data fetching during the build step of a static site.

What Is getStaticProps?

The getStaticProps pattern is a convention popularized by Next.js where you export a special function from a page component to fetch data at build time rather than request time. Think of it like preparing ingredients before a restaurant opens—everything is ready when customers (users) arrive, rather than scrambling to gather data when each request comes in.

How It Works

When you add a getStaticProps function to a page, your static site generator runs this function during the build process. The function fetches data (from an API, database, or file system), and that data gets baked into the HTML file. When a user visits the page, they receive fully-rendered HTML with the data already embedded—no loading spinners needed.

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

  return {
    props: {
      posts, // passed to the page component as props
    },
  };
}

export default function Blog({ posts }) {
  return (
    <div>
      {posts.map(post => <h2 key={post.id}>{post.title}</h2>)}
    </div>
  );
}

Why This Pattern Matters

This pattern separates when data is fetched from where it's displayed. Your page component receives pre-fetched data as props, keeping the component clean and ensuring blazing-fast page loads. Users get instant content, search engines see complete HTML, and your server doesn't handle repetitive data fetching on every request.

Key Takeaway: The getStaticProps pattern moves data fetching to build time, delivering pre-rendered pages with embedded data for optimal performance and SEO.