Is there a away to build a dynamic route tree at runtime
I have a situation where my route tree depends on some runtime parameters (determined by backend). I'm trying to see if I can combine the file based routing system with code based routing but at runtime. Has anyone done something like this?
7 Replies
criminal-purpleOP•3w ago
For example, I have a route like
$entity.(policy).settings.tsx
that I'd like to combine with a route like $entity.(repository).settings.tsx
. Their paths are the same, but what they render is based on what $entity is. I know i can just wrap the components with React.lazy
but then the individual settings pages don't get nice isolated beforeLoad
hooks.
I suspect virtual routes may help but would love to see if someone has handled this kind of thing before
Ah, i've found some recent posts about this (once i figured out a term for it - fog of war) and can consider this resolved (at least until we have an api to support it): Related posts: https://discord.com/channels/719702312431386674/1371961528785305632/1371961528785305632
https://discord.com/channels/719702312431386674/1384211408685629510/1384223653155180736optimistic-gold•3w ago
why would you need this kind of flexibility ? is the route tree too big?
criminal-purpleOP•3w ago
Not currently. It's more about code organization. The reason I like the file system organization is it's clear what loads when. This requires some routes to be special and for them to hoist a special component (with beforeLoad, etc, encoded differently). Ideally I could have a single route that could then choose which beforeLoad and component I use based on the incoming request and have it handle code splitting like everything else. This would make it so i can easily define all my repository routes under
(repository)/...
without having to worry about conflicts. Obviously I'd have to do some initial work to mark some routes as potentially conflicting but ideally it would be a one off kind of thing.optimistic-gold•3w ago
and those routes must share the same visible url path?
criminal-purpleOP•3w ago
Ideally yes. I’d rather not change the exposed API (ie routes) based on our router choice
optimistic-gold•3w ago
API as in. ... ?
criminal-purpleOP•3w ago
Sorry, I usually think of our sites routes as a public API, the routes themselves. And we strive to not break backwards compat so we try to prevent changes to them as much as possible. Redirects are sometimes necessary but ideally avoided.
What I'm thinking might be useful is a prop attached to a route called
resolveRouteChildren
. This function can return some virtual Routes (or any routes I guess). From a typegen perspective, it makes things a little muddier since it'll have to union all those possible routes together. I'll need to play with this idea but I think that could provide the best DX for applications that are migrating from react-router and might use a similar pattern.