0
0
NextjsConceptBeginner · 3 min read

What is getStaticProps in Next.js: Explanation and Example

getStaticProps is a special function in Next.js that runs at build time to fetch data and pass it as props to a page component. It enables static site generation by pre-rendering pages with data before the user visits them.
⚙️

How It Works

Imagine you are preparing a photo album before a party. You gather all the pictures and arrange them nicely in advance so when guests arrive, the album is ready to show immediately. getStaticProps works similarly by fetching data and preparing the page content during the build process, not when a user visits the page.

This means the page is generated once with the data and saved as a static file. When someone visits the page, Next.js serves this pre-built page instantly, making it very fast and efficient. This approach is great for content that does not change often.

💻

Example

This example shows a Next.js page that uses getStaticProps to fetch a list of posts at build time and display them.

javascript
export async function getStaticProps() {
  // Simulate fetching data from an API or database
  const posts = [
    { id: 1, title: 'Hello World' },
    { id: 2, title: 'Next.js is awesome' }
  ];

  return {
    props: {
      posts
    }
  };
}

export default function PostsPage({ posts }) {
  return (
    <main>
      <h1>Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </main>
  );
}
Output
<h1>Posts</h1><ul><li>Hello World</li><li>Next.js is awesome</li></ul>
🎯

When to Use

Use getStaticProps when your page content can be prepared ahead of time and does not need to change on every request. This is perfect for blogs, marketing pages, documentation, or product listings that update infrequently.

It improves performance by serving static files and reduces server load. However, if your data changes often or depends on user input, consider other methods like server-side rendering or client-side fetching.

Key Points

  • Runs at build time: Fetches data once when building the site.
  • Static generation: Creates fast, static pages served to users.
  • Props passing: Passes fetched data as props to the page component.
  • Best for: Content that changes rarely or on a schedule.
  • Not for: Real-time or user-specific data.

Key Takeaways

getStaticProps fetches data at build time to generate static pages.
It improves page load speed by serving pre-built content.
Ideal for pages with data that changes infrequently.
Passes data as props to the page component for rendering.
Not suitable for dynamic or user-specific data that changes on every request.