Capítulo 44 de 57

Chapter 44: Creating a Router

Core Idea

The createRouter function instantiates the core Router object, which needs a routeTree, and its type must be registered via TypeScript declaration merging (Register interface) to enable full type safety across the application.

Key Concepts

  • createRouter: The function that creates a Router instance, the "brains" of TanStack Router responsible for route matching, navigation, and router-wide configuration.
  • routeTree: Required option passed to createRouter, produced either by file-based routing (imported from the generated src/routeTree.gen.ts) or code-based routing (built manually via rootRoute.addChildren([...])).
  • Declaration merging registration: Extending the Register interface from @tanstack/react-router with a router: typeof router property so the entire project gets type-safe hooks, components, and imports.
  • notFoundComponent: Passed to createRootRoute to render a fallback (e.g. a 404 page) when no route matches.
  • Router-wide options: Many additional settings can be passed to createRouter beyond routeTree, documented in the RouterOptions API reference.

Code Examples

import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'

const router = createRouter({
  routeTree,
})

declare module '@tanstack/react-router' {
  interface Register {
    // This infers the type of our router and registers it across your entire project
    router: typeof router
  }
}
  • What it demonstrates: The minimal setup to create and globally register a router instance for full type safety.
export const Route = createRootRoute({
  component: () => (
    // ...
  ),
  notFoundComponent: () => <div>404 Not Found</div>,
})
  • What it demonstrates: Configuring a router-wide 404 fallback on the root route.

Key Takeaways

  1. Always register the router type via declaration merging immediately after creating it, this section is explicitly flagged as critical in the docs (not optional).
  2. The route tree can come from file-based routing (auto-generated) or code-based routing (manually assembled with addChildren).
  3. A notFoundComponent on the root route handles unmatched paths; skipping this step leaves navigation without a fallback UI.

Connects To

  • Ch 57: File-Based Routing API Reference, covers how routeTree.gen.ts is generated and configured.
  • Ch 47: Type Safety, expands on why router registration unlocks type-safe hooks/components.
  • Ch 50: Not Found Errors, the deeper mechanics behind notFoundComponent.