T
TanStack7mo ago
rival-black

Best way to avoid route duplication for optional parent segment (file-based routing)

I'm using file-based routing and need to support an optional parent segment in my URLs. Current routes:
/event123/overview/
/event123/schedule/detail/
/event123/overview/
/event123/schedule/detail/
New requirement (without duplicating routes):
/orgA/event123/overview/
/orgA/event123/schedule/detail/
/orgA/event123/overview/
/orgA/event123/schedule/detail/
Since optional path params aren't supported, what’s the best way to reuse routes without duplicating all child configs (loader, beforeLoad, etc.)? Any recommended patterns for this? Thanks! 🙏
5 Replies
quickest-silver
quickest-silver7mo ago
Move code that doesn't change if the parent param isn't present into it's own layout component(s). The code that's common to all loaders and before load, you can move into there own reuseable functions as well (you'll end up having to write a bit more type annotations as well). You could look into https://tanstack.com/router/latest/docs/framework/react/routing/virtual-file-routes as well, I'm not too sure how well it would work for you.
Virtual File Routes | TanStack Router React Docs
We'd like to thank the Remix team for . We've taken inspiration from their work and adapted it to work with TanStack Router's existing file-based route-tree generation. Virtual file routes are a power...
rival-black
rival-blackOP7mo ago
Thanks for the tips! I tried the virtual routing approach but couldn't get it to work - maybe I'm doing it wrong!? 🤔 I set up a simple StackBlitz example (https://stackblitz.com/edit/tanstack-router-pbshsqaa), but it throws this error:
Uncaught Error: Invariant failed: Duplicate routes found with id: /$org/$event/
Uncaught Error: Invariant failed: Duplicate routes found with id: /$org/$event/
Any thoughts on what I might be missing?
national-gold
national-gold7mo ago
virtual route won't help here
rival-black
rival-blackOP7mo ago
@Manuel Schiller thanks for the clarification! If virtual routes won't help in this case, what approach would you recommend?
national-gold
national-gold7mo ago
you need separate route files until we support optiona path params

Did you find this page helpful?