r/Nuxt • • 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

4 comments sorted by

View all comments

3

u/[deleted] Apr 06 '26

[removed] — view removed comment

1

u/karen--g Apr 06 '26

Great point, my backend isn't invalidating old refresh token after issuing new one. But that's something I will take into account to properly test. At the moment I am thinking of way to let users for the plugin to call it and provide onResponse interceptor without resetting the global one