0

In the Next.JS documentation I read the following.

Note: You should not use fetch() to call an API route in getStaticProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach.

Fetching from an external API is fine!

But if I'm not supposed to use the internal API then two questions arise.

  • How can I handle POSTS? Should I handle POSTS / PUTS etc through the API but not GETS? That seems odd to me.
  • If I also should not do 'internal POSTS etc' why is the API option there?

edit:

Hmm. I suppose one of the reasons is that when using getStaticProps, and compiling a static version of the site, @ compile time the API is potentially not running. But that could be easily solved by running the API at the same time. (Since GetStaticProps is not really relevant for interactive pages, so POST etc)

edit2:

Someone here also figure that out. Next.js - Error: only absolute urls are supported run export and sever separately and then you can do fetch in static props when needed. Then at least all stuff is in one place.

Matthijn
  • 3,126
  • 9
  • 46
  • 69
  • Why are you doing `POST`/`PUT` requests to your internal API route inside `getStaticProps`? Next.js uses `getStaticProps` to pre-render pages at build time. While API routes exist to handle client-side requests. – juliomalves Jun 06 '21 at 12:07
  • https://stackoverflow.com/questions/62089870/api-call-in-nextjs-getstaticprops-causes-error-500/62091147#62091147 does it help? – Nikolai Kiselev Jun 07 '21 at 05:52
  • I'm not doing POST or PUT in getStaticProps. I understand that. But my point is. Lets say I'm also making a mobile app (native). Then I want my API to not only handle POST and PUT, but also whatever getStaticProps might want to GET. So, in there I want to call the API in those cases too. So instead of `fetchUsers()` I call `fetch('/api/users')` or something. Since I already made that for a mobile app too. – Matthijn Jun 07 '21 at 14:38

1 Answers1

0

The function getStaticProps is meant to generate the data on the server-side when the page is loaded.

Answer 1: You should handle POST/PUT/GET, etc in your API routes.

Answer 2: The main difference between getStaticProps and API is the time they are run. getStaticProps is run when the page is generated on the server. API can be called anytime you need them.

jordiburgos
  • 5,964
  • 4
  • 46
  • 80