Back to Blog

I Thought Refresh Token Was Easy (Until Next.js 15 Happened)

Royan Gagas
June 2, 2025
Share
react
nextjs
I Thought Refresh Token Was Easy (Until Next.js 15 Happened)

At first, I wanted to implement refresh token flow in my website. But then I got stuck with how cookies work in Nextjs 15. I was using cookies to store my JWT for API authorization.



The Problem

When the access token expires, I fetch the refresh token to get a new one. The request is successful, but... I can't update the accessToken cookie from the client. Why? Because the cookie only exists on the server😐

For context:

I used custom fetch function (I used to use Axios before). When I tried to implement refresh token logic inside in an Axios interceptor, it caused waterfall looping. Axios kept hitting the refresh token endpoint over and over again because the cookie never got updated, and the new token never got set.



You can see in the image what flow I want implement to refresh the token. I know you can use Server Action or Route Handler but it is not worth the cookie still send the message "Cookie only in the server"

Yes, I know I could use Server Actions or Route Handlers, but it's still not working because... yeah "cookie only available on the server" error keeps showing up.



My Attempt

I tried two approaches:

1. A route handler at /api/auth/config
2. A server action called logoutAction()

/api/auth/config

this server action I use

I didn't use both at the same time, just one or the other.

But the issue is I think the problem is when fetch in the response error. Next JS recognizing that fetch is not in the server again but it have on the browser client. so i can't access cookie in the server.



Solution

Because of all that mess, I decided no refresh token for now. Instead, I just use one token (access token), and to handle problem when token expired with status 401. I redirect to invalid-token route which is fake route.

Then in my middleware, I listen to that fake route and clear the cookie there. and yeaaah that work for me. yuhuuu finally

this for the middleware

Credit for this solution

here



If you know a proper way to implement refresh token with cookies in Nextjs 15, feel free to comment on my social media, DM, or emal me. Would love to hear your thoughts!✨✨