Next Js getStaticProps

August 15, 2023

When should I use getStaticProps?

In Next.js, getStaticProps is a special function that you can use in a page component to fetch data at build time. This function runs on the server during the build process, not on the client side. It's commonly used for pre-rendering dynamic data onto static pages, which can greatly improve the performance and SEO of your application.

You should use getStaticProps if:

  • The data required to render the page is available at build time ahead of a user’s request

  • The data comes from a headless CMS

  • The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance

  • The data can be publicly cached (not user-specific). This condition can be bypassed in certain specific situation by using a Middleware to rewrite the path.

Example:

export async function getStaticProps() {

const data = await fetchData();

return {

props: {

data,

},

};

}

Back to Blogs