TanStackT
TanStack2y ago
12 replies
progressive-amaranth

Combining file based routes with code based routing

We're migrating a big and old codebase from react-router@v3 and exploring TanStack Router.

We intend to primarily setup our routes through the recommended file-based routing, but our application has a lot of redirects from older migrations that we need to keep working.

We need to target some wildcard routes, and we've found a way to achieve this in the router.tsx, but it feels a little hacky. Is there a best practice to define code based routing besides file based routing that doesn't involve mutating the auto-generated routeTree?

// app/router.tsx
import { routeTree } from './routeTree.gen'

// Capture existing children from the generated routeTree (file-based)
const fileBasedRoutes = routeTree.children || []

// `addChildren()` mutates and replaces any previousy children
routeTree.addChildren([
  // Since `addChildren()` replaces the children, spread the existing children back in the new array
  ...fileBasedRoutes,

  // Create code-based routes to add to the route tree's children
  ...createWildcardRedirectRoutes('aaa', 'bbb'),
  ...createWildcardRedirectRoutes('create/station', 'create/music'),
])

export const router = createRouter({
  routeTree,
})
Was this page helpful?