TanStackT
TanStack6mo ago
4 replies
dead-brown

Global middleware for JWT token refresh?

Is it possible to catch a 401 error in global middleware, call the refresh token logic, and then retry the original request?

I'm able to catch the error and refresh the token, but I'm not sure how to call the original request again.

My use case is that I use secure cookie storage with h3, so the client has no access to the JWT tokens.

I tried handling this on the client side, but when calling the refresh token logic (a server function), I encountered a "Headers already set" error. (while setting h3 session). To be honest, I'm not sure why this is happening, as I call it during the promise chain.

I'm having a hard time implementing the refresh token logic because I use TanStack Start with Query and useSuspenseQuery. I don't want my ErrorBoundary to catch 401 errors; I just want to intercept them with useQuery or global middleware.

Any hints would be appreciated!
Was this page helpful?