TanStackT
TanStack3mo ago
37 replies
uncertain-scarlet

How to update router context globally within `beforeLoad`?

I have a layout route "/admin/_authenticated". I want to check context's isAuthenticated property in
beforeLoad
method of this route and update the context in such a way that the updated context is immediately reflected everywhere, as if I'm updating a global variable. Global variable technique works fine, but I think it's not a clean way of doing that.

My use case: Implementing cookie-based auth. Backend is separate (Express). The idea is to check whether session is active on initial load, and if so, to update isAuthenticated key of context, accordingly; otherwise, to redirect to login route. The problem is that the context keeps being stale on
beforeLoad
calls executed when redirecting user among sibling routes.

Another approach would be to use a custom React Context hook, but there is no convenient way to "inject" the hook into the router like it's done in Tanstack Router (example).

Thank you for building such a great toolchain.
Was this page helpful?