'API Routes vs getStaticProps

Sorry to ask but I don't quite understand what the difference is between the two.

With getStaticProps you can get data via fetch and display it on the site and with API routes you do exactly the same or not? You call the API which gets the data and then display it on the screen. I can't really see what the difference is.



Solution 1:[1]

The difference lies in how and when the page is rendered. getStaticProps enables Static Site Generation (SSG). With SSG, the props for the page are gotten at build time when the page is prerendered. This means when you load the page, you're just loading plain HTML and JSON (to hold the props). No need to wait for a server to process it and no need to run Javascript to get the data.

With API routes, the case is a bit different. You may still choose to render your page anyhow. But now, you are also able to write backend code and deploy it with Next.js. You may call the endpoints anywhere; in getServerSideProps (SSR), getStaticProps (SSG) - which is quite redundant, or dynamically in any component or page.

In short, the difference is that getStaticProps enables static site generation while API routes have no direct role in how a page is rendered (it depends on where they are called).

The docs include use cases for both:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FarayolaJ