Labs ICT
โญ Pro Login

getStaticProps

getStaticProps

The getStaticProps function is used for static site generation. It runs at build time and fetches data that your page needs. The generated HTML is then cached and served to all users.

Think of it as a recipe that's prepared once and then served to everyone. The cooking happens at build time, and every visitor gets the same delicious meal.

Basic Usage

Here's how to use getStaticProps to fetch data at build time:

// app/blog/page.js
export async function getStaticProps() {
  const posts = await fetch('https://api.example.com/posts');
  const data = await posts.json();
  
  return {
    props: {
      posts: data,
    },
  };
}

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

The data returned from getStaticProps is passed as props to your page component.

Revalidation

You can add a revalidate option to enable Incremental Static Regeneration:

export async function getStaticProps() {
  const posts = await fetch('https://api.example.com/posts');
  const data = await posts.json();
  
  return {
    props: {
      posts: data,
    },
    revalidate: 3600, // Regenerate every hour
  };
}

This combines the performance of static generation with the freshness of dynamic updates. The page is regenerated in the background after the specified time.

Error Handling

You should handle errors gracefully in getStaticProps. If data fetching fails during build time, you can return a 404 or redirect:

export async function getStaticProps() {
  try {
    const posts = await fetch('https://api.example.com/posts');
    const data = await posts.json();
    
    return {
      props: {
        posts: data,
      },
    };
  } catch (error) {
    return {
      notFound: true,
    };
  }
}

This ensures your build doesn't fail if an API is temporarily unavailable.

When to Use getStaticProps

Use getStaticProps when:

The content is public: Static pages are perfect for content everyone should see.

Performance is critical: Static files load incredibly fast from CDNs.

The content doesn't change often: If updates happen hourly or less frequently, SSG is ideal.

You need SEO: Static pages are easily crawlable by search engines.

For content that needs to be personalized or changes very frequently, consider getServerSideProps or client-side fetching instead.

๐Ÿงช Quick Quiz

What is the difference between getStaticProps and getServerSideProps?