I’m building a NextJS application (app router) where an API endpoint returns an auth token and a refresh token upon successful login. Further, there are routes that use server components within which an API endpoint is triggered. I’m using axios
to perform network calls and also using axios interceptors that implement refresh token mechanism. Whenever an endpoint returns 401
this interceptor accesses the refresh token from the zustand store, makes a call to a refresh endpoint to get a new auth token, and then re-invokes the original request with the new token. So far so good.
But, as I mentioned earlier, some routes use React Server components within which the API call is made. In this case, the interceptor runs on the server and neither has access to the auth token nor the refresh token. My question is, how can I access the client-side store value on the server?
I don’t want to convert the server component into a client component. In addition, I did try setting these store values as cookies using cookies-next
and in the interceptor, I added a check to see if it is running on the server following which I tried hitting a route-handler that used cookies
from next/headers
/getCookies
from cookies-next
to fetch the set cookies, but it returned undefined
.
I do understand that it is not possible to access the client state on a server component. However, my concern is only to access these tokens without making many changes to the interceptor architecture.
Please nudge me in the right direction.