Why does calling external API need to be proxied through Nextjs API route?

I’m migrating an existing React app that uses auth0 react SDK to NextJs.

In the original app, the frontend makes a direct api call to the backend by passing access token in the authorization header that it obtained from the react auth0 sdk (using getTokenSilently api)

I came across this article, which seems to imply that with NextJS SDK calling external api would require proxying the api call through nextjs’s API route. That is [frontend] → nextjs api route → actual backend api gateway. This is because the frontend no longer has access to the access_token, so the request is sent to the nextjs’s api route. Where it uses the session to look up the access token and then make another api call to the api gateway by passing the access token.

Is my understanding correct?

I’m concerned with this extra hop introduced by the proxy (latency/performance rason) but I also feel like I would need to write nextjs’s api route corresponding to every single route on the backend that is authenticated (I have about 70-80 apis endpoints).

7 Likes

I also have this question but haven’t found any documentation. I experimented with the encrypted cookie “appSession” set by Auth0. If your external API is on the same domain (or a subdomain), technically you can read this cookie and get the access token from there. To do this:

  1. Call external API directly from the browser.
  2. Decrypt the cookie on the server. Encryption key is AUTH0_SECRET variable in Next.JS. The cookie contains user data, session token and id token.

Interested to see an example on how the whole flow would look like. Proxying requests through the Next.JS server feels like unnecessarily complicating things.

1 Like

Hello, any news on this subject ?

Looking for an answer to this as well, I also find it weird that I need to route everything through the api.

My solution for now is calling the access token in get server side props, and calling my api on the client side of nextjs, not sure of this, I’ve read some solution with middlewares but it adds some latency to each api call

For what it’s worth, we have a workaround by passing the accessToken to the frontend.
I have a brief example code here: Next.js & External API without Proxying requests through Next.js backend

I’m just looking for some kind of official confirmation that this is safe to do.

1 Like

Thanks for sharing @felix3 !

Sharing this issue against nextjs-auth0 that goes into a bit more detail on this for future reference:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.