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
other-emerald•13mo ago
seems possible, what do you want to do exactly?
multiple-amethystOP•13mo 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
other-emerald•13mo 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
other-emerald•13mo ago
it does not set a cookie but handles auth logic in a parent
beforeLoad
multiple-amethystOP•13mo 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
other-emerald•13mo ago
a layout route cannot have a path param
or maybe I am misunderstanding what you want to do
multiple-amethystOP•13mo 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/barother-emerald•13mo ago
yes this will work
multiple-amethystOP•13mo 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 arrayother-emerald•13mo ago
looks fine like it is
multiple-amethystOP•13mo ago
Hmm, routing is broken now. URL changes, but components dont. I gotta read more how this works lol
other-emerald•13mo ago
your
<User>
component needs to render an <Outlet>
btw, I would use file based routingmultiple-amethystOP•13mo 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 $userId
other-emerald•13mo ago
sure it's the same thing with file based routing
it's just more convenient
did it work as expected?
multiple-amethystOP•13mo ago
Ya just wrapped all project routes in a layout, and using a non-strict useParams hook to do my needed logic