Do beforeLoad logic on all children routes of parent.
Take tree for example
Is it possible to have something on the root route
/users/$userId and apply some beforeLoad logic on all of its children? Or do you have to do it for each route?15 Replies
mute-gold•16mo ago
seems possible, what do you want to do exactly?
foreign-sapphireOP•16mo ago
Basically I just need to set a cookie when userId changes
And doing it beforeLoad, settin the cookie if it doesnt exist, at the route level seems best
mute-gold•16mo ago
Authenticated Routes | TanStack Router React Docs
Authentication is an extremely common requirement for web applications. In this guide, we'll walk through how to use TanStack Router to build protected routes, and how to redirect users to login if they try to access them.
The route.beforeLoad Option
mute-gold•16mo ago
it does not set a cookie but handles auth logic in a parent
beforeLoadforeign-sapphireOP•16mo ago
Yeah, reading that right now. My first intention is to create a middleware layout route with no path, just ID, but I won't have the needed param types
mute-gold•16mo ago
a layout route cannot have a path param
or maybe I am misunderstanding what you want to do
foreign-sapphireOP•16mo ago
If we take
/users/$userId as the parent, I want the beforeLoad on this to trigger when navigating to any of its children, so foo and foo/barmute-gold•16mo ago
yes this will work
foreign-sapphireOP•16mo ago
So would it be something like this?
or would the parentRoute need to be
appRoute for all of them, and you'd just add these into the userRoute children arraymute-gold•16mo ago
looks fine like it is
foreign-sapphireOP•16mo ago
Hmm, routing is broken now. URL changes, but components dont. I gotta read more how this works lol
mute-gold•16mo ago
your
<User> component needs to render an <Outlet>
btw, I would use file based routingforeign-sapphireOP•16mo ago
Ya, started to read into it, seems more intuitive
I feel like I'm running into the same issue here.
I feel like if i put a layout component inside of
$userId, then it should apply the beforeLoad to all routes that have $userid
Else I have to do my beforeLoad logic on every single route that has $userIdmute-gold•16mo ago
sure it's the same thing with file based routing
it's just more convenient
did it work as expected?
foreign-sapphireOP•16mo ago
Ya just wrapped all project routes in a layout, and using a non-strict useParams hook to do my needed logic