Next.js Discord

Discord Forum

How to refresh tokens using SSR - App Router

Unanswered
Scottish Fold posted this in #help-forum
Open in Discord
Scottish FoldOP
When fetching user data in SSR sometimes the access token needs to be refreshed (like when is close to expiring or when the user permission scopes changes)
However in SSR cookies are readonly, we cannot update.

Using middleware is not viable because it would add extra request for each route.

Currently this is the expected flow:
1. App router (SSR) calls externals API
2. External APIs return an error that means the token must be revalidated
3. Revalidate the token (requires update the cookie)
4. Retry step 1

7 Replies

Acacia-ants
I assume you mean that the cookie is being set as HTTP-Only. The server itself does not hold cookies. One of the reasons is that it has to serve multiple clients and it must be stateless and cookies are stateful. What you need to do is read the cookie from the API call and then append it to the result that you return to the client and set is as HTTP-Only again. Each subsequent request from the client will include that cookie when sent to the server. Does that help?
Hello there
in the doc (https://nextjs.org/docs/app/api-reference/functions/cookies) you can set a cookie!

Thats going on if you recreate a cookie with the same name ?
Oh, my bad then
@joulev afaik using middleware is the only viable way
Scottish FoldOP
yeah 😦