12 Feb 2024
Intermediate
In Next.js, getStaticPaths and getStaticProps are two functions used for server-side rendering (SSR) and static site generation (SSG) to pre-render pages.
-
getStaticPaths:
- The
getStaticPathsfunction is used to specify dynamic routes that should be pre-rendered to HTML at build time. - It is typically used with dynamic routes where the number of possible paths is not known in advance, such as pages that depend on data fetched from an external API or a database.
getStaticPathsreturns an object containing two keys:paths: An array of possible values for the dynamic segments in the URL.fallback: A boolean value indicating whether to show a fallback page (404 page) for paths that have not been generated at build time.
- The
-
getStaticProps:
- The
getStaticPropsfunction is used to fetch data at build time and pre-render a page with that data. - It allows you to fetch data from any data source, including APIs, databases, or files.
- The data returned from
getStaticPropsis serialized to JSON before being sent to the component as props. getStaticPropsis a per-page function, meaning that it's exported from a page (or a component) and not from a regular utility file.
- The
Relationship:
getStaticPathsandgetStaticPropsare often used together in Next.js when dealing with dynamic routes.getStaticPathsdetermines the possible values for the dynamic parameters in the URL, whilegetStaticPropsfetches the necessary data for each possible value.getStaticPathsis required when usinggetStaticPropswith dynamic routes. It tells Next.js which paths it needs to pre-render.- The values returned by
getStaticPathsare used to determine which pages Next.js will statically generate at build time. getStaticPropsis then called for each path returned bygetStaticPathsto fetch the necessary data and pre-render the page.
In summary, getStaticPaths sets the paths that Next.js should pre-render, while getStaticProps fetches the data for each path during the pre-rendering process.
next.js
getstaticpaths