Next.js Discord

Discord Forum

What is a good pattern for fetching data from server when using access/refresh tokens? (app router)

Unanswered
American Sable posted this in #help-forum
Open in Discord
American SableOP
I am struggling to figure out how to best fetch data from server components. Nextjs seems to strongly recommend this but Idk how when JWTs are involved. Here is my setup:
1. My auth server returns an access token (AT) in the HTTP response body, and a refresh token (RT) in an HTTP only cookie.
2. Rather then calling the auth server (or my backend API) directly from the client, I am using route handlers as a backend-for-frontend (BFF) which will proxy the client's fetch call to the auth server.
3. When the BFF receives the AT/RT, it places both in HTTP cookies on the browser. I am doing this so that I can access the AT from server components, because if the client received the AT, directly I would need to store that in memory (react context), and thus would be unable to make requests server side, which is what I ultimately want to do.
4. The AT cookie has a path set to / so that the browser will send the AT on every request so that the server can fetch data with it. The RT cookie has a path of /bff/auth/refresh so it will only be sent when refreshing.
5. When server component needs to fetch data from the API, it retrieves the AT from the client's cookies, and then makes the request. So far, everything works great up to here.
The problem comes when the AT expires. When the server attempts a request to the API and receives a 401, I want to automatically refresh the tokens and resubmit the request. Problem is, the browser only sends the RT to /bff/auth/refresh. The client would need to be redirected to that url, which will trigger a refresh (tried that, it works). But from there, I can't dynamically redirect back to the previous url because server components don't have access to the current url. So this is preventing me from doing any data fetching from the server. What I am currently doing is always fetching from client side, which is basically what I would normally do in a Create React App. But I'd like to take advantage of server components. Any ideas?

0 Replies