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.
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> ); }
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.