Next.js Discord

Discord Forum

Next.JS API Routes functionality behind the curtains

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
Hello there!
I have a question.

I am using an axios client within a Next.JS API Route:
const apiClient = axios.create({baseUrl: '...'})

Within the API route, I am setting a bearer token as default:
apiClient.defaults.headers.common['Authorization'] = Bearer ${accessToken}

After that, some async work happens, and then a request to the axios client is made.

Is each memory instance of Next.JS API routes completely separate when deployed to Vercel? Are they serverless lambda functions behind the curtains?
In other words, is it impossible that by settings apiClient.defaults.headers in one call of the API route, it would override the default headers in another?

8 Replies

it is possible I think
Vercel will by default bundle pages and bundle API routes into a single app
it can then split them intelligently but I couldn't get more details about the heuristics behind it
so I tend to consider that the API routes may run on different machines, process, or not
all the more that if you change your host you'd want your app to work the same
I don't see the point of axios in an API route to be frank
client-side routers are often used for their caching capabilities, so it may make sense if you extract Axios cache afterwards to feed a client context (if you use graphql this may make sense to use Dataloader this way for instance)
American black bearOP
Thanks Eric,
That helps alot. I assume so too, because this is also the behaviour I am experiencing in my applications..
The axios call is necessary because of complexities involved in a specialized authentication system which needs to run in a server-only environment, but this is another issue altogether 😉