Cross-Domain Authentication with Next.js: Choosing Between Bearer Tokens and JWT for better-auth
I'm setting up an application with my backend running better-auth hosted on domain A and my frontend on domain B (different domains). I've run into some authentication challenges that I'd like your advice on.
I initially tried using the cookie approach, but quickly learned that cookies across different domains is problematic due to browser security restrictions.
I then moved to bearer token auth, which works for API calls, but I'm having issues with Next.js navigation and middleware. Specifically, when a user navigates between pages, the middleware checks for authentication, but the bearer token isn't automatically included in these navigation requests (only in API calls through my auth client).
I'm now considering JWT as it seems like it might be the best of both worlds - it can work across domains while still functioning through cookies for smoother Next.js navigation. The token would be stored in as a cookie.
Is this the right approach? Would you recommend JWT with better-auth in my cross-domain scenario, or is there a better way I'm missing?
(PS: Eventually I'd like to move to a subdomain-based system, but that's not feasible for me right now due to costs.)
2 Replies
The problem here is not only you have two domains but also two servers. the nextjs server and your backend one. I highly recommend moving to just the nextjs server if possible or at least using it as a proxy for backend calls. This would remove a lot of complexity.
passing a token stored in local storage when the server tries to ssr will cause a lot of headaches, no matter the method you use. you're not in control of the request next is. look into how to proxy calls to your server using the nextjs server.
yup that resolved everything, thanks for putting me on the right track. I just went with normal sessions which is nice as well. Thanks again!