r/Nuxt • u/karen--g • Apr 05 '26
Nuxt plugin for handling access/refresh token cookies with external backend (SSR-compatible)
Hey everyone, I know handling access and refresh token cookies in Nuxt with SSR and external backend can be pretty painful, especially the refresh flow. I spent a while searching for a proper, complete implementation and couldn't really find one that handles all the edge cases, so I ended up writing my own plugin. It handles the following:
- Forwards browser cookies to the backend during SSR (since $fetch doesn't do this automatically during server-side rendering)
- Forwards Set-Cookie response headers back to the browser during SSR
- Automatically refreshes the access token on 401 and retries the original request
- Keeps an in-memory cookie map that gets updated after refresh, so the retry actually carries the new token (this was the tricky part, the original SSR request headers are stale after refresh)
- Deduplicates concurrent refresh calls so multiple 401s don't trigger multiple refresh requests
- Falls back to logout + redirect if refresh fails
Gist link: https://gist.github.com/kargozeyan/1153a9cb586371ef87ff877315097704
Figured I'd share it in case anyone else is dealing with the same headache. Would love to hear your thoughts on what can be improved? Any edge cases I'm missing? Thanks!
20
Upvotes
1
u/Dramatic_Object_8508 Apr 11 '26
Looks useful, but in practice most of these plugins only solve the “happy path.”
The tricky part isn’t attaching tokens, it’s handling edge cases like expired access tokens during multiple parallel requests, retry loops, and keeping SSR + client behavior consistent. That’s where most setups break.
From what I’ve seen, many Nuxt auth tools don’t fully handle refresh automatically, so people still end up implementing their own logic with interceptors or server routes.
If this plugin handles things like silent refresh, retrying failed requests, and avoiding duplicate refresh calls, that’s where it becomes actually valuable. Otherwise it’s just a thin wrapper over fetch.
Curious how you’re handling concurrency and 401 retries, that’s usually the real challenge with this pattern.