Q2: What is getStaticProps and when should you use it?
getStaticProps is an async function that runs exclusively on the server at build time. It fetches data required to pre-render static HTML pages (SSG). Use it for pages with data that doesn't change on every user request, such as marketing pages, blogs, or documentation.
SSG Data Fetching with getStaticProps
// pages/posts.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
};
}
export default function Posts({ posts }) {
return <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
}💡 getStaticProps fetches data at build time and supplies it as props to the page component.
Key Takeaways
- Runs only on the server during
next build. - Passes fetched data as props to the default exported page component.
Knowledge Check
Where does getStaticProps execute when a user visits the site in production?