Next.js Discord

Discord Forum

Handle refresh token in server request

Answered
British Shorthair posted this in #help-forum
Open in Discord
British ShorthairOP
"How can I manage the handling of refresh tokens in server requests within Next.js version 13 (using the app router)?"
Answered by European sprat
Middleware is also used with route Handlers
View full answer

7 Replies

House Wren
you might need to do it in a middleware
British ShorthairOP
@House Wren But the middleware is invoked when a request is sent for the routes system. for example when a user send a request to the / redirect him to /login but in my case I do some api call in the server and in case the response
detail: 'Given token not valid for any token type',
  code: 'token_not_valid',
  messages: [
    {
      token_class: 'AccessToken',
      token_type: 'access',
      message: 'Token is invalid or expired'
    }
  ]

I want to make api call to the resource /refresh_token to get the new access token and updated it in the cookies
House Wren
I'm not sure I'm understanding correctly, but from what I understand, you can do this in the middleware.

The middleware intercepts requests to your pages, in there you can check whether the access token needs to be refreshed, if it does you call /refresh_token and within the middleware you can set/re-set the cookie.

As far as I understand you cannot do this within a react server component
basically: you want to make sure your token is refreshed, if needs to, by the time it gets to the RSC (the routes system as you call it)
European sprat
Middleware is also used with route Handlers
Answer
House Wren
you can also set cookies from a route handler, though idk if that'll fit your case
British ShorthairOP
you are right @European sprat and @House Wren
I am making post request to end point that handle refresh the token and if the response is ok, i set the new access token.