Next.js Discord

Discord Forum

NextJS 15 : axios interceptor for getting 'accessToken'

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
I’m working with a Node.js backend and a Next.js 15 frontend. My backend APIs for login and signup return both an access token and a refresh token, which I use for authenticated API requests. When the access token expires during an API call, I need to obtain a new access token using the refresh token and then retry the original request, also ensuring that cookies or tokens are saved appropriately in the store.

For a Next.js 15 application, what are the recommended best practices for maintaining user sessions? Specifically, should I rely on an Axios interceptor to automatically check if the access token has expired, handle refreshing, and re-issue requests? Or is there a more robust pattern commonly used in modern Next.js applications?"
currently i am trying to save the 'new access token ' in axios interceptor by calling server action inside axios interceptor , but getting error that ' you can update the cookies in server action and route handler only'

1 Reply

Pacific sand lance
i can suggest rotating tokens in middleware (server-side only, 'pre request') and later in axios 'post request' interceptor (client side only). also, as of you can't update cookies from within react server components (i guess that's why you are getting this error)