Next.js Discord

Discord Forum

Help Needed with Axios Interceptor and Next-Auth in Next.js 14

Unanswered
Philippine Crocodile posted this in #help-forum
Open in Discord
Philippine CrocodileOP
Hey everyone! I'm currently facing a challenge in my Next.js 14 application where I'm using next-auth@5 for authentication and Axios for API requests. I've set up an Axios interceptor to handle 401 Unauthorized responses from my external REST API. The goal is to sign out the user automatically when a 401 response is detected. However, I'm running into an issue with cookie modifications.

Here's the interceptor code I'm using:

The problem arises when the interceptor tries to sign out the user on a 401 response. I'm getting the error: "Cookies can only be modified in a Server Action or Route Handler." It seems like the signOut() call from next-auth is not allowed to modify cookies directly from the client side.

I'm looking for advice or suggestions on how to handle this properly in a Next.js context. Ideally, I want to keep the interceptor logic but manage the sign-out process in a way that aligns with Next.js's constraints regarding cookie modifications.

Has anyone dealt with a similar issue or have insights on how to approach this? Any guidance or examples would be greatly appreciated!

Thanks in advance! 🙏

3 Replies

you can't modify cookies in any page file, so you need to use a middleware or route hander (or client) to do remove it... page is server by default
@riský you can't modify cookies in any page file, so you need to use a middleware or route hander (or client) to do remove it... page is server by default
Philippine CrocodileOP
Thank you so much for the clarification! Your explanation about the limitations of modifying cookies in page files and the suggestion to use either middleware or an API route handler in Next.js makes perfect sense. It's clear now why my approach was encountering issues and how I should proceed to handle authentication more effectively and securely.

Could you possibly share any links or resources that explain the implementation of middleware in Next.js, especially in the context of authentication and cookie manipulation? I'm looking to deepen my understanding and ensure that I implement this in the best way possible.

Thanks again for your invaluable help! 🙏
hmm i can't think of many resources of top of my head (docs should have some things)...