Next.js Discord

Discord Forum

Connecting access token in cookies() to axios client

Unanswered
Ojos Azules posted this in #help-forum
Open in Discord
Ojos AzulesOP
(nextjs v14)
I am struggling to include an access token in my axios requests to an external Express.js API server.

On my mobile frontend I just store the access token in localstorage, and set axiosClient.config.defaults.headers.Authorization = "Bearer accessToken" on login and app startup.

For nextjs, trying to set the axiosClient's default wasn't doing anything. I'm assuming its because of client vs server components.

Next, I tried to store the access token in a cookie. When the user logs in I do cookies().set(). However I'm not sure how I am supposed to grab the accessToken from the cookie and include it in the axios request. The axiosClient is intialized and exported from a root file but it's imported in a client component so I can't grab the cookie in the axios client setup file.

I tried to get the cookie from an api route instead and attach it to the request in the axios request interceptor but I'm getting unexpected results that I really don't understand at all. The API route to grab the access token fails at first, causing my external api request to 401, but then seems to succeed afterward.

My intial guess was that cookies().get() was a promise but that appears to not be the case in nextjs14

Order of events:
1. /tracker page that triggers the external API request to retrieve a list of actions is landed on. It uses React Query so it's a client component. 
2. Page is compiled
3. React query calls the external API with axios.
4. Axios req interceptor calls /api/auth/token to get my access token from the cookie.
5. /api/auth/token is compiled
6. /api/auth/token returns 401 (no access token cookie found)
7. Request to external API returns 401 (Authorization Bearer Header is undefined)
8. GET /tracker returns 500
9. GET /api/auth/token returns 200 (successfully finds the token)


Any idea what's happening and how I should go about restructuring my code to fix it?

0 Replies