T
TanStack5mo ago
deep-jade

Is there a smart way to cache the secure cookie session client-side?

I setup a DYI Auth using an existing API. I fetch the session from the cookies on the root's beforeLoad context and that works fine. It handles login & logout correctly and easily. You can preview how I did it here: https://codesandbox.io/p/devbox/distracted-cohen-h89lrq Now, I noticed that this introduced a lot of HTTP requests. Everytime a route is preloaded or loaded, a request to the fetchSession's serverFn is made to get a fresh session. While this ensures that the session is always fresh, it feels like too much for my case. I receive an expiration time with my token, so I'd like to be able to handle the expiration myself or at least give it some slack because the API will throw 401 in case the token is expired anyway, so I don't really need a session that fresh. I started to refactor to leverage the queryClient for storing the session state but I'm hitting a few issues with this implementation. It does the job, but after login & logout the state is not updated & the user is stuck on the "old" screen as if nothing happened. I wonder if it's related to the redirections that are thrown in the serverFn, maybe I should refactor further and handle the redirection in the client? Here's a refactored version using clientQuery: https://codesandbox.io/p/devbox/fervent-frog-w4pkm2 FYI: you need to open the preview in a new tab, because secure sessions/cookies are not supported by Code Sandbox
4 Replies
provincial-silver
provincial-silver5mo ago
the second link is not using react-query, maybe forgot to publish a newer version? By the way, if you have session inside react-query after logout you need to invalidate the query key for it
deep-jade
deep-jadeOP5mo ago
Ah my bad, here's the correct link that uses react-query: https://codesandbox.io/p/devbox/fervent-frog-w4pkm2 invalidating the queries (like all the user-specific data) is fine as it can happen after the redirection, that works. The specific part which doesn't work is invalidating/forcing the session query to clear/refetch/invalidate before the redirection in both the login & logout actions.
national-gold
national-gold5mo ago
Hi there Have you tried removing the query that caches the user data(not invalidate).... something like queryClient.removeQueryData(queryKey) ? I think i faced something like this in my own side project. I simply wrapped the redirect logic in a setTimeout .
deep-jade
deep-jadeOP5mo ago
The redirect is thrown by the server function, so I'm not sure it can be delayed like that, unless I move the redirection management in the client which I'd like to avoid.

Did you find this page helpful?