Next.js Discord

Discord Forum

external API

Unanswered
Pond loach posted this in #help-forum
Open in Discord
Pond loachOP
What's the best practice in calling external API in NextJS 13? Create a server utility function where its imported into multiple UI components / pages or write a new API route handlers and fetch it in UI components? And why?

I am having difficulties understanding the use of route handlers if utility API functions will also just do the work on fetching data from server.

2 Replies

@Pond loach What's the best practice in calling external API in NextJS 13? Create a server utility function where its imported into multiple UI components / pages or write a new API route handlers and fetch it in UI components? And why? I am having difficulties understanding the use of route handlers if utility API functions will also just do the work on fetching data from server.
As far as I know, from reading the docs and working on my own projects, the API route should only really be used for interacting with external APIs from the client, e.g sending data to an external source from the client, receiving data from an external source from the client. Since these are happening on the client you should assume that these actions are being triggered by user interaction (if they aren't move them to the server), so yes a server utility function being called in multiple UI components is fine and intended. This will change a bit once Server Actions are stable as something like a form submission will no longer require an API route, API routes will soon exclusively be used to act as a way for external sources to interact with your app. e.g Webhooks etc.

Sending data or receiving data based on user action will be able to be done in Server Actions I presume (I can be wrong on this, we're still waiting to hear more about this API)
On top of this as well, the use react hook whenever that is stable will also help in this regard when it comes to client-side data fetching, you will definitely be seeing a lot less API route declaration for simpler apps.