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!4 Replies
unwilling-turquoise•5w ago
I'm curious to see an example of how you implemented secure cookie storage with H3, so that the client has no access to the JWT tokens.
I have a backend API for login that returns a JWT token, and I need to reuse that token to authenticate other API calls. However, I believe I need to wrap all my API calls in server functions to achieve this, since loader and beforeLoad are isomorphic. Is that correct, or is there another way to handle it?
conscious-sapphireOP•5w ago
I just use h3 cookie. I have serverFunctions that call real API. Before calling real api I get
accessToken
from session 😄unwilling-turquoise•5w ago
this is what i am using


conscious-sapphireOP•5w ago
Yup, looks the same