How to handle auth token refresh for both client/server components after failed API request
Unanswered
Bonga shad posted this in #help-forum
Bonga shadOP
I have a middleware that makes the call to get the auth token, I then save it on request cookie and access it via cookies from next-headers for server components and by getCookie from cookies-next.
I always check if the token is saved in cookies and if its still valid (i.e. not expired) and if it isn't I refetch the token and save the new one - all done in middleware.
The issue I am having is how can I also handle the situation where e.g. user stays on one page for a extended period of time and the token has expired. If they make an api call without page refresh (running middleware) they will get the 403 because of the token.
How can I seamlessly integrate the token refrecht on 403 response that works for both server and client. I get the error when trying to use next-headers in client components so I would need to have 2 separate fetch wrapers - one for server and one for client.
Is there a better way to do that?
I always check if the token is saved in cookies and if its still valid (i.e. not expired) and if it isn't I refetch the token and save the new one - all done in middleware.
The issue I am having is how can I also handle the situation where e.g. user stays on one page for a extended period of time and the token has expired. If they make an api call without page refresh (running middleware) they will get the 403 because of the token.
How can I seamlessly integrate the token refrecht on 403 response that works for both server and client. I get the error when trying to use next-headers in client components so I would need to have 2 separate fetch wrapers - one for server and one for client.
Is there a better way to do that?
7 Replies
middleware canr un for API routes
it depends on how you setup your matchers, the docs shows a default example that excludes API call
but you can include an API
if you mean an API that is not your Next.js app, then your API need to have logic for auth
"I have a middleware that makes the call to get the auth token," I don't really get this part
maybe take a look at this https://github.com/vercel/next.js/discussions/63775
Bonga shadOP
Hi Eric, thanks for the reply. the api I use to get the token is not part of the next.js (i.e. its not an api router) but an 3rd party API that I call to get the token. The current setup I have is that I have separate auth for an acutall user session that I manage via Auth0 plugin ,and I also authenticate api calls by calling a 3rd party api. Currently I only check APi auth tokens via middleware but this wont work If I stay on the same page for a long time and try to make the api call then (once token fetched from middleware has expired).