Next.js Discord

Discord Forum

which is better: route handlers or server components for interacting and authenticate external api?

Unanswered
Bluethroat posted this in #help-forum
Open in Discord
BluethroatOP
I'm building my first Next.js v14.1 app and I have to authenticate (vía JWT) and interact with an external rest API. I saw some people uses fetch directly in the server components and other create route handlers for interacting with the external api and then fetch those endpoints in the components... which should I use?

6 Replies

you only need to create a route handler if you need to call it from the browser, otherwise you should try to make the requests directly in the component otherwise you are adding an unnecessary layer of indirection between the component and the fetch code
BluethroatOP
Hi, @Rafael Almeida , thanks. By "call it from the browser" I guess you mean from a client component, right? I really wanted to keep the logic that connects to the external api organized... which would be an advisable pattern on this?
I created different functions in a separate apicalls.ts file, but as they are not in a server component I have to add NEXTPUBLIC to the env variables, which I tried to avoid
@Bluethroat Hi, <@258390283127881728> , thanks. By "call it from the browser" I guess you mean from a client component, right? I really wanted to keep the logic that connects to the external api organized... which would be an advisable pattern on this?
yeah a client component or an external client, you can have the functions organized in a different file but I am not sure why you need to add NEXT_PUBLIC_, you are right you should avoid it
Yellowfin tuna
Hi @Bluethroat How did you end up with the configuration of the project?

I am in a similar situation. I have to use an external API, and pass authorization headers.

I find calling the external API directly from server components is the best approach, but I am not being able to cache the fetches result in production.

It does cache the fetch results in dev mode though.

I know calling cookies() or headers() opt out of cahcing, so i pass the "force-cache" option to the fetch call.
BluethroatOP
Hi @Yellowfin tuna ! sorry for the delay in my response. I couldn't tell. I'm still in development... unfortunately. I guess I'll take a look at what you said to see what happens in my case