Next.js Discord

Discord Forum

Seamlessly refreshing an access token/cookie while using streaming

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
This is my middleware:
1. pull cookie from request
2. check if the access token is valid
3. check if the refresh token is valid
4. use the refresh token to generate new tokens
5. set the cookie on the response with the new access and refresh tokens
6. return the mutated response

I'm aware that you cannot modify cookies once streaming has begun, but I expect middleware to execute before the page executes. My current approach results in this scenario:

1. user with an expired access token visits the site
2. middleware executes, refreshes the token and sets the updated cookie
3. page pulls the token from the cookie
4. page passes the token into an HTTP request to authenticate with an external service
5. external service returns an unexpected 401 due to an expired token
6. server component errors and shows an error boundary
7. user refreshes the page
8. page works as expected, as the token has been refreshed

The whole point of a middleware is that it executes before pages and modifies the request/response before it hits the page, so why does it just pass the old cookie through?
I can't do the token refreshing as part of step 3 or 4 because you cannot set cookies in server components. If I just pass the new token through to the external service request without setting the cookie, then it may result in the expired token being refreshed X number of times depending on how many suspense-enabled streamed components use it. If I set a renderless component in the layout to execute a server action to trigger a refresh, that doesn't seem like it would work as the whole point of streaming is that all the suspense-enabled components execute in parallel...

5 Replies

Golden-cheeked Warbler
@Asian black bear did you manage to solve this?
Asian black bearOP
unfortunately no
this is working locally for me in a little repro repo. i can't test it in prod against my actual app as i'm interfacing with an api i don't control token expiries of but it looks like it should work
absolutely insane that this issue is almost a year old with no fix