From 762f9496061f8fd274ffc5d0da47c9c42bb4b83b Mon Sep 17 00:00:00 2001
From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com>
Date: Sun, 1 Nov 2026 23:38:51 +0100
Subject: [PATCH 01/44] feat: experimental route modules for file-based routing
Route modules are workspace packages that own a subtree of file-based routes and are mounted into applications or other modules. A package declares `tanstack.router.module` in its package.json. The generator gives it qualified route ids (`:`), a generated route scope (`routeScope.gen.ts` plus one namespace file per included or used module), a public contract (`routeContract.gen.ts`, exported as `./route-types` after the package's own declaration build), a runtime entry (`routeModule.gen.ts`, exported as `./route-module`) and a topology manifest (`.tanstack/route-module.json`). Includers mount modules with the `routeModules` option: `includes` chooses the host route and mount path, optionally under path params, `uses` references modules mounted elsewhere, and an application installs a module several times by including it once per installation named with `as`, each with its own namespace and route ids (`#:`). Matches of module routes carry `localRouteId`, and the generated `isScopedMatch` guard narrows whole-router matches by module id prefix.
Runtime: the generated host tree mounts module roots with the internal `mountRouteModule`; module-local ids, destinations, redirects and not-found errors resolve to the installation of the route that uses them; `HostedRouter` types the links of code that mounts modules under path params. Type composition is contract-based through `./route-types`; the framework packages augment `@tanstack/router-core/extensions` and export `RouteCore`.
Start: modules get `createServerFn`, `createMiddleware` and `createStartModule` in their scope, declare required context by augmenting `StartModuleRequirements`, and contribute fragments that applications install with `createStart(() => ({ extends: startModules }))`; `startModules.gen.ts` type-checks installation and requirements. The Start plugin lists module routes in the routes manifest, selects the providers' client tree views, discovers prerenderable module pages and extends import protection to module packages.
Build and tooling: the host bundler compiles, code-splits and hot-updates module routes, including every installation; `tsr generate` and `tsr watch` are the only commands and packages own their declaration builds; the devtools show modules; the `route-module-imports` ESLint rule enforces scope imports. Fixtures cover React, Solid, Vue and Start with Vite and Rsbuild, and a large example measures builds.
---
.changeset/clever-buttons-push.md | 12 +
.changeset/itchy-chairs-melt.md | 5 +
.changeset/route-modules-devtools.md | 5 +
.changeset/route-modules-eslint.md | 5 +
.changeset/route-modules-generator.md | 7 +
.changeset/route-modules-router.md | 8 +
.changeset/route-modules-start.md | 9 +
.changeset/router-core-extensions.md | 10 +
.changeset/salty-dryers-move.md | 5 +
.changeset/start-modules-many-fragments.md | 5 +
.../start-rsbuild-compiler-esm-resolve.md | 5 +
.changeset/true-houses-behave.md | 16 +
.../client-nav/link-performance/cases.ts | 9 +
.../link-performance/src/workload.tsx | 10 +
docs/router/config.json | 8 +
docs/router/eslint/eslint-plugin-router.md | 1 +
docs/router/eslint/route-module-imports.md | 47 +
docs/router/routing/route-modules.md | 445 ++++
docs/start/config.json | 4 +
.../framework/react/guide/route-modules.md | 196 ++
e2e/react-router/route-modules/.gitignore | 8 +
.../route-modules/e2e-dev/devtools.spec.ts | 46 +
.../route-modules/e2e-dev/hmr.spec.ts | 109 +
.../route-modules/e2e/app.spec.ts | 126 ++
.../route-modules/e2e/scope-parity.spec.ts | 215 ++
e2e/react-router/route-modules/package.json | 24 +
.../packages/account/package.json | 43 +
.../packages/account/src/routes/__root.tsx | 25 +
.../packages/account/src/routes/index.tsx | 35 +
.../account/src/routes/orders.$orderId.tsx | 44 +
.../packages/account/tsconfig.json | 15 +
.../account/tsconfig.route-types.json | 13 +
.../packages/billing/package.json | 41 +
.../packages/billing/src/routes/__root.tsx | 23 +
.../packages/billing/src/routes/index.tsx | 29 +
.../packages/billing/tsconfig.json | 15 +
.../billing/tsconfig.route-types.json | 13 +
.../packages/products/package.json | 43 +
.../packages/products/src/api.ts | 12 +
.../products/src/routes/$productId.tsx | 49 +
.../packages/products/src/routes/__root.tsx | 24 +
.../packages/products/src/routes/_layout.tsx | 10 +
.../products/src/routes/_layout/deals.tsx | 12 +
.../src/routes/catalog.{-$category}.tsx | 12 +
.../packages/products/src/routes/compare.tsx | 17 +
.../packages/products/src/routes/files.$.tsx | 10 +
.../packages/products/src/routes/index.tsx | 22 +
.../packages/products/src/routes/legacy.tsx | 10 +
.../packages/products/src/schemas.ts | 6 +
.../packages/products/tsconfig.json | 15 +
.../products/tsconfig.route-types.json | 13 +
.../packages/settings/package.json | 38 +
.../packages/settings/src/routes/__root.tsx | 44 +
.../packages/settings/src/routes/forward.tsx | 5 +
.../packages/settings/src/routes/index.tsx | 16 +
.../packages/settings/src/routes/legacy.tsx | 6 +
.../packages/settings/src/routes/members.tsx | 12 +
.../packages/settings/src/routes/missing.tsx | 6 +
.../packages/settings/src/routes/profile.tsx | 81 +
.../packages/settings/src/routes/search.tsx | 4 +
.../packages/settings/tsconfig.json | 15 +
.../settings/tsconfig.route-types.json | 13 +
.../packages/storefront/package.json | 42 +
.../packages/storefront/src/routes/__root.tsx | 26 +
.../packages/storefront/src/routes/cart.tsx | 30 +
.../packages/storefront/src/routes/index.tsx | 30 +
.../packages/storefront/tsconfig.json | 15 +
.../storefront/tsconfig.route-types.json | 13 +
.../route-modules/packages/team/package.json | 38 +
.../packages/team/src/routes/__root.tsx | 27 +
.../packages/team/src/routes/index.tsx | 25 +
.../team/src/routes/members.$memberId.tsx | 28 +
.../route-modules/packages/team/tsconfig.json | 15 +
.../packages/team/tsconfig.route-types.json | 13 +
.../route-modules/packages/web/index.html | 11 +
.../route-modules/packages/web/package.json | 33 +
.../route-modules/packages/web/src/main.tsx | 28 +
.../packages/web/src/profile-links.tsx | 18 +
.../route-modules/packages/web/src/router.tsx | 20 +
.../packages/web/src/routes/__root.tsx | 94 +
.../web/src/routes/_authenticated.tsx | 6 +
.../packages/web/src/routes/index.tsx | 122 ++
.../packages/web/src/routes/orgs.$orgId.tsx | 15 +
.../web/src/routes/people.$personId.tsx | 13 +
.../route-modules/packages/web/src/styles.css | 450 ++++
.../web/tests/match-identity.test.tsx | 139 ++
.../packages/web/tests/scope-options.test.tsx | 140 ++
.../packages/web/tsconfig.contracts.json | 7 +
.../route-modules/packages/web/tsconfig.json | 15 +
.../packages/web/tsr.config.json | 36 +
.../web/type-tests/core-contracts.tsx | 211 ++
.../packages/web/type-tests/module-apis.tsx | 207 ++
.../web/type-tests/scope-contracts.tsx | 96 +
.../web/type-tests/validation-aliases.tsx | 110 +
.../route-modules/packages/web/vite.config.ts | 12 +
.../route-modules/playwright.config.ts | 29 +
.../route-modules/playwright.dev.config.ts | 29 +
.../route-modules/scripts/prepare.mjs | 49 +
.../tests/generated-api-bundles.test.ts | 446 ++++
.../tests/generated-scope-cache.test.ts | 114 +
.../tests/host-context-contracts.test.ts | 52 +
.../tests/host-parameter-contracts.test.ts | 73 +
.../route-modules/tests/route-modules.test.ts | 511 +++++
.../route-modules/tests/workspace.ts | 287 +++
e2e/react-router/route-modules/tsconfig.json | 20 +
.../route-modules/vitest.config.ts | 11 +
e2e/react-start/route-modules/.gitignore | 9 +
.../route-modules/e2e-dev/devtools.spec.ts | 50 +
.../route-modules/e2e-dev/hmr.spec.ts | 169 ++
e2e/react-start/route-modules/e2e/app.spec.ts | 160 ++
e2e/react-start/route-modules/package.json | 54 +
.../packages/catalog/package.json | 36 +
.../route-modules/packages/catalog/src/api.ts | 41 +
.../packages/catalog/src/money.ts | 20 +
.../packages/catalog/src/requirements.ts | 7 +
.../catalog/src/routes/$productId.tsx | 62 +
.../packages/catalog/src/routes/__root.tsx | 21 +
.../packages/catalog/src/routes/index.tsx | 25 +
.../packages/catalog/src/start.ts | 8 +
.../packages/catalog/tsconfig.json | 15 +
.../catalog/tsconfig.route-types.json | 13 +
.../route-modules/packages/notes/package.json | 34 +
.../packages/notes/src/routes/__root.tsx | 18 +
.../packages/notes/src/routes/index.tsx | 18 +
.../packages/notes/tsconfig.json | 15 +
.../packages/notes/tsconfig.route-types.json | 13 +
.../packages/settings/package.json | 36 +
.../packages/settings/src/api.ts | 6 +
.../packages/settings/src/routes/__root.tsx | 38 +
.../packages/settings/src/routes/index.tsx | 15 +
.../packages/settings/src/routes/profile.tsx | 27 +
.../packages/settings/tsconfig.json | 15 +
.../settings/tsconfig.route-types.json | 13 +
.../route-modules/packages/team/package.json | 41 +
.../route-modules/packages/team/src/api.ts | 8 +
.../packages/team/src/routes/__root.tsx | 25 +
.../packages/team/src/routes/index.tsx | 27 +
.../team/src/routes/members.$memberId.tsx | 28 +
.../route-modules/packages/team/tsconfig.json | 15 +
.../packages/team/tsconfig.route-types.json | 13 +
.../route-modules/packages/web/package.json | 34 +
.../packages/web/route-modules.ts | 28 +
.../packages/web/rsbuild.config.ts | 16 +
.../route-modules/packages/web/server.js | 19 +
.../route-modules/packages/web/src/router.tsx | 6 +
.../packages/web/src/routes/__root.tsx | 90 +
.../packages/web/src/routes/index.tsx | 90 +
.../packages/web/src/routes/orgs.$orgId.tsx | 15 +
.../web/src/routes/people.$personId.tsx | 13 +
.../route-modules/packages/web/src/start.ts | 12 +
.../route-modules/packages/web/src/styles.css | 486 +++++
.../route-modules/packages/web/tsconfig.json | 15 +
.../route-modules/packages/web/vite.config.ts | 14 +
.../route-modules/playwright.config.ts | 31 +
.../route-modules/playwright.dev.config.ts | 30 +
.../route-modules/scripts/prepare.mjs | 43 +
.../route-modules/tests/start-modules.test.ts | 328 +++
.../route-modules/tests/workspace.ts | 225 ++
e2e/react-start/route-modules/tsconfig.json | 20 +
.../route-modules/vitest.config.ts | 11 +
e2e/solid-router/route-modules/.gitignore | 2 +
.../route-modules/e2e/scope-parity.spec.ts | 177 ++
e2e/solid-router/route-modules/index.html | 11 +
e2e/solid-router/route-modules/package.json | 29 +
.../packages/settings/package.json | 37 +
.../packages/settings/src/routes/__root.tsx | 8 +
.../packages/settings/src/routes/forward.tsx | 4 +
.../packages/settings/src/routes/index.tsx | 4 +
.../packages/settings/src/routes/legacy.tsx | 6 +
.../packages/settings/src/routes/members.tsx | 11 +
.../packages/settings/src/routes/missing.tsx | 6 +
.../packages/settings/src/routes/profile.tsx | 56 +
.../packages/settings/src/routes/search.tsx | 4 +
.../packages/settings/tsconfig.json | 16 +
.../settings/tsconfig.route-types.json | 13 +
.../packages/settings/tsr.config.json | 3 +
.../route-modules/playwright.config.ts | 17 +
.../route-modules/scripts/prepare.mjs | 28 +
e2e/solid-router/route-modules/src/main.tsx | 19 +
.../route-modules/src/routes/__root.tsx | 29 +
.../route-modules/src/routes/orgs.$orgId.tsx | 2 +
.../src/routes/users.$userId.tsx | 2 +
e2e/solid-router/route-modules/tsconfig.json | 16 +
.../route-modules/tsr.config.json | 19 +
.../type-tests/scope-contracts.tsx | 95 +
.../type-tests/validation-aliases.tsx | 110 +
e2e/solid-router/route-modules/vite.config.ts | 10 +
e2e/vue-router/route-modules/.gitignore | 2 +
.../route-modules/e2e/scope-parity.spec.ts | 175 ++
e2e/vue-router/route-modules/index.html | 11 +
e2e/vue-router/route-modules/package.json | 29 +
.../packages/settings/package.json | 37 +
.../packages/settings/src/routes/__root.tsx | 9 +
.../packages/settings/src/routes/forward.tsx | 5 +
.../packages/settings/src/routes/index.tsx | 4 +
.../packages/settings/src/routes/legacy.tsx | 6 +
.../packages/settings/src/routes/members.tsx | 12 +
.../packages/settings/src/routes/missing.tsx | 6 +
.../packages/settings/src/routes/profile.tsx | 58 +
.../packages/settings/src/routes/search.tsx | 4 +
.../packages/settings/tsconfig.json | 16 +
.../settings/tsconfig.route-types.json | 13 +
.../packages/settings/tsr.config.json | 3 +
.../route-modules/playwright.config.ts | 17 +
.../route-modules/scripts/prepare.mjs | 28 +
e2e/vue-router/route-modules/src/main.tsx | 16 +
.../route-modules/src/routes/__root.tsx | 32 +
.../route-modules/src/routes/orgs.$orgId.tsx | 2 +
.../src/routes/users.$userId.tsx | 2 +
e2e/vue-router/route-modules/tsconfig.json | 16 +
e2e/vue-router/route-modules/tsr.config.json | 19 +
.../type-tests/scope-contracts.tsx | 95 +
.../type-tests/validation-aliases.tsx | 110 +
e2e/vue-router/route-modules/vite.config.ts | 10 +
eslint.config.js | 14 +
.../start-large-route-modules/.gitignore | 21 +
.../start-large-route-modules/.prettierignore | 4 +
.../react/start-large-route-modules/README.md | 80 +
.../app/rsbuild.config.ts | 11 +
.../start-large-route-modules/app/server.js | 18 +
.../app/src/router.tsx | 10 +
.../app/src/routes/__root.tsx | 44 +
.../app/src/routes/index.tsx | 23 +
.../app/src/start.ts | 10 +
.../app/src/styles.css | 114 +
.../app/tsconfig.json | 20 +
.../app/vite.config.ts | 11 +
.../start-large-route-modules/package.json | 49 +
.../start-large-route-modules/scripts/gen.mjs | 384 ++++
.../scripts/measure.mjs | 242 +++
.../template/account/src/api.ts | 8 +
.../template/account/src/routes/__root.tsx | 18 +
.../template/account/src/routes/index.tsx | 21 +
.../template/feature/src/api.ts | 45 +
.../template/feature/src/requirements.ts | 10 +
.../template/feature/src/routes/$itemId.tsx | 28 +
.../template/feature/src/routes/__root.tsx | 28 +
.../template/feature/src/routes/index.tsx | 25 +
.../feature/src/routes/pages/page.tsx | 30 +
.../template/feature/src/routes/search.tsx | 44 +
.../src/__tests__/fixtures/app/package.json | 4 +
.../fixtures/route-module/package.json | 9 +
.../route-module-imports.rule.test.ts | 101 +
packages/eslint-plugin-router/src/index.ts | 2 +
packages/eslint-plugin-router/src/rules.ts | 2 +
.../rules/route-module-imports/constants.ts | 37 +
.../route-module-imports.rule.ts | 90 +
.../route-module-imports.utils.ts | 50 +
packages/eslint-plugin-router/tsconfig.json | 3 +-
packages/react-router/package.json | 24 +-
packages/react-router/src/Match.tsx | 6 +-
packages/react-router/src/Matches.tsx | 72 +-
packages/react-router/src/fileRoute.ts | 142 +-
packages/react-router/src/index.tsx | 47 +
packages/react-router/src/link.tsx | 81 +-
packages/react-router/src/matchContext.tsx | 2 +-
.../react-router/src/route-module-internal.ts | 6 +
packages/react-router/src/route.tsx | 130 +-
packages/react-router/src/routeModule.tsx | 441 ++++
packages/react-router/src/router.ts | 2 +-
packages/react-router/src/routerStores.ts | 2 +-
packages/react-router/src/ssr/serializer.ts | 2 +-
packages/react-router/src/useBlocker.tsx | 41 +-
packages/react-router/src/useLoaderData.tsx | 26 +-
packages/react-router/src/useLoaderDeps.tsx | 19 +-
packages/react-router/src/useLocation.tsx | 15 +
packages/react-router/src/useMatch.tsx | 51 +-
packages/react-router/src/useNavigate.tsx | 55 +-
packages/react-router/src/useParams.tsx | 31 +-
packages/react-router/src/useRouteContext.ts | 19 +-
packages/react-router/src/useRouter.tsx | 17 +-
packages/react-router/src/useRouterState.tsx | 16 +-
packages/react-router/src/useSearch.tsx | 31 +-
.../tests/blocker-server.test.tsx | 33 +
.../tests/navigate-options-parity.test.tsx | 96 +
.../tests/registered-router-cycle/app.tsx | 95 +
.../registered-router-cycle/tsconfig.json | 6 +
.../react-router/tests/routeApi.test-d.tsx | 2 +-
packages/react-router/tsconfig.json | 3 +-
packages/react-router/vite.config.ts | 1 +
packages/react-start-rsc/eslint.config.js | 3 +-
packages/react-start-rsc/package.json | 2 +-
.../src/ServerComponentTypes.ts | 2 +-
packages/react-start/package.json | 10 +-
packages/react-start/src/index.ts | 1 +
.../react-start/src/route-module-internal.ts | 1 +
packages/react-start/vite.config.ts | 1 +
packages/router-cli/package.json | 2 +-
packages/router-core/package.json | 22 +-
packages/router-core/src/Matches.ts | 101 +-
packages/router-core/src/RouterProvider.ts | 19 +-
packages/router-core/src/extensions.ts | 32 +
packages/router-core/src/index.ts | 57 +-
packages/router-core/src/link.ts | 41 +
packages/router-core/src/load-client.ts | 20 +-
packages/router-core/src/load-server.ts | 16 +-
packages/router-core/src/redirect.ts | 24 +-
packages/router-core/src/route-id.ts | 27 +
.../router-core/src/route-module-internal.ts | 4 +
packages/router-core/src/route-module.ts | 820 ++++++++
packages/router-core/src/route.ts | 68 +-
packages/router-core/src/router.ts | 85 +-
packages/router-core/src/stores.ts | 4 +-
packages/router-core/src/useNavigate.ts | 14 +-
.../tests/route-module-unmounted.test.ts | 44 +
.../router-core/tests/route-module.test.ts | 853 ++++++++
.../router-core/tests/route-modules.bench.ts | 342 +++
packages/router-core/vite.config.ts | 2 +
.../src/BaseTanStackRouterDevtoolsPanel.tsx | 287 ++-
.../router-devtools-core/src/routeModules.ts | 75 +
.../router-devtools-core/src/useStyles.tsx | 48 +
.../tests/route-modules.test.ts | 198 ++
packages/router-generator/src/config.ts | 25 +-
.../router-generator/src/generated-names.ts | 120 ++
packages/router-generator/src/generator.ts | 1126 +++++++++-
packages/router-generator/src/index.ts | 26 +
.../src}/pruneServerOnlySubtrees.ts | 8 +-
.../src/route-module/context.ts | 629 ++++++
.../src/route-module/declaration.ts | 252 +++
.../router-generator/src/route-module/emit.ts | 493 +++++
.../src/route-module/manifest.ts | 126 ++
.../src/routeClassification.ts | 11 +
.../src/transform/transform.ts | 42 +-
.../router-generator/src/transform/types.ts | 5 +
packages/router-generator/src/types.ts | 10 +
packages/router-generator/src/utils.ts | 44 +-
.../tests/route-modules.test.ts | 1859 +++++++++++++++++
.../routeScope.catalog.snapshot.ts | 210 ++
.../application/routeScope.snapshot.ts | 9 +
.../application/routeTree.snapshot.ts | 79 +
.../host-params/routeContract.snapshot.ts | 49 +
.../routeScope.catalog.snapshot.ts | 218 ++
.../host-params/routeScope.snapshot.ts | 261 +++
.../host-params/routeTree.snapshot.ts | 103 +
.../includer/routeContract.snapshot.ts | 49 +
.../includer/routeScope.catalog.snapshot.ts | 210 ++
.../includer/routeScope.snapshot.ts | 261 +++
.../includer/routeTree.snapshot.ts | 99 +
.../routeScope.account.snapshot.ts | 218 ++
.../routeScope.orgCatalog.snapshot.ts | 249 +++
.../installations/routeScope.snapshot.ts | 13 +
.../routeScope.userCatalog.snapshot.ts | 255 +++
.../installations/routeTree.snapshot.ts | 157 ++
.../module/routeContract.snapshot.ts | 33 +
.../module/routeModule.snapshot.ts | 10 +
.../module/routeScope.snapshot.ts | 277 +++
.../module/routeTree.snapshot.ts | 112 +
.../startModules.snapshot.ts | 34 +
.../start-module/routeModule.snapshot.ts | 18 +
.../start-module/routeScope.snapshot.ts | 306 +++
packages/router-generator/tsconfig.json | 3 +-
.../router-generator/tsconfig.legacy.json | 2 +-
packages/router-plugin/package.json | 2 +-
.../src/core/code-splitter/compilers.ts | 37 +-
.../src/core/hmr/handle-route-update.ts | 76 +-
.../src/core/hmr/vite-adapter.ts | 10 +-
.../src/core/hmr/webpack-adapter.ts | 12 +-
.../src/core/router-generator-plugin.ts | 42 +-
packages/router-plugin/tests/add-hmr.test.ts | 2 +-
.../snapshots/react/arrow-function@true.tsx | 70 +-
.../react/arrow-function@webpack-hot.tsx | 72 +-
...ateFileRoute-lowercase-components@true.tsx | 70 +-
.../createRootRoute-inline-component@true.tsx | 70 +-
...ateRootRoute-lowercase-components@true.tsx | 70 +-
.../snapshots/react/createRootRoute@true.tsx | 70 +-
...ateRootRouteWithContext-type-args@true.tsx | 70 +-
.../explicit-undefined-component@true.tsx | 70 +-
.../react/function-declaration@true.tsx | 70 +-
.../snapshots/react/multi-component@true.tsx | 70 +-
.../react/string-literal-keys@true.tsx | 70 +-
.../snapshots/solid/arrow-function@true.tsx | 70 +-
.../router-plugin/tests/code-splitter.test.ts | 193 +-
.../react/1-default/inline-memo-component.tsx | 7 +
.../inline-memo-component@component.tsx | 6 +
.../inline-memo-component@errorComponent.tsx | 0
...nline-memo-component@notFoundComponent.tsx | 0
.../inline-memo-component@shared.tsx | 0
.../inline-memo-component.tsx | 7 +
...--notFoundComponent---pendingComponent.tsx | 6 +
.../inline-memo-component@loader.tsx | 0
.../inline-memo-component@shared.tsx | 0
.../inline-memo-component.tsx | 7 +
...--notFoundComponent---pendingComponent.tsx | 6 +
.../inline-memo-component@errorComponent.tsx | 0
.../inline-memo-component@shared.tsx | 0
.../vue/1-default/inline-define-component.tsx | 7 +
.../inline-define-component@component.tsx | 8 +
...inline-define-component@errorComponent.tsx | 0
...ine-define-component@notFoundComponent.tsx | 0
.../inline-define-component@shared.tsx | 0
.../inline-define-component.tsx | 7 +
...--notFoundComponent---pendingComponent.tsx | 8 +
.../inline-define-component@loader.tsx | 0
.../inline-define-component@shared.tsx | 0
.../inline-define-component.tsx | 7 +
...--notFoundComponent---pendingComponent.tsx | 8 +
...inline-define-component@errorComponent.tsx | 0
.../inline-define-component@shared.tsx | 0
.../react/inline-memo-component.tsx | 9 +
.../vue/inline-define-component.tsx | 11 +
.../tests/handle-route-update.test.ts | 76 +-
packages/router-vite-plugin/package.json | 2 +-
packages/solid-router/package.json | 16 +-
packages/solid-router/src/Match.tsx | 9 +-
packages/solid-router/src/Matches.tsx | 69 +-
packages/solid-router/src/fileRoute.ts | 142 +-
packages/solid-router/src/index.tsx | 47 +
packages/solid-router/src/link.tsx | 39 +-
.../solid-router/src/route-module-internal.ts | 6 +
packages/solid-router/src/route.tsx | 125 +-
packages/solid-router/src/routeModule.tsx | 435 ++++
packages/solid-router/src/router.ts | 2 +-
packages/solid-router/src/useBlocker.tsx | 41 +-
packages/solid-router/src/useLoaderData.tsx | 19 +-
packages/solid-router/src/useLoaderDeps.tsx | 18 +-
packages/solid-router/src/useLocation.tsx | 13 +
packages/solid-router/src/useMatch.tsx | 59 +-
packages/solid-router/src/useNavigate.tsx | 65 +-
packages/solid-router/src/useParams.tsx | 28 +-
packages/solid-router/src/useRouteContext.ts | 19 +-
packages/solid-router/src/useRouter.tsx | 17 +-
packages/solid-router/src/useRouterState.tsx | 21 +-
packages/solid-router/src/useSearch.tsx | 28 +-
.../tests/blocker-server.test.tsx | 32 +
.../tests/navigate-options-parity.test.tsx | 74 +
.../solid-router/tests/routeApi.test-d.tsx | 2 +-
.../tests/server/Navigate.test.tsx | 34 +
packages/solid-router/vite.config.ts | 1 +
packages/solid-start/package.json | 10 +-
packages/solid-start/src/index.ts | 1 +
.../solid-start/src/route-module-internal.ts | 1 +
packages/solid-start/vite.config.ts | 1 +
packages/start-client-core/package.json | 8 +-
.../start-client-core/src/createMiddleware.ts | 42 +-
.../start-client-core/src/createServerFn.ts | 4 +-
packages/start-client-core/src/createStart.ts | 193 +-
.../src/createStartModule.ts | 797 +++++++
packages/start-client-core/src/index.tsx | 15 +
.../src/route-module-internal.ts | 1 +
packages/start-client-core/src/serverRoute.ts | 2 +-
.../start-client-core/src/startOptionList.ts | 11 +
.../src/tests/createStartModule.test-d.ts | 331 +++
.../tests/moduleMiddlewareConsumers.test-d.ts | 111 +
.../startModuleConditionalEntry.test-d.ts | 40 +
.../startModuleConditionalOptions.test-d.ts | 331 +++
...tartModuleContextProjectionEdges.test-d.ts | 316 +++
.../tests/startModuleContextScaling.test-d.ts | 211 ++
.../tests/startModuleGlobalOwner.test-d.ts | 106 +
...startModuleImpossibleRequirement.test-d.ts | 26 +
.../tests/startModuleInstallation.test-d.ts | 56 +
.../startModuleRequirementFreeArray.test-d.ts | 34 +
.../startModuleUnionRequirement.test-d.ts | 178 ++
.../startModuleUnscopedConsumer.test-d.ts | 70 +
.../startModuleWidenedGlobalDedupe.test-d.ts | 43 +
.../tests/createStartModule.test.ts | 175 ++
packages/start-client-core/vite.config.ts | 1 +
packages/start-plugin-core/package.json | 2 +-
.../src/import-protection/adapterUtils.ts | 12 +-
packages/start-plugin-core/src/prerender.ts | 11 +-
.../src/rsbuild/import-protection.ts | 18 +-
.../start-plugin-core/src/rsbuild/plugin.ts | 37 +-
.../src/rsbuild/start-compiler-host.ts | 53 +-
.../src/rsbuild/start-router-plugin.ts | 38 +
.../start-router-plugin/client-route-tree.ts | 87 +
.../start-router-plugin/generator-config.ts | 2 +-
.../prerender-routes-plugin.ts | 36 +-
.../routes-manifest-plugin.ts | 79 +-
.../route-module-directories.ts | 25 +
.../vite/import-protection-plugin/plugin.ts | 17 +-
.../vite/import-protection-plugin/types.ts | 2 +
.../src/vite/start-router-plugin/plugin.ts | 82 +-
.../tests/route-module-start-build.test.ts | 744 +++++++
packages/vue-router/package.json | 8 +-
packages/vue-router/src/Match.tsx | 6 +-
packages/vue-router/src/Matches.tsx | 76 +-
packages/vue-router/src/fileRoute.ts | 142 +-
packages/vue-router/src/index.tsx | 47 +
packages/vue-router/src/link.tsx | 70 +-
.../vue-router/src/route-module-internal.ts | 6 +
packages/vue-router/src/route.ts | 128 +-
packages/vue-router/src/routeModule.ts | 441 ++++
packages/vue-router/src/router.ts | 2 +-
packages/vue-router/src/routerStores.ts | 2 +-
packages/vue-router/src/useBlocker.tsx | 39 +-
packages/vue-router/src/useLoaderData.tsx | 19 +-
packages/vue-router/src/useLoaderDeps.tsx | 18 +-
packages/vue-router/src/useLocation.tsx | 13 +
packages/vue-router/src/useMatch.tsx | 89 +-
packages/vue-router/src/useNavigate.tsx | 74 +-
packages/vue-router/src/useParams.tsx | 28 +-
packages/vue-router/src/useRouteContext.ts | 19 +-
packages/vue-router/src/useRouter.tsx | 17 +-
packages/vue-router/src/useRouterState.tsx | 17 +-
packages/vue-router/src/useSearch.tsx | 28 +-
.../vue-router/tests/blocker-server.test.tsx | 38 +
.../tests/navigate-options-parity.test.tsx | 107 +
packages/vue-router/vite.config.ts | 1 +
packages/vue-start/package.json | 10 +-
packages/vue-start/src/index.ts | 1 +
.../vue-start/src/route-module-internal.ts | 1 +
packages/vue-start/vite.config.ts | 1 +
pnpm-lock.yaml | 683 +++++-
pnpm-workspace.yaml | 8 +-
scripts/benchmarks/route-modules/measure.mjs | 586 ++++++
.../benchmarks/route-modules/measure.test.mjs | 32 +
.../benchmarks/route-modules/scoped-match.mjs | 241 +++
.../benchmarks/route-modules/start-types.mjs | 325 +++
507 files changed, 33445 insertions(+), 1286 deletions(-)
create mode 100644 .changeset/clever-buttons-push.md
create mode 100644 .changeset/itchy-chairs-melt.md
create mode 100644 .changeset/route-modules-devtools.md
create mode 100644 .changeset/route-modules-eslint.md
create mode 100644 .changeset/route-modules-generator.md
create mode 100644 .changeset/route-modules-router.md
create mode 100644 .changeset/route-modules-start.md
create mode 100644 .changeset/router-core-extensions.md
create mode 100644 .changeset/salty-dryers-move.md
create mode 100644 .changeset/start-modules-many-fragments.md
create mode 100644 .changeset/start-rsbuild-compiler-esm-resolve.md
create mode 100644 .changeset/true-houses-behave.md
create mode 100644 docs/router/eslint/route-module-imports.md
create mode 100644 docs/router/routing/route-modules.md
create mode 100644 docs/start/framework/react/guide/route-modules.md
create mode 100644 e2e/react-router/route-modules/.gitignore
create mode 100644 e2e/react-router/route-modules/e2e-dev/devtools.spec.ts
create mode 100644 e2e/react-router/route-modules/e2e-dev/hmr.spec.ts
create mode 100644 e2e/react-router/route-modules/e2e/app.spec.ts
create mode 100644 e2e/react-router/route-modules/e2e/scope-parity.spec.ts
create mode 100644 e2e/react-router/route-modules/package.json
create mode 100644 e2e/react-router/route-modules/packages/account/package.json
create mode 100644 e2e/react-router/route-modules/packages/account/src/routes/__root.tsx
create mode 100644 e2e/react-router/route-modules/packages/account/src/routes/index.tsx
create mode 100644 e2e/react-router/route-modules/packages/account/src/routes/orders.$orderId.tsx
create mode 100644 e2e/react-router/route-modules/packages/account/tsconfig.json
create mode 100644 e2e/react-router/route-modules/packages/account/tsconfig.route-types.json
create mode 100644 e2e/react-router/route-modules/packages/billing/package.json
create mode 100644 e2e/react-router/route-modules/packages/billing/src/routes/__root.tsx
create mode 100644 e2e/react-router/route-modules/packages/billing/src/routes/index.tsx
create mode 100644 e2e/react-router/route-modules/packages/billing/tsconfig.json
create mode 100644 e2e/react-router/route-modules/packages/billing/tsconfig.route-types.json
create mode 100644 e2e/react-router/route-modules/packages/products/package.json
create mode 100644 e2e/react-router/route-modules/packages/products/src/api.ts
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/$productId.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/__root.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/_layout.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/_layout/deals.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/catalog.{-$category}.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/compare.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/files.$.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/index.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/legacy.tsx
create mode 100644 e2e/react-router/route-modules/packages/products/src/schemas.ts
create mode 100644 e2e/react-router/route-modules/packages/products/tsconfig.json
create mode 100644 e2e/react-router/route-modules/packages/products/tsconfig.route-types.json
create mode 100644 e2e/react-router/route-modules/packages/settings/package.json
create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/__root.tsx
create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/forward.tsx
create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/index.tsx
create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/legacy.tsx
create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/members.tsx
create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/missing.tsx
create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx
create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/search.tsx
create mode 100644 e2e/react-router/route-modules/packages/settings/tsconfig.json
create mode 100644 e2e/react-router/route-modules/packages/settings/tsconfig.route-types.json
create mode 100644 e2e/react-router/route-modules/packages/storefront/package.json
create mode 100644 e2e/react-router/route-modules/packages/storefront/src/routes/__root.tsx
create mode 100644 e2e/react-router/route-modules/packages/storefront/src/routes/cart.tsx
create mode 100644 e2e/react-router/route-modules/packages/storefront/src/routes/index.tsx
create mode 100644 e2e/react-router/route-modules/packages/storefront/tsconfig.json
create mode 100644 e2e/react-router/route-modules/packages/storefront/tsconfig.route-types.json
create mode 100644 e2e/react-router/route-modules/packages/team/package.json
create mode 100644 e2e/react-router/route-modules/packages/team/src/routes/__root.tsx
create mode 100644 e2e/react-router/route-modules/packages/team/src/routes/index.tsx
create mode 100644 e2e/react-router/route-modules/packages/team/src/routes/members.$memberId.tsx
create mode 100644 e2e/react-router/route-modules/packages/team/tsconfig.json
create mode 100644 e2e/react-router/route-modules/packages/team/tsconfig.route-types.json
create mode 100644 e2e/react-router/route-modules/packages/web/index.html
create mode 100644 e2e/react-router/route-modules/packages/web/package.json
create mode 100644 e2e/react-router/route-modules/packages/web/src/main.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/src/profile-links.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/src/router.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/__root.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/_authenticated.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/index.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/orgs.$orgId.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/people.$personId.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/src/styles.css
create mode 100644 e2e/react-router/route-modules/packages/web/tests/match-identity.test.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/tests/scope-options.test.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/tsconfig.contracts.json
create mode 100644 e2e/react-router/route-modules/packages/web/tsconfig.json
create mode 100644 e2e/react-router/route-modules/packages/web/tsr.config.json
create mode 100644 e2e/react-router/route-modules/packages/web/type-tests/core-contracts.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/type-tests/module-apis.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/type-tests/scope-contracts.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/type-tests/validation-aliases.tsx
create mode 100644 e2e/react-router/route-modules/packages/web/vite.config.ts
create mode 100644 e2e/react-router/route-modules/playwright.config.ts
create mode 100644 e2e/react-router/route-modules/playwright.dev.config.ts
create mode 100644 e2e/react-router/route-modules/scripts/prepare.mjs
create mode 100644 e2e/react-router/route-modules/tests/generated-api-bundles.test.ts
create mode 100644 e2e/react-router/route-modules/tests/generated-scope-cache.test.ts
create mode 100644 e2e/react-router/route-modules/tests/host-context-contracts.test.ts
create mode 100644 e2e/react-router/route-modules/tests/host-parameter-contracts.test.ts
create mode 100644 e2e/react-router/route-modules/tests/route-modules.test.ts
create mode 100644 e2e/react-router/route-modules/tests/workspace.ts
create mode 100644 e2e/react-router/route-modules/tsconfig.json
create mode 100644 e2e/react-router/route-modules/vitest.config.ts
create mode 100644 e2e/react-start/route-modules/.gitignore
create mode 100644 e2e/react-start/route-modules/e2e-dev/devtools.spec.ts
create mode 100644 e2e/react-start/route-modules/e2e-dev/hmr.spec.ts
create mode 100644 e2e/react-start/route-modules/e2e/app.spec.ts
create mode 100644 e2e/react-start/route-modules/package.json
create mode 100644 e2e/react-start/route-modules/packages/catalog/package.json
create mode 100644 e2e/react-start/route-modules/packages/catalog/src/api.ts
create mode 100644 e2e/react-start/route-modules/packages/catalog/src/money.ts
create mode 100644 e2e/react-start/route-modules/packages/catalog/src/requirements.ts
create mode 100644 e2e/react-start/route-modules/packages/catalog/src/routes/$productId.tsx
create mode 100644 e2e/react-start/route-modules/packages/catalog/src/routes/__root.tsx
create mode 100644 e2e/react-start/route-modules/packages/catalog/src/routes/index.tsx
create mode 100644 e2e/react-start/route-modules/packages/catalog/src/start.ts
create mode 100644 e2e/react-start/route-modules/packages/catalog/tsconfig.json
create mode 100644 e2e/react-start/route-modules/packages/catalog/tsconfig.route-types.json
create mode 100644 e2e/react-start/route-modules/packages/notes/package.json
create mode 100644 e2e/react-start/route-modules/packages/notes/src/routes/__root.tsx
create mode 100644 e2e/react-start/route-modules/packages/notes/src/routes/index.tsx
create mode 100644 e2e/react-start/route-modules/packages/notes/tsconfig.json
create mode 100644 e2e/react-start/route-modules/packages/notes/tsconfig.route-types.json
create mode 100644 e2e/react-start/route-modules/packages/settings/package.json
create mode 100644 e2e/react-start/route-modules/packages/settings/src/api.ts
create mode 100644 e2e/react-start/route-modules/packages/settings/src/routes/__root.tsx
create mode 100644 e2e/react-start/route-modules/packages/settings/src/routes/index.tsx
create mode 100644 e2e/react-start/route-modules/packages/settings/src/routes/profile.tsx
create mode 100644 e2e/react-start/route-modules/packages/settings/tsconfig.json
create mode 100644 e2e/react-start/route-modules/packages/settings/tsconfig.route-types.json
create mode 100644 e2e/react-start/route-modules/packages/team/package.json
create mode 100644 e2e/react-start/route-modules/packages/team/src/api.ts
create mode 100644 e2e/react-start/route-modules/packages/team/src/routes/__root.tsx
create mode 100644 e2e/react-start/route-modules/packages/team/src/routes/index.tsx
create mode 100644 e2e/react-start/route-modules/packages/team/src/routes/members.$memberId.tsx
create mode 100644 e2e/react-start/route-modules/packages/team/tsconfig.json
create mode 100644 e2e/react-start/route-modules/packages/team/tsconfig.route-types.json
create mode 100644 e2e/react-start/route-modules/packages/web/package.json
create mode 100644 e2e/react-start/route-modules/packages/web/route-modules.ts
create mode 100644 e2e/react-start/route-modules/packages/web/rsbuild.config.ts
create mode 100644 e2e/react-start/route-modules/packages/web/server.js
create mode 100644 e2e/react-start/route-modules/packages/web/src/router.tsx
create mode 100644 e2e/react-start/route-modules/packages/web/src/routes/__root.tsx
create mode 100644 e2e/react-start/route-modules/packages/web/src/routes/index.tsx
create mode 100644 e2e/react-start/route-modules/packages/web/src/routes/orgs.$orgId.tsx
create mode 100644 e2e/react-start/route-modules/packages/web/src/routes/people.$personId.tsx
create mode 100644 e2e/react-start/route-modules/packages/web/src/start.ts
create mode 100644 e2e/react-start/route-modules/packages/web/src/styles.css
create mode 100644 e2e/react-start/route-modules/packages/web/tsconfig.json
create mode 100644 e2e/react-start/route-modules/packages/web/vite.config.ts
create mode 100644 e2e/react-start/route-modules/playwright.config.ts
create mode 100644 e2e/react-start/route-modules/playwright.dev.config.ts
create mode 100644 e2e/react-start/route-modules/scripts/prepare.mjs
create mode 100644 e2e/react-start/route-modules/tests/start-modules.test.ts
create mode 100644 e2e/react-start/route-modules/tests/workspace.ts
create mode 100644 e2e/react-start/route-modules/tsconfig.json
create mode 100644 e2e/react-start/route-modules/vitest.config.ts
create mode 100644 e2e/solid-router/route-modules/.gitignore
create mode 100644 e2e/solid-router/route-modules/e2e/scope-parity.spec.ts
create mode 100644 e2e/solid-router/route-modules/index.html
create mode 100644 e2e/solid-router/route-modules/package.json
create mode 100644 e2e/solid-router/route-modules/packages/settings/package.json
create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/__root.tsx
create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/forward.tsx
create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/index.tsx
create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/legacy.tsx
create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/members.tsx
create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/missing.tsx
create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/profile.tsx
create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/search.tsx
create mode 100644 e2e/solid-router/route-modules/packages/settings/tsconfig.json
create mode 100644 e2e/solid-router/route-modules/packages/settings/tsconfig.route-types.json
create mode 100644 e2e/solid-router/route-modules/packages/settings/tsr.config.json
create mode 100644 e2e/solid-router/route-modules/playwright.config.ts
create mode 100644 e2e/solid-router/route-modules/scripts/prepare.mjs
create mode 100644 e2e/solid-router/route-modules/src/main.tsx
create mode 100644 e2e/solid-router/route-modules/src/routes/__root.tsx
create mode 100644 e2e/solid-router/route-modules/src/routes/orgs.$orgId.tsx
create mode 100644 e2e/solid-router/route-modules/src/routes/users.$userId.tsx
create mode 100644 e2e/solid-router/route-modules/tsconfig.json
create mode 100644 e2e/solid-router/route-modules/tsr.config.json
create mode 100644 e2e/solid-router/route-modules/type-tests/scope-contracts.tsx
create mode 100644 e2e/solid-router/route-modules/type-tests/validation-aliases.tsx
create mode 100644 e2e/solid-router/route-modules/vite.config.ts
create mode 100644 e2e/vue-router/route-modules/.gitignore
create mode 100644 e2e/vue-router/route-modules/e2e/scope-parity.spec.ts
create mode 100644 e2e/vue-router/route-modules/index.html
create mode 100644 e2e/vue-router/route-modules/package.json
create mode 100644 e2e/vue-router/route-modules/packages/settings/package.json
create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/__root.tsx
create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/forward.tsx
create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/index.tsx
create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/legacy.tsx
create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/members.tsx
create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/missing.tsx
create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/profile.tsx
create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/search.tsx
create mode 100644 e2e/vue-router/route-modules/packages/settings/tsconfig.json
create mode 100644 e2e/vue-router/route-modules/packages/settings/tsconfig.route-types.json
create mode 100644 e2e/vue-router/route-modules/packages/settings/tsr.config.json
create mode 100644 e2e/vue-router/route-modules/playwright.config.ts
create mode 100644 e2e/vue-router/route-modules/scripts/prepare.mjs
create mode 100644 e2e/vue-router/route-modules/src/main.tsx
create mode 100644 e2e/vue-router/route-modules/src/routes/__root.tsx
create mode 100644 e2e/vue-router/route-modules/src/routes/orgs.$orgId.tsx
create mode 100644 e2e/vue-router/route-modules/src/routes/users.$userId.tsx
create mode 100644 e2e/vue-router/route-modules/tsconfig.json
create mode 100644 e2e/vue-router/route-modules/tsr.config.json
create mode 100644 e2e/vue-router/route-modules/type-tests/scope-contracts.tsx
create mode 100644 e2e/vue-router/route-modules/type-tests/validation-aliases.tsx
create mode 100644 e2e/vue-router/route-modules/vite.config.ts
create mode 100644 examples/react/start-large-route-modules/.gitignore
create mode 100644 examples/react/start-large-route-modules/.prettierignore
create mode 100644 examples/react/start-large-route-modules/README.md
create mode 100644 examples/react/start-large-route-modules/app/rsbuild.config.ts
create mode 100644 examples/react/start-large-route-modules/app/server.js
create mode 100644 examples/react/start-large-route-modules/app/src/router.tsx
create mode 100644 examples/react/start-large-route-modules/app/src/routes/__root.tsx
create mode 100644 examples/react/start-large-route-modules/app/src/routes/index.tsx
create mode 100644 examples/react/start-large-route-modules/app/src/start.ts
create mode 100644 examples/react/start-large-route-modules/app/src/styles.css
create mode 100644 examples/react/start-large-route-modules/app/tsconfig.json
create mode 100644 examples/react/start-large-route-modules/app/vite.config.ts
create mode 100644 examples/react/start-large-route-modules/package.json
create mode 100644 examples/react/start-large-route-modules/scripts/gen.mjs
create mode 100644 examples/react/start-large-route-modules/scripts/measure.mjs
create mode 100644 examples/react/start-large-route-modules/template/account/src/api.ts
create mode 100644 examples/react/start-large-route-modules/template/account/src/routes/__root.tsx
create mode 100644 examples/react/start-large-route-modules/template/account/src/routes/index.tsx
create mode 100644 examples/react/start-large-route-modules/template/feature/src/api.ts
create mode 100644 examples/react/start-large-route-modules/template/feature/src/requirements.ts
create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/$itemId.tsx
create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/__root.tsx
create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/index.tsx
create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/pages/page.tsx
create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/search.tsx
create mode 100644 packages/eslint-plugin-router/src/__tests__/fixtures/app/package.json
create mode 100644 packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json
create mode 100644 packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts
create mode 100644 packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts
create mode 100644 packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts
create mode 100644 packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts
create mode 100644 packages/react-router/src/route-module-internal.ts
create mode 100644 packages/react-router/src/routeModule.tsx
create mode 100644 packages/react-router/tests/blocker-server.test.tsx
create mode 100644 packages/react-router/tests/navigate-options-parity.test.tsx
create mode 100644 packages/react-router/tests/registered-router-cycle/app.tsx
create mode 100644 packages/react-router/tests/registered-router-cycle/tsconfig.json
create mode 100644 packages/react-start/src/route-module-internal.ts
create mode 100644 packages/router-core/src/extensions.ts
create mode 100644 packages/router-core/src/route-id.ts
create mode 100644 packages/router-core/src/route-module-internal.ts
create mode 100644 packages/router-core/src/route-module.ts
create mode 100644 packages/router-core/tests/route-module-unmounted.test.ts
create mode 100644 packages/router-core/tests/route-module.test.ts
create mode 100644 packages/router-core/tests/route-modules.bench.ts
create mode 100644 packages/router-devtools-core/src/routeModules.ts
create mode 100644 packages/router-devtools-core/tests/route-modules.test.ts
create mode 100644 packages/router-generator/src/generated-names.ts
rename packages/{start-plugin-core/src/start-router-plugin => router-generator/src}/pruneServerOnlySubtrees.ts (85%)
create mode 100644 packages/router-generator/src/route-module/context.ts
create mode 100644 packages/router-generator/src/route-module/declaration.ts
create mode 100644 packages/router-generator/src/route-module/emit.ts
create mode 100644 packages/router-generator/src/route-module/manifest.ts
create mode 100644 packages/router-generator/src/routeClassification.ts
create mode 100644 packages/router-generator/tests/route-modules.test.ts
create mode 100644 packages/router-generator/tests/route-modules/application/routeScope.catalog.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/application/routeScope.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/application/routeTree.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/host-params/routeContract.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/host-params/routeScope.catalog.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/host-params/routeScope.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/host-params/routeTree.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/includer/routeContract.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/includer/routeScope.catalog.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/includer/routeScope.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/includer/routeTree.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/installations/routeScope.account.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/installations/routeScope.orgCatalog.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/installations/routeScope.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/installations/routeScope.userCatalog.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/installations/routeTree.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/module/routeContract.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/module/routeModule.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/module/routeScope.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/module/routeTree.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/start-application/startModules.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/start-module/routeModule.snapshot.ts
create mode 100644 packages/router-generator/tests/route-modules/start-module/routeScope.snapshot.ts
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@errorComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@notFoundComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@shared.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@loader.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@shared.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@component---loader---notFoundComponent---pendingComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@errorComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@shared.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@errorComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@notFoundComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@shared.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@component---errorComponent---notFoundComponent---pendingComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@loader.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@shared.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@component---loader---notFoundComponent---pendingComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@errorComponent.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@shared.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/test-files/react/inline-memo-component.tsx
create mode 100644 packages/router-plugin/tests/code-splitter/test-files/vue/inline-define-component.tsx
create mode 100644 packages/solid-router/src/route-module-internal.ts
create mode 100644 packages/solid-router/src/routeModule.tsx
create mode 100644 packages/solid-router/tests/blocker-server.test.tsx
create mode 100644 packages/solid-router/tests/navigate-options-parity.test.tsx
create mode 100644 packages/solid-router/tests/server/Navigate.test.tsx
create mode 100644 packages/solid-start/src/route-module-internal.ts
create mode 100644 packages/start-client-core/src/createStartModule.ts
create mode 100644 packages/start-client-core/src/route-module-internal.ts
create mode 100644 packages/start-client-core/src/startOptionList.ts
create mode 100644 packages/start-client-core/src/tests/createStartModule.test-d.ts
create mode 100644 packages/start-client-core/src/tests/moduleMiddlewareConsumers.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleConditionalEntry.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleConditionalOptions.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleContextProjectionEdges.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleContextScaling.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleGlobalOwner.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleImpossibleRequirement.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleInstallation.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleRequirementFreeArray.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleUnionRequirement.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleUnscopedConsumer.test-d.ts
create mode 100644 packages/start-client-core/src/tests/startModuleWidenedGlobalDedupe.test-d.ts
create mode 100644 packages/start-client-core/tests/createStartModule.test.ts
create mode 100644 packages/start-plugin-core/src/start-router-plugin/client-route-tree.ts
create mode 100644 packages/start-plugin-core/src/start-router-plugin/route-module-directories.ts
create mode 100644 packages/start-plugin-core/tests/route-module-start-build.test.ts
create mode 100644 packages/vue-router/src/route-module-internal.ts
create mode 100644 packages/vue-router/src/routeModule.ts
create mode 100644 packages/vue-router/tests/blocker-server.test.tsx
create mode 100644 packages/vue-router/tests/navigate-options-parity.test.tsx
create mode 100644 packages/vue-start/src/route-module-internal.ts
create mode 100644 scripts/benchmarks/route-modules/measure.mjs
create mode 100644 scripts/benchmarks/route-modules/measure.test.mjs
create mode 100644 scripts/benchmarks/route-modules/scoped-match.mjs
create mode 100644 scripts/benchmarks/route-modules/start-types.mjs
diff --git a/.changeset/clever-buttons-push.md b/.changeset/clever-buttons-push.md
new file mode 100644
index 0000000000..d9fb637d2d
--- /dev/null
+++ b/.changeset/clever-buttons-push.md
@@ -0,0 +1,12 @@
+---
+'@tanstack/router-cli': minor
+'@tanstack/router-plugin': minor
+'@tanstack/router-vite-plugin': minor
+'@tanstack/start-plugin-core': minor
+'@tanstack/react-start': minor
+'@tanstack/solid-start': minor
+'@tanstack/vue-start': minor
+'@tanstack/react-start-rsc': minor
+---
+
+Require Node.js 22.22.0 or later for Router and Start build tooling. Upgrade file watching to Chokidar 6.
diff --git a/.changeset/itchy-chairs-melt.md b/.changeset/itchy-chairs-melt.md
new file mode 100644
index 0000000000..2ea0e1e902
--- /dev/null
+++ b/.changeset/itchy-chairs-melt.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/router-plugin': patch
+---
+
+Preserve JSX and TypeScript syntax when splitting route components wrapped in calls such as React `memo` and Vue `defineComponent`.
diff --git a/.changeset/route-modules-devtools.md b/.changeset/route-modules-devtools.md
new file mode 100644
index 0000000000..e60fb2c888
--- /dev/null
+++ b/.changeset/route-modules-devtools.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/router-devtools-core': minor
+---
+
+Experimental: The router devtools show route modules. Each mounted module's routes form a collapsible group, nested where the module is mounted, and a filter narrows the route tree to one module. A module panel shows the module's mount path, parent module, routes with their module-local and final paths, and active matches. Matches carry a module badge, and match details show the module, the local path and the final path.
diff --git a/.changeset/route-modules-eslint.md b/.changeset/route-modules-eslint.md
new file mode 100644
index 0000000000..14f07932fc
--- /dev/null
+++ b/.changeset/route-modules-eslint.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/eslint-plugin-router': minor
+---
+
+Experimental: Add the `route-module-imports` rule, enabled in the recommended configs: files of a route module must import routing and Start APIs from the module's generated route scope. The rule only applies to packages that declare `tanstack.router.module`.
diff --git a/.changeset/route-modules-generator.md b/.changeset/route-modules-generator.md
new file mode 100644
index 0000000000..08d84ef3bb
--- /dev/null
+++ b/.changeset/route-modules-generator.md
@@ -0,0 +1,7 @@
+---
+'@tanstack/router-generator': minor
+'@tanstack/router-cli': minor
+'@tanstack/router-plugin': minor
+---
+
+Experimental: Generate route modules. A package that declares `tanstack.router.module` in its `package.json` gets qualified route ids (`:`), a generated route scope (`routeScope.gen.ts`, with one namespace file per included or used module), a public contract (`routeContract.gen.ts`, exported as `./route-types` after the package's own declaration build), a runtime entry (`routeModule.gen.ts`, exported as `./route-module`) and a topology manifest (`.tanstack/route-module.json`) for includers. Module identity is the package name. Applications and modules mount modules with the `routeModules` option: `includes` chooses the host route and mount path of each module and `uses` references modules mounted elsewhere. An application installs a module several times by including it once per installation, each named with `as`; every installation gets its own namespace and route ids, and a module that uses it links to the installation mounted above it. A module mounted under path params gets a namespace typed with them in its includers; the generator rejects a module that uses it without being mounted below those params, and rejects mounts whose full paths collide. `tsr generate` emits the module files. Packages emit and check declarations with their own TypeScript projects; Nx or similar workspace tooling reruns generation and compilation in dependency order when sources, configuration or provider artifacts change. `tsr watch` retains its standalone route-directory and configuration watching. The bundler plugin compiles, code-splits and hot-updates mounted module routes, including every installation of a module installed several times. Applications without route modules generate the same output as before.
diff --git a/.changeset/route-modules-router.md b/.changeset/route-modules-router.md
new file mode 100644
index 0000000000..b8f42ebc86
--- /dev/null
+++ b/.changeset/route-modules-router.md
@@ -0,0 +1,8 @@
+---
+'@tanstack/router-core': minor
+'@tanstack/react-router': minor
+'@tanstack/solid-router': minor
+'@tanstack/vue-router': minor
+---
+
+Experimental: Add route modules: workspace packages that own a subtree of file-based routes and are mounted into applications or other modules. The generated host route tree mounts a module root under a host route and type-checks the mount: a static mount path, no required search params above the module, the router context the module requires, and serializable lifecycle results in server-rendered applications. Module routes, links, navigation, redirects and hooks come from the module's generated route scope and take module-local paths and qualified route ids wherever the module is mounted; `getRouteApi` and route-bound hooks resolve the nearest installation. A module mounted under path params keeps the params of the current location in its own links, and `HostedRouter` types the links of code that mounts it. A module installed several times gets one copy of its routes per installation, with ids `#:/…`; module-local ids, destinations, redirects and not-found errors resolve to the installation of the route that uses them, and `InstallationRoutesById` types an installation's routes. Matches of module routes carry `localRouteId`, the installation-independent id, and the generated `isScopedMatch` guard narrows whole-router matches to the routes of a scope. Applications without route modules are unaffected.
diff --git a/.changeset/route-modules-start.md b/.changeset/route-modules-start.md
new file mode 100644
index 0000000000..fea474bcd0
--- /dev/null
+++ b/.changeset/route-modules-start.md
@@ -0,0 +1,9 @@
+---
+'@tanstack/start-client-core': minor
+'@tanstack/start-plugin-core': minor
+'@tanstack/react-start': minor
+'@tanstack/solid-start': minor
+'@tanstack/vue-start': minor
+---
+
+Experimental: Support route modules in TanStack Start. A module that depends on the Start framework package gets `createServerFn`, `createMiddleware` and `createStartModule` in its generated route scope. It declares the context it requires from the application by augmenting `StartModuleRequirements`, keyed by its package name, with `requestContext` and `functionContext`; the declaration emits no JavaScript. A module that contributes serialization adapters or middleware exports a fragment created with `createStartModule` from `start.ts`, and applications install the generated list with `createStart(() => ({ extends: startModules }))`; the application's own entries run first and entries are deduplicated by identity. The generated `startModules.gen.ts` type-checks that the application installs every fragment and provides the required context. The Start plugin lists module routes in the routes manifest, selects the providers' client tree views for client builds, discovers prerenderable module pages and extends import protection to installed module packages.
diff --git a/.changeset/router-core-extensions.md b/.changeset/router-core-extensions.md
new file mode 100644
index 0000000000..eb667c584e
--- /dev/null
+++ b/.changeset/router-core-extensions.md
@@ -0,0 +1,10 @@
+---
+'@tanstack/router-core': minor
+'@tanstack/react-router': minor
+'@tanstack/solid-router': minor
+'@tanstack/vue-router': minor
+'@tanstack/start-client-core': patch
+'@tanstack/react-start-rsc': patch
+---
+
+Declarations emitted by packages that use the router now import router types from the framework package, for example `@tanstack/react-router`, instead of `@tanstack/router-core`, which pnpm does not let those packages resolve unless they depend on it. The framework packages augment the new `@tanstack/router-core/extensions` entry instead of `@tanstack/router-core`, and the router packages export router-core's `Route` interface, which `createFileRoute` returns, as `RouteCore`. Existing augmentations of `@tanstack/router-core` keep working.
diff --git a/.changeset/salty-dryers-move.md b/.changeset/salty-dryers-move.md
new file mode 100644
index 0000000000..d9612eaf47
--- /dev/null
+++ b/.changeset/salty-dryers-move.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/router-generator': patch
+---
+
+Use the package name as the route module's identity. Remove the experimental custom module ID override so generated routes and consumer scopes use the same identity.
diff --git a/.changeset/start-modules-many-fragments.md b/.changeset/start-modules-many-fragments.md
new file mode 100644
index 0000000000..99e34250c2
--- /dev/null
+++ b/.changeset/start-modules-many-fragments.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/start-client-core': patch
+---
+
+Type-check `createStart(() => ({ extends: startModules }))` for applications that install the Start fragments of many route modules. With about 50 fragments, TypeScript reported "Type instantiation is excessively deep and possibly infinite".
diff --git a/.changeset/start-rsbuild-compiler-esm-resolve.md b/.changeset/start-rsbuild-compiler-esm-resolve.md
new file mode 100644
index 0000000000..fe04e03124
--- /dev/null
+++ b/.changeset/start-rsbuild-compiler-esm-resolve.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/start-plugin-core': patch
+---
+
+Rsbuild: the Start compiler resolves the imports it follows, such as those of a module that re-exports `createServerFn`, as ES module imports. It used the loader's base resolver, so packages whose exports only list `import`, like `@tanstack/react-start`, failed to resolve and the build stopped.
diff --git a/.changeset/true-houses-behave.md b/.changeset/true-houses-behave.md
new file mode 100644
index 0000000000..722483ca4d
--- /dev/null
+++ b/.changeset/true-houses-behave.md
@@ -0,0 +1,16 @@
+---
+'@tanstack/router-core': patch
+'@tanstack/react-router': patch
+'@tanstack/solid-router': patch
+'@tanstack/vue-router': patch
+'@tanstack/router-devtools-core': patch
+'@tanstack/router-cli': patch
+'@tanstack/router-generator': patch
+'@tanstack/start-client-core': patch
+'@tanstack/start-plugin-core': patch
+'@tanstack/react-start': patch
+'@tanstack/solid-start': patch
+'@tanstack/vue-start': patch
+---
+
+Correct experimental route-module installation identity, scope ownership, framework navigation parity, and Start context validation. Generate independently tree-shakeable scope APIs and explicit dependency namespaces, and keep module composition helpers internal. Use ordinary TypeScript declaration builds, refresh route topology during development, and include provider routes in Start client pruning and prerender discovery.
diff --git a/benchmarks/client-nav/link-performance/cases.ts b/benchmarks/client-nav/link-performance/cases.ts
index a25eac563b..9203d3ff35 100644
--- a/benchmarks/client-nav/link-performance/cases.ts
+++ b/benchmarks/client-nav/link-performance/cases.ts
@@ -25,6 +25,12 @@ export const LINK_CASES = [
label: 'Relative targets',
description: 'Parent and child targets inherit current params and search.',
},
+ {
+ id: 'route-bound',
+ label: 'Route-bound relative targets',
+ description:
+ 'The relative case through Route.Link, which resolves from its route.',
+ },
{
id: 'middleware',
label: 'Search middleware chain',
@@ -103,6 +109,7 @@ export function sourceSearch(
switch (caseId) {
case 'location-updaters':
case 'relative':
+ case 'route-bound':
case 'middleware':
case 'active':
return {
@@ -157,6 +164,7 @@ function url(pathname: string, search: Partial = {}, hash = '') {
function sourcePath(caseId: LinkCaseId, stateIndex: number) {
switch (caseId) {
case 'relative':
+ case 'route-bound':
return `/teams/team-${stateIndex}/item-${stateIndex}`
case 'numeric-params':
return `/numbers/${stateIndex}`
@@ -210,6 +218,7 @@ function expectedHref(caseId: LinkCaseId, stateIndex: number, index: number) {
`source-${stateIndex}-link-${index % 5}`,
)
case 'relative':
+ case 'route-bound':
return url(
index % 2 === 0
? `/teams/team-${stateIndex}`
diff --git a/benchmarks/client-nav/link-performance/src/workload.tsx b/benchmarks/client-nav/link-performance/src/workload.tsx
index 8315b85b8b..62107e525c 100644
--- a/benchmarks/client-nav/link-performance/src/workload.tsx
+++ b/benchmarks/client-nav/link-performance/src/workload.tsx
@@ -238,6 +238,7 @@ function sourceOptions(caseId: LinkCaseId, stateIndex: number) {
}
switch (caseId) {
case 'relative':
+ case 'route-bound':
return linkOptions({
...common,
to: '/teams/$teamId/$itemId',
@@ -386,6 +387,15 @@ function measuredLink(
search
/>
)
+ case 'route-bound':
+ return (
+
+ )
case 'middleware':
return (
[!WARNING]
+> This rule supports [route modules](../routing/route-modules.md), which are experimental. The rule may change with them in any release.
+
+Files of a [route module](../routing/route-modules.md) must import routing and Start APIs from the module's generated route scope (`routeScope.gen.ts`), which types them against the module's own routes. The same APIs imported from `@tanstack/react-router`, `@tanstack/solid-router`, `@tanstack/vue-router` or the framework's Start package are typed against an application the module does not know.
+
+The rule reports value imports of these APIs from the framework packages:
+
+- Route constructors and routing APIs: `createFileRoute`, `Link`, `createLink`, `linkOptions`, `Navigate`, `useNavigate`, `redirect`, `MatchRoute`, `useMatchRoute`, `useRouter`, `getRouteApi`, `useMatch`, `useMatches`, `useParentMatches`, `useChildMatches`, `useLoaderData`, `useLoaderDeps`, `useSearch`, `useParams`, `useRouteContext`, `useLocation` and `useRouterState`.
+- Root route constructors (`createRootRoute`, `createRootRouteWithContext`): a module root is created with `createModuleRoot`.
+- Start APIs of Start route modules: `createServerFn` and `createStartModule`.
+
+The rule only applies to files whose nearest `package.json` declares `tanstack.router.module`. It ignores generated files and type-only imports.
+
+## Rule Details
+
+Examples of **incorrect** code for this rule:
+
+```tsx title="packages/products/src/routes/$productId.tsx"
+/* eslint "@tanstack/router/route-module-imports": "error" */
+import { createFileRoute, Link } from '@tanstack/react-router'
+
+export const Route = createFileRoute('@acme/products:/$productId')({
+ component: () => All products,
+})
+```
+
+Examples of **correct** code for this rule:
+
+```tsx title="packages/products/src/routes/$productId.tsx"
+/* eslint "@tanstack/router/route-module-imports": "error" */
+import { Outlet } from '@tanstack/react-router'
+import { createFileRoute, Link } from '../routeScope.gen'
+
+export const Route = createFileRoute('@acme/products:/$productId')({
+ component: () => All products,
+})
+```
+
+## Attributes
+
+- [x] ✅ Recommended
+- [ ] 🔧 Fixable
diff --git a/docs/router/routing/route-modules.md b/docs/router/routing/route-modules.md
new file mode 100644
index 0000000000..a510731b55
--- /dev/null
+++ b/docs/router/routing/route-modules.md
@@ -0,0 +1,445 @@
+---
+id: route-modules
+title: Route Modules (Experimental)
+---
+
+> [!WARNING]
+> Route modules are experimental. Their APIs, generated files, `package.json` fields, CLI commands and TanStack Start integration may change in any release, including minor and patch releases. Pin your TanStack Router versions when you adopt them.
+
+A **route module** is a workspace package that owns a subtree of file-based routes. Applications, and other route modules, mount it into their route tree. Each module is generated and type-checked by its own package, and links into it stay fully typed wherever it is mounted.
+
+Use route modules when several teams or applications share routes in a monorepo:
+
+- A feature (a product catalog, an account area) lives in its own package with its own routes, loaders and components.
+- Applications choose where a module is mounted, so the same module can appear at `/shop/products` in one app and at `/catalog` in another.
+- A module only sees what it declares: its own routes, the modules it mounts or uses, and the router context it requires.
+
+Route modules are opt-in. Applications without them are generated exactly as before.
+
+> [!NOTE]
+> Route modules require TypeScript, and the generator rejects `disableTypes`. Lazy route files (`createLazyFileRoute`, `.lazy.tsx`) are not supported in route modules: [automatic code splitting](../guide/automatic-code-splitting.md) splits module routes like any other route.
+
+## Declaring a route module
+
+A package is a route module when its `package.json` has a `tanstack.router.module` field:
+
+```json title="packages/products/package.json"
+{
+ "name": "@acme/products",
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": {}
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "build:types": "node -e \"require('node:fs').rmSync('.tanstack/types', { recursive: true, force: true })\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "^1.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "^1.0.0",
+ "typescript": "^5.6.0"
+ }
+}
+```
+
+The module's identity is its `package.json` name. Generated route IDs use that
+name as their prefix, for example `@acme/products:/$productId`.
+
+The module field accepts these options. `true` is the same as `{}`.
+
+| Option | Description |
+| ---------- | -------------------------------------------------------------------------- |
+| `includes` | Modules installed into this module's tree, with includer-owned mount paths |
+| `uses` | Explicit references to other modules' routes; defaults to an empty list |
+
+The two `exports` entries are the module's public surface:
+
+- `./route-types` points to the emitted declarations of the module's contract: its router type and route ids. Consumers only read these declarations, never the module's sources.
+- `./route-module` points to the module's runtime entry, which includers mount. Applications compile it from source like any other workspace code.
+
+Route ids and module-local paths are part of this public surface. Consumers reference them in `getRouteApi`, `useMatch`, namespaced links and `isScopedMatch`, so renaming or moving a route file is a breaking change for them, like renaming an export.
+
+The package build must verify that its exported declarations and their imports resolve in consumers. Build and check declarations before publishing, including a consumer with `skipLibCheck: false` and no provider source files.
+
+Declarations are emitted with a `tsconfig.route-types.json` that you own:
+
+```json title="packages/products/tsconfig.route-types.json"
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
+```
+
+## Authoring module routes
+
+Module routes live in the module's routes directory as usual. Two things differ from an application:
+
+1. **Import routing APIs from the generated scope.** `src/routeScope.gen.ts` exports `createFileRoute`, `createModuleRoot`, `Link`, `useNavigate`, `redirect`, the hooks and `useRouter`, all typed against the module's own routes. Imports from `@tanstack/react-router` would be typed against an application the module does not know. The [`route-module-imports`](../eslint/route-module-imports.md) lint rule enforces this.
+2. **Route ids are qualified with the module id.** The generator writes them, exactly as it writes ids in an application.
+
+```tsx title="packages/products/src/routes/$productId.tsx"
+import { createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@acme/products:/$productId')({
+ loader: ({ params, context }) =>
+ context.productsApi.getProduct(params.productId),
+ component: ProductPage,
+})
+
+function ProductPage() {
+ const product = Route.useLoaderData()
+ return (
+
+ {product.name}
+ {/* Module-local path: resolves to wherever the module is mounted. */}
+ All products
+
+ )
+}
+```
+
+Paths inside a module are **module-local**. `to="/"` is the module's index route, whether the module is mounted at `/products` or `/shop/catalog`.
+
+### The module root and its requirements
+
+`src/routes/__root.tsx` creates the module root with `createModuleRoot`. Its type parameter is the router context the module requires from wherever it is mounted:
+
+```tsx title="packages/products/src/routes/__root.tsx"
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+import type { ProductsApi } from '../api'
+
+export const Route = createModuleRoot<{ productsApi: ProductsApi }>()({
+ component: () => ,
+})
+```
+
+The module type-checks on its own against this requirement. When an application mounts the module, the mount fails to type-check unless the parent route provides that context. It does not matter whether the context comes from the application's root, `createRouter({ context })`, or a layout's `beforeLoad`.
+
+Shared libraries with nominal types, such as a `QueryClient` class, must resolve to one declaration in the whole workspace. Make them `peerDependencies` of route modules.
+
+## Mounting modules
+
+An application mounts modules with the `routeModules` option. It is accepted by `tsr.config.json`, the bundler plugin and the `router` option of TanStack Start:
+
+```json title="apps/web/tsr.config.json"
+{
+ "routesDirectory": "./src/routes",
+ "generatedRouteTree": "./src/routeTree.gen.ts",
+ "routeModules": {
+ "includes": [
+ { "module": "@acme/storefront", "at": "/shop" },
+ {
+ "module": "@acme/account",
+ "parent": "/_authenticated",
+ "at": "/account"
+ }
+ ]
+ }
+}
+```
+
+A route module mounts other modules with `includes` in its own `package.json`. A string entry mounts the module under the root without adding a path segment. Use an object to select the mount and installation name:
+
+| Field | Description |
+| -------- | ------------------------------------------------------------------------------ |
+| `module` | Package name of the module, declared as a dependency of the includer |
+| `parent` | Host route ID; defaults to the root |
+| `at` | Static path below the parent; defaults to no additional segment |
+| `as` | Generated namespace and installation name, including for a single installation |
+
+The includer owns the URL. Relative and leading-slash `at` spellings are normalized as paths below the selected parent before collision checks.
+
+Mounting follows these rules, and the generator or the type checker reports every violation:
+
+- **The host chain has no required search params.** Links carry the path params of the current location over, but not its search params, so a module's own links could not provide them. Routes above a module may have path params (see [Mounting under path params](#mounting-under-path-params)). `at` itself must be a static path.
+- **The parent provides the context the module root requires.**
+- **A module is mounted once per route tree,** unless an application names several installations of it (see [Installing a module several times](#installing-a-module-several-times)). Several includers can depend on the same module, but only one of them can mount it. The others use it.
+- **Each package declares its direct providers.** Declare the modules it mounts or uses as dependencies. Generated declarations reference those providers' symbolic contracts; each provider resolves its own dependencies from its package. An application need not list every transitive module as a direct dependency. The package declaration build reports unresolved imports.
+- **Full paths must not collide** with routes of the includer or other modules.
+
+Generated code performs the mounting and emits the corresponding type checks. Mounting helpers are internal; author composition through configuration and generated APIs.
+
+### Mounting under path params
+
+A module can be mounted below routes with path params, for example once per organization:
+
+```json title="apps/web/tsr.config.json"
+{
+ "routeModules": {
+ "includes": [
+ { "module": "@acme/team", "parent": "/orgs/$orgId", "at": "/team" }
+ ]
+ }
+}
+```
+
+The module never sees `orgId` in its types: its own links keep the path params of the current location, which always has them while the module renders. At runtime `useParams()` and `match.params` contain them, like the final paths in `match.fullPath`. Whatever an installation needs about its host comes through the context its root requires, which the host route provides:
+
+```tsx title="apps/web/src/routes/orgs.$orgId.tsx"
+export const Route = createFileRoute('/orgs/$orgId')({
+ beforeLoad: ({ params }) => ({ org: { id: params.orgId } }),
+})
+```
+
+The includer's namespace for the module is typed from where it is mounted, so links from outside the module pass the host params:
+
+```tsx
+
+ Ada
+
+```
+
+A module that only uses a module mounted under path params fills them from the current location, so the generator requires it to be mounted below the routes that declare them. It reports a using module mounted elsewhere, naming both modules and the routes with the params.
+
+### Installing a module several times
+
+An application can install a module more than once, for example the same settings per organization and per person. Every include of the module names its installation with `as`:
+
+```json title="apps/web/tsr.config.json"
+{
+ "routeModules": {
+ "includes": [
+ {
+ "module": "@acme/settings",
+ "parent": "/orgs/$orgId",
+ "at": "/settings",
+ "as": "orgSettings"
+ },
+ {
+ "module": "@acme/settings",
+ "parent": "/people/$personId",
+ "at": "/settings",
+ "as": "personSettings"
+ }
+ ]
+ }
+}
+```
+
+Each installation gets its own routes, with ids `#:` such as `@acme/settings#orgSettings:/profile`. They share the module's components, loaders and code-split chunks, and a hot update reaches every installation. An explicitly named single installation uses this identity too. Only an unnamed single installation uses `:`, so adding another installation does not rename an existing named one.
+
+The module's code does not change. Its route ids, `Route` APIs, links, navigation and redirects resolve to the installation it renders under. Configure each installation through the context the module root requires: each host route provides its own.
+
+Outside the module, address one installation at a time:
+
+- **Through its namespace.** The application gets a namespace per installation, named by `as`. It takes the module's local paths and ids and addresses that installation: `orgSettings.Link`, `orgSettings.getRouteApi('@acme/settings:/profile')`.
+- **By its installation ids.** `useMatch({ from: '@acme/settings#orgSettings:/profile' })`. The module's plain ids (`@acme/settings:/profile`) are type errors outside the module.
+
+A module that uses a module installed several times links to the installation whose host routes are above its own mount: a billing module mounted below `/orgs/$orgId` links to `orgSettings`. The generator reports a using module with no such installation, or with several.
+
+Only applications install a module several times. A module installed several times cannot itself install other modules.
+
+## Linking across modules
+
+Every module the includer mounts or uses gets a **namespace** in its `routeScope.gen.ts`. A namespace has the same APIs as the module's own scope, typed against that module's local paths:
+
+```tsx title="apps/web/src/routes/index.tsx"
+import { createFileRoute } from '@tanstack/react-router'
+import { products } from '../routeScope.gen'
+
+export const Route = createFileRoute('/')({
+ component: () => (
+
+ Pick of the day
+
+ ),
+})
+```
+
+The namespace name is the last segment of the package name in camel case. Choose another with `as` when two modules would get the same name.
+
+In `includes`, `as` also names the installation. In a `uses` reference, `{ "module": "@acme/products", "as": "catalog" }` only renames the local namespace; it does not create or rename an installation.
+
+An application cannot link to a module route by its final path: ` ` is a type error. This keeps modules independent of where they are mounted.
+
+APIs that take a route id work across modules with qualified ids:
+
+```tsx
+const productApi = getRouteApi('@acme/products:/$productId')
+const match = useMatch({ from: '@acme/products:/$productId' })
+```
+
+A module can reference another module's routes without mounting it by listing it in `uses`:
+
+```json title="packages/account/package.json"
+{
+ "name": "@acme/account",
+ "tanstack": {
+ "router": {
+ "module": { "uses": ["@acme/products"] }
+ }
+ },
+ "dependencies": { "@acme/products": "workspace:*" }
+}
+```
+
+The application must install that provider somewhere, directly or through an include. The generator reports a reference whose provider is not installed. A dependency used only for schemas, utilities or server functions needs no `uses` entry and imposes no route-installation requirement. Dependencies are resolved as packages; they are not automatically discovered as route consumers. An include already exposes its installed subtree, so it need not be repeated in `uses`.
+
+Namespaces are read-only generated ESM namespaces. Each API and namespace can be tree-shaken independently: using `products.Link` should not retain every routing helper. Do not mutate namespace members.
+
+Options created by a scope retain their ownership. Reuse `products.linkOptions(...)` with the products APIs; passing them to a conflicting scope is rejected instead of silently changing their destination.
+
+### Match identity and whole-router state
+
+`match.routeId` is the final installed ID. Module matches also carry `match.localRouteId`, for example `@acme/settings:/profile` even when the final ID is `@acme/settings#orgSettings:/profile`. Ordinary application matches omit this property.
+
+Scoped `useMatches` keeps the whole active match chain, including foreign host routes. Those foreign matches retain common metadata, but their loader data and context are `unknown`. Narrow membership before using module-specific data. `isScopedMatch` accepts every route of the modules in the scope, identified by their module id, including routes a module adds later:
+
+```ts
+import { isScopedMatch, useMatches } from '../routeScope.gen'
+
+for (const match of useMatches()) {
+ if (
+ isScopedMatch(match) &&
+ match.localRouteId === '@acme/settings:/profile'
+ ) {
+ const profile = match.loaderData
+ }
+}
+```
+
+Known-route APIs such as `useMatch({ from: ... })` retain precise types. Constructing `getRouteApi(...)` at module scope is valid; its hooks resolve the nearest installation when called in a component. An ambiguous lookup outside a matching context needs an explicit installation.
+
+The generated scope also includes `useLinkProps`, `useBlocker` and targeted `notFound`. `useBlocker` observes whole-router transitions. Import `Outlet` from the framework package. `Navigate` navigates on mount and on option changes across React, Solid and Vue; it does not navigate during SSR.
+
+Generated validation type aliases bind the module's router while retaining the corresponding framework type's other argument order and defaults:
+
+- `ValidateLinkOptions` and `ValidateLinkOptionsArray`
+- `ValidateNavigateOptions` and `ValidateNavigateOptionsArray`
+- `ValidateRedirectOptions` and `ValidateRedirectOptionsArray`
+- `ValidateUseSearchOptions` and `ValidateUseParamsOptions`
+- `ValidateId`, `ValidateFromPath`, `ValidateToPath`, `ValidateSearch` and `ValidateParams`
+
+> [!NOTE]
+> A module match's `fullPath` is the final installed path pattern and is typed as `string`; the paths accepted by its generated APIs are module-local. Read `match.pathname` for the current concrete URL. Module source route objects are shared definitions, so use the current match when you need an installation's identity or path.
+
+## Generated files
+
+| File | Purpose |
+| ------------------------------------ | ---------------------------------------------------------------------------- |
+| `src/routeTree.gen.ts` | Full route tree and type maps |
+| `src/routeTree.gen.client.ts` | Provider-owned client view used by Start's client bundlers |
+| `src/routeScope.gen.ts` | Module-scoped exports and namespace re-exports |
+| `src/routeScope.gen.namespace.ts` | Independent ESM exports for a referenced installation |
+| `src/routeContract.gen.ts` | Public route contract, exposed as `./route-types` after declaration emission |
+| `src/routeModule.gen.ts` | Runtime entry exposed as `./route-module` |
+| `src/startModules.gen.ts` | Start contributions and erased application contract checks |
+| `.tanstack/route-module.json` | Portable route/source topology, installation metadata and client-view paths |
+| `.tanstack/types/` | Example declaration output directory, owned by the package build |
+
+The generated files sit beside the configured route tree. Do not edit them. They can be committed or ignored; generation must precede any task that reads them. Add `.tanstack` to `.gitignore`.
+
+Package runtime exports must retain every referenced route source or compiled JavaScript file, generated namespace/client-tree file and topology manifest. Declaration exports must retain their complete reachable declaration graph. Keep framework versions compatible with the generated source's internal implementation imports.
+
+## Building and watching
+
+Router generates routes; the package's TypeScript build emits and checks declarations; a task runner schedules, caches and reruns those operations when inputs change.
+
+| Command | Responsibility |
+| ---------------------------------- | --------------------------------------------------------------- |
+| `tsr generate` | Generate the package's route topology, source APIs and manifest |
+| `tsc -p tsconfig.route-types.json` | Emit declarations with the package's own compiler project |
+| `tsc --noEmit` | Check a package's sources against current provider declarations |
+
+A declaration build should clean its configured output first, because TypeScript does not remove declarations for deleted source files. The example `build:types` script above owns that cleanup. A failed build must fail the task graph. Router has no declaration-status file, compiler wrapper or stale-output health check.
+
+Order work by the route-package dependency graph:
+
+1. Generate providers before packages that include or reference them.
+2. Emit provider declarations before emitting or checking consumers.
+3. Regenerate packages that include or reference a provider after its topology changes; recheck consumers after contract changes.
+4. Build the application from the resulting artifacts.
+
+An implementation edit can produce identical declaration bytes. Whether that suppresses a consumer task depends on the task runner's cache policy, not Router.
+
+Router CLI and bundler plugins require Node.js 22.22.0 or later.
+
+### Nx and Turborepo
+
+Expose ordinary `generate`, `build:types` and `check` package scripts. For example, an Nx graph can start with these uncached targets:
+
+```json title="nx.json"
+{
+ "targetDefaults": {
+ "generate": { "cache": false, "dependsOn": ["^generate"] },
+ "build:types": {
+ "cache": false,
+ "dependsOn": ["generate", "^build:types"]
+ },
+ "check": {
+ "cache": false,
+ "dependsOn": ["generate", "^build:types"]
+ }
+ }
+}
+```
+
+The equivalent Turborepo tasks use `dependsOn: ["^generate"]` for generation and `dependsOn: ["generate", "^build:types"]` for declaration builds/checks. Use the task runner's watch mode to rerun these finite tasks in dependency order.
+
+Configure that workflow to react to route source and generation-config changes, module `package.json` metadata, and Start-entry additions or removals beside the configured route tree. A provider topology change must regenerate packages that include or reference it. Provider declaration changes must rebuild or recheck their consumers. Include custom generated directories and TypeScript project inputs in the task configuration.
+
+`tsr watch` remains available for standalone route-directory and configuration watching. Route-module development uses the workspace task runner to watch the complete build graph and invoke `tsr generate`.
+
+When enabling caches, model every source/configuration and provider artifact a task reads. Restore every generated scope/namespace/client-tree file, the topology manifest, the complete declaration output/maps and the intended runtime output. Match custom generation directories and declaration `outDir` settings. A task whose inputs include ignored generated workloads must model those inputs or remain uncached. Cache hits must restore the same usable package as a successful uncached run.
+
+The application bundler compiles module runtime source and handles code splitting/HMR. It also consumes provider manifests; it does not generate into provider packages. Run the workspace task watcher alongside the application dev server so provider artifacts stay current.
+
+## TanStack Start
+
+Route modules work in TanStack Start applications. A module can declare type-only Start context requirements and can separately contribute an executable **Start fragment** that the application installs. See [Route Modules in TanStack Start](../../start/framework/react/guide/route-modules.md).
+
+A module without Start features can be mounted in a Start application as is. When the application renders on the server, the mount checks that the loader and `beforeLoad` results of the module's routes can be serialized.
+
+## Migrating from a router package
+
+The `router-monorepo-*` examples share one router between packages: a router package builds the route tree from routes defined in feature packages and registers it globally. To move a feature package to a route module:
+
+1. Move its routes into `src/routes` of the package and add `tanstack.router.module` and the `exports` entries to its `package.json`.
+2. Replace route constructors and routing APIs imported from the framework package with imports from `./routeScope.gen`. Create the root with `createModuleRoot` and declare the context the routes need.
+3. Replace absolute paths that pointed into other features, in the features and in the application, with their namespaces. The type checker reports each one:
+
+ ```tsx
+ // Before
+
+ // After
+
+ ```
+
+4. Mount the module from the application with `routeModules.includes`, and remove the hand-written route tree assembly and the shared `Register` augmentation.
+5. Declare cross-module route references in `uses`. Add generation, ordinary declaration-build and source-check tasks in dependency order.
+
+## Limitations
+
+- Route modules require TypeScript and emit declarations with the module's own compiler. TypeScript 5.6 or newer is supported.
+- Consumer declarations use `moduleResolution: "bundler"`. `node16`/`nodenext` compatibility is not supported by this workflow.
+- A module is mounted at a static path, under a host chain without required search params. Only applications install a module more than once, and a module installed several times cannot install other modules.
+- A module that another module installs cannot link to a module the application installs several times.
+- Lazy route files are not supported in route modules.
+- `Register.server.requestContext` of TanStack Start stays global to the application.
+- Mixed code-based and file-based route-module composition is a future TODO. Use generated file-based composition for now; the mounting and scope factories remain internal. Existing physical/virtual file-routing configuration remains supported.
+- Router instances own their runtime state, including request-specific SSR state; shared module definitions must not store user context.
diff --git a/docs/start/config.json b/docs/start/config.json
index 36af0e6e0d..df475b821d 100644
--- a/docs/start/config.json
+++ b/docs/start/config.json
@@ -90,6 +90,10 @@
"label": "Import Protection",
"to": "framework/react/guide/import-protection"
},
+ {
+ "label": "Route Modules (Experimental)",
+ "to": "framework/react/guide/route-modules"
+ },
{
"label": "Path Aliases",
"to": "framework/react/guide/path-aliases"
diff --git a/docs/start/framework/react/guide/route-modules.md b/docs/start/framework/react/guide/route-modules.md
new file mode 100644
index 0000000000..fd953445ab
--- /dev/null
+++ b/docs/start/framework/react/guide/route-modules.md
@@ -0,0 +1,196 @@
+---
+id: route-modules
+title: Route Modules (Experimental)
+---
+
+Start build tooling requires Node.js 22.22.0 or later.
+
+> [!WARNING]
+> Route modules are experimental. Their APIs, generated files and build integration may change in any release, including minor and patch releases. Pin your TanStack Start versions when you adopt them.
+
+[Route modules](../../../../router/routing/route-modules.md) are packages that own a subtree of file-based routes. A module that depends on `@tanstack/react-start` also receives generated Start APIs. The same design applies to Solid and Vue through their framework packages.
+
+```json title="packages/catalog/package.json"
+{
+ "name": "@acme/catalog",
+ "tanstack": { "router": { "module": {} } },
+ "dependencies": {
+ "@tanstack/react-router": "^1.0.0",
+ "@tanstack/react-start": "^1.0.0"
+ }
+}
+```
+
+Use `createServerFn`, `createMiddleware` and `createStartModule` from the module's generated `routeScope.gen.ts`. These APIs select the module's requirements and serialization types. The application continues to import its APIs from `@tanstack/react-start`.
+
+## Declare required context with types
+
+Requirements describe context that the host must provide. Augment `StartModuleRequirements` in the framework package, keyed by the module's package name:
+
+```ts title="packages/catalog/src/requirements.ts"
+export type { StartModuleRequirements } from '@tanstack/react-start'
+
+interface User {
+ id: string
+}
+
+declare module '@tanstack/react-start' {
+ interface StartModuleRequirements {
+ '@acme/catalog': {
+ requestContext: { user: User }
+ functionContext: { permissions: Array }
+ }
+ }
+}
+```
+
+The two fields are optional and independent:
+
+- `requestContext` is available during requests and server functions. The application can supply it through `handler.fetch` context or request middleware.
+- `functionContext` is required by server functions and their server middleware. Global function middleware can provide it, in addition to the request context already available at that stage. It does not describe client middleware or context sent over the transport.
+
+The generated application assertion selects installed route modules. An application's unrelated dependency does not impose a requirement merely because TypeScript loads its types. Installing a module more than once reuses its package's requirement. Explicitly consuming module middleware also checks its requirements at that consumer.
+
+These declarations emit no JavaScript and need no runtime marker, middleware entry or empty Start fragment. They are separate from `Register.server.requestContext`, which describes context supplied by the host.
+
+### Preserve requirements in published declarations
+
+Consumers must reach the augmentation through the package's declaration exports. Keep it in a `.ts` source file, preserve the framework registry re-export above, and add a type-only re-export to the module's root route:
+
+```tsx title="packages/catalog/src/routes/__root.tsx"
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+export type {} from '../requirements'
+
+export const Route = createModuleRoot()({
+ component: () => ,
+})
+```
+
+The emitted route contract reaches the root declaration, which reaches `requirements.d.ts`. Both re-exports are erased from JavaScript. A standalone `.d.ts` that is never referenced by an exported declaration is insufficient; ordinary declaration emission does not copy arbitrary input declaration files. An unused empty type import may also disappear during emission.
+
+Verify the published package from a consumer that has only its declarations, with `skipLibCheck: false`. Requirements can also be authored in a shared package, provided the module's public declaration graph retains the augmentation and its framework registry reference.
+
+## Author middleware and server functions
+
+The generated middleware factory knows the module's requirements without reading the inferred type of its Start fragment:
+
+```ts title="packages/catalog/src/api.ts"
+import { createMiddleware, createServerFn } from './routeScope.gen'
+
+const pricing = createMiddleware({ type: 'function' }).server(
+ ({ context, next }) =>
+ next({
+ context: {
+ currency: context.permissions.includes('europe') ? 'EUR' : 'USD',
+ },
+ }),
+)
+
+export const getProduct = createServerFn()
+ .middleware([pricing])
+ .validator((id: string) => id)
+ .handler(({ data, context }) => ({
+ id: data,
+ shopper: context.user.id,
+ currency: context.currency,
+ }))
+```
+
+Middleware attached to a server function runs for that function. This is the appropriate place for feature-specific authorization or pricing logic. Global contributions run for the whole application.
+
+Context validation follows middleware execution order, including nested middleware and replacement of existing context properties. A later incompatible replacement cannot be hidden by an earlier valid provider. The checks also apply when module middleware is consumed from an application or another module. Use concrete compatible context types; an `any` value cannot establish the required contract.
+
+## Contribute application-wide behavior
+
+A Start fragment contains executable contributions: `serializationAdapters`, `requestMiddleware` and `functionMiddleware`. Create one only when the module contributes such behavior. Put it in `start.ts` or `start.tsx` next to the configured generated route tree, and export it as `start`:
+
+```ts title="packages/catalog/src/start.ts"
+import { createStartModule } from './routeScope.gen'
+import { moneyAdapter } from './money'
+
+export const start = createStartModule(() => ({
+ serializationAdapters: [moneyAdapter],
+}))
+```
+
+A fragment cannot set application-wide options such as `defaultSsr` or `serverFns`. Its factory is independent of the application's Start instance. Loader and `beforeLoad` results, as well as server-function results, are checked for serialization with the appropriate adapters.
+
+| Need | Author it with |
+| ---------------------------------------------------------- | ----------------------------------------------------- |
+| Context supplied by the host | `StartModuleRequirements` augmentation |
+| Logic used by particular server functions | Generated `createMiddleware` and `.middleware([...])` |
+| Middleware or adapters installed for the whole application | `createStartModule(() => ({ ... }))` |
+
+Shared authentication normally belongs in the host. Modules can require the resulting user context instead of contributing duplicate authentication middleware. Runtime deduplication recognizes the same middleware or adapter object; two separately created objects still both run.
+
+Run `tsr generate` after adding or removing the fragment file. During development, configure Nx or another workspace task runner to rerun generation and dependent builds/checks for these changes. Include the fragment beside the configured route tree in the task inputs, including when that directory is outside `src`.
+
+## Install modules in an application
+
+Choose mount paths in the application configuration:
+
+```ts title="apps/web/vite.config.ts"
+import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+
+export default defineConfig({
+ plugins: [
+ tanstackStart({
+ router: {
+ routeModules: {
+ includes: [{ module: '@acme/catalog', at: '/shop' }],
+ },
+ },
+ }),
+ ],
+})
+```
+
+For modules with executable fragments, install the generated list in the application's Start instance:
+
+```ts title="apps/web/src/start.ts"
+import { createMiddleware, createStart } from '@tanstack/react-start'
+import { startModules } from './startModules.gen'
+
+const user = createMiddleware().server(({ next }) =>
+ next({ context: { user: { id: 'ada' } } }),
+)
+const permissions = createMiddleware({ type: 'function' }).server(({ next }) =>
+ next({ context: { permissions: ['europe'] } }),
+)
+
+export const startInstance = createStart(() => ({
+ extends: startModules,
+ requestMiddleware: [user],
+ functionMiddleware: [permissions],
+}))
+```
+
+The generated type check validates the requirements of every installed module, including modules without a fragment. A requirements-only module needs no `extends` entry. Executable contributions still need installation through `extends: startModules`.
+
+Validation needs concrete tuples and rejects a required entry or provider that may be absent. It checks request and function lists independently: conditionally supplying the same field through one list or the other may work at runtime but cannot establish the contract. Keep a common provider in an unconditional tuple entry when the requirement depends on that relationship.
+
+Prefer named context properties for module requirements. A `Record` does not establish that a required `user` property exists. Optional properties and index signatures may leave earlier context values untouched. The validator keeps those possibilities; repairing one named property may not prove a broad index contract again.
+
+Application entries run first, followed by contributed entries. Entries are deduplicated by object identity, preserving their first position. If an application explicitly places a contributed middleware earlier in its own list, that is its execution position. Compatible host context providers can satisfy a requirement; they need not come from a particular authentication package. Subsequent middleware must preserve the context promised to each consumer.
+
+Without an application `start.ts`, requirements-only modules are checked against the default Start configuration, including registered `handler.fetch` context. Create an entry exporting `startInstance` when the application needs its own middleware or must install executable fragments. Executable fragments require that entry and `extends: startModules`; mounting them into an application without the framework's Start package is rejected.
+
+## Build and publish modules
+
+Use the [ordinary package build workflow](../../../../router/routing/route-modules.md#building-and-watching): route generation, the package's TypeScript declaration build, and consumer source checks in dependency order. Nx, Turborepo or another task runner owns scheduling, caching and rerunning tasks when sources, package metadata or provider artifacts change. Router does not run TypeScript, publish declaration health records or detect whether a task runner restored stale declarations.
+
+Publish the generated runtime entry, its referenced route sources or compiled JavaScript, the generated client tree views, the topology manifest and the complete reachable declaration output. Include all of them in cached task outputs when caching is enabled. A package build must remove obsolete declaration output and verify its export paths and dependencies.
+
+## Client and server builds
+
+Vite and Rsbuild use the same rules across React, Solid and Vue:
+
+- Module sources participate in normal code splitting, Start compilation and [import protection](./import-protection.md).
+- Client trees remove a route whose only recorded option is `server` when all of its children are also removed. Mixed UI/server routes and ancestors needed by surviving children remain. Server trees preserve the endpoints.
+- Providers generate their own client tree views. The host bundler selects those views for client imports; it does not write files into provider packages or filter routes in the browser.
+- Automatic prerender discovery includes eligible mounted module pages, including nested and named installations. Dynamic installed URLs and handler-only endpoints are excluded. Explicit pages, disabling discovery, filters and basepaths continue to apply.
+
+> [!NOTE]
+> In a module installed several times, loader and `beforeLoad` redirects resolve from the matched route. Redirects returned through a component's `useServerFn` do not yet capture its nearest installation. Return data and navigate with the module's `useNavigate` in that case.
diff --git a/e2e/react-router/route-modules/.gitignore b/e2e/react-router/route-modules/.gitignore
new file mode 100644
index 0000000000..2634249916
--- /dev/null
+++ b/e2e/react-router/route-modules/.gitignore
@@ -0,0 +1,8 @@
+# Generated by the route generator and TypeScript; the tests generate
+# them from a clean copy of the packages.
+**/routeTree.gen.ts
+**/routeScope.gen.ts
+**/routeContract.gen.ts
+**/routeModule.gen.ts
+**/routeScope.gen.*.ts
+**/routeTree.gen.*.ts
diff --git a/e2e/react-router/route-modules/e2e-dev/devtools.spec.ts b/e2e/react-router/route-modules/e2e-dev/devtools.spec.ts
new file mode 100644
index 0000000000..6fb9e0a0ea
--- /dev/null
+++ b/e2e/react-router/route-modules/e2e-dev/devtools.spec.ts
@@ -0,0 +1,46 @@
+import { expect, test } from '@playwright/test'
+
+test('the router devtools group the routes of mounted modules', async ({
+ page,
+}) => {
+ await page.goto('/shop/products/7')
+ await page
+ .getByRole('button', { name: 'Open TanStack Router Devtools' })
+ .click()
+
+ // A module's group sits inside the group of the module that mounts it.
+ const outer = page.getByRole('group', {
+ name: 'Route module @route-modules/storefront',
+ })
+ await expect(outer).toBeVisible()
+ await expect(
+ outer.getByRole('group', { name: 'Route module @route-modules/products' }),
+ ).toBeVisible()
+
+ await page
+ .getByRole('button', {
+ name: 'Open module details for @route-modules/products',
+ })
+ .first()
+ .click()
+ const details = page.getByRole('region', { name: 'Module details' })
+ await expect(details).toContainText('Mount path:/shop/products')
+ await expect(details).toContainText('Parent module:@route-modules/storefront')
+})
+
+test('the router devtools show each installation of a module installed twice', async ({
+ page,
+}) => {
+ await page.goto('/people/ada/settings')
+ await page
+ .getByRole('button', { name: 'Open TanStack Router Devtools' })
+ .click()
+
+ for (const installation of ['orgSettings', 'personSettings']) {
+ await expect(
+ page.getByRole('group', {
+ name: `Route module @route-modules/settings#${installation}`,
+ }),
+ ).toBeVisible()
+ }
+})
diff --git a/e2e/react-router/route-modules/e2e-dev/hmr.spec.ts b/e2e/react-router/route-modules/e2e-dev/hmr.spec.ts
new file mode 100644
index 0000000000..7eacbaaa9e
--- /dev/null
+++ b/e2e/react-router/route-modules/e2e-dev/hmr.spec.ts
@@ -0,0 +1,109 @@
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { expect } from '@playwright/test'
+import { createHmrFileEditor, test } from '@tanstack/router-e2e-utils'
+import { Generator, getConfig } from '@tanstack/router-generator'
+
+const packages = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../packages',
+)
+const products = path.join(packages, 'products')
+
+const editor = createHmrFileEditor({
+ rootDir: products,
+ files: {
+ product: 'src/routes/$productId.tsx',
+ },
+})
+const settingsEditor = createHmrFileEditor({
+ rootDir: path.join(packages, 'settings'),
+ files: {
+ profile: 'src/routes/profile.tsx',
+ },
+})
+
+test.afterEach(async () => {
+ await editor.restoreFiles()
+ await settingsEditor.restoreFiles()
+})
+
+test('editing a module route file hot-updates it in the application', async ({
+ page,
+}) => {
+ await page.goto('/shop/products/7')
+ await expect(page.getByRole('heading')).toHaveText('Product 7')
+ await page.evaluate(() => {
+ ;(window as any).__beforeHmr = true
+ })
+
+ await editor.replaceText(
+ 'product',
+ '{product.name} ',
+ 'Updated {product.name} ',
+ )
+ await expect(page.getByRole('heading')).toHaveText('Updated Product 7')
+ // A hot update, not a reload: page state survives.
+ expect(await page.evaluate(() => (window as any).__beforeHmr)).toBe(true)
+ await expect(page).toHaveURL('/shop/products/7?tab=specs')
+})
+
+test('editing a route of a module installed twice hot-updates every installation', async ({
+ page,
+}) => {
+ await page.goto('/people/ada/settings/profile')
+ await expect(page.getByRole('heading', { name: 'Profile' })).toBeVisible()
+ await page.evaluate(() => {
+ ;(window as any).__beforeHmr = true
+ })
+
+ await settingsEditor.replaceText(
+ 'profile',
+ 'Profile ',
+ 'Updated profile ',
+ )
+ await expect(
+ page.getByRole('heading', { name: 'Updated profile' }),
+ ).toBeVisible()
+
+ // The installation of the organizations runs the updated route too.
+ await page.evaluate(() =>
+ (window as any).__TSR_ROUTER__.navigate({
+ to: '/orgs/acme/settings/profile',
+ }),
+ )
+ await expect(page.getByTestId('profile-kind')).toHaveText('organization')
+ await expect(
+ page.getByRole('heading', { name: 'Updated profile' }),
+ ).toBeVisible()
+ // Hot updates, not reloads: page state survives.
+ expect(await page.evaluate(() => (window as any).__beforeHmr)).toBe(true)
+})
+
+test('a route added to a module is served after the module regenerates', async ({
+ page,
+}) => {
+ const newRoute = path.join(products, 'src/routes/brands.tsx')
+ const { writeFile, rm } = await import('node:fs/promises')
+ await writeFile(
+ newRoute,
+ `import { createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/products:/brands')({
+ component: () => Brands ,
+})
+`,
+ )
+ try {
+ // A workspace task reruns the provider's generation after the edit.
+ const config = getConfig({ disableLogging: true }, products)
+ await new Generator({ config, root: products }).run()
+
+ await page.goto('/shop/products/brands')
+ await expect(page.getByRole('heading')).toHaveText('Brands')
+ } finally {
+ await rm(newRoute)
+ const config = getConfig({ disableLogging: true }, products)
+ await new Generator({ config, root: products }).run()
+ }
+})
diff --git a/e2e/react-router/route-modules/e2e/app.spec.ts b/e2e/react-router/route-modules/e2e/app.spec.ts
new file mode 100644
index 0000000000..51afb3509d
--- /dev/null
+++ b/e2e/react-router/route-modules/e2e/app.spec.ts
@@ -0,0 +1,126 @@
+import { expect, test } from '@playwright/test'
+
+test('the application links into mounted modules by namespace', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await expect(page.getByRole('link', { name: 'Cart' })).toHaveAttribute(
+ 'href',
+ '/shop/cart',
+ )
+ await page.getByRole('link', { name: 'Pick of the day' }).click()
+ await expect(page).toHaveURL('/shop/products/home-pick?tab=specs')
+ await expect(page.getByRole('heading')).toHaveText('Product home-pick')
+})
+
+test('module-local links resolve inside the module', async ({ page }) => {
+ await page.goto('/shop/products/3')
+ await page.getByRole('link', { name: 'All products' }).click()
+ await expect(page).toHaveURL('/shop/products')
+ await expect(page.getByRole('link', { name: 'Product 1' })).toHaveAttribute(
+ 'href',
+ '/shop/products/1',
+ )
+})
+
+test('a module mounted under a layout gets its context and links into other modules', async ({
+ page,
+}) => {
+ await page.goto('/account')
+ await expect(page.getByRole('heading')).toHaveText('u-1')
+ await expect(
+ page.getByRole('link', { name: 'Last viewed product' }),
+ ).toHaveAttribute('href', '/shop/products/last-viewed?tab=reviews')
+
+ await page.getByRole('link', { name: 'Last order' }).click()
+ await expect(page).toHaveURL('/account/orders/1')
+ await page.getByRole('button', { name: 'Ordered product' }).click()
+ await expect(page).toHaveURL('/shop/products/p-1?tab=specs')
+ await expect(page.getByRole('heading')).toHaveText('Product p-1')
+})
+
+test('module routes are code-split from the application bundle', async ({
+ page,
+}) => {
+ const scripts: Array = []
+ page.on('request', (request) => {
+ if (request.resourceType() === 'script') {
+ scripts.push(new URL(request.url()).pathname)
+ }
+ })
+ await page.goto('/')
+ await expect(page.getByRole('link', { name: 'Home' })).toBeVisible()
+ expect(scripts.some((script) => script.includes('_productId'))).toBe(false)
+
+ await page.getByRole('link', { name: 'Pick of the day' }).click()
+ await expect(page.getByRole('heading')).toHaveText('Product home-pick')
+ expect(scripts.some((script) => script.includes('_productId'))).toBe(true)
+})
+
+test('a module mounted under path params links within its organization', async ({
+ page,
+}) => {
+ await page.goto('/')
+ // The application passes the path params above the module.
+ await page.getByRole('link', { name: 'Acme team' }).click()
+ await expect(page).toHaveURL('/orgs/acme/team')
+ await expect(
+ page.getByRole('heading', { name: 'Team of ACME' }),
+ ).toBeVisible()
+
+ // Module-local links keep the path params of the current location.
+ await page.getByRole('link', { name: 'grace' }).click()
+ await expect(page).toHaveURL('/orgs/acme/team/members/grace')
+ await expect(
+ page.getByRole('heading', { name: 'grace at ACME' }),
+ ).toBeVisible()
+ await page.getByRole('link', { name: 'All members' }).click()
+ await expect(page).toHaveURL('/orgs/acme/team')
+})
+
+test('a module that uses a module mounted under path params fills them from the location', async ({
+ page,
+}) => {
+ await page.goto('/orgs/globex/billing')
+ const contact = page.getByRole('link', { name: 'Billing contact' })
+ await expect(contact).toHaveAttribute('href', '/orgs/globex/team/members/ada')
+ await contact.click()
+ await expect(
+ page.getByRole('heading', { name: 'ada at GLOBEX' }),
+ ).toBeVisible()
+})
+
+test('a module installed twice renders each installation with its own owner', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await page.getByRole('link', { name: 'Globex settings' }).click()
+ await expect(page).toHaveURL('/orgs/globex/settings')
+ await expect(
+ page.getByRole('heading', { name: 'Settings of GLOBEX' }),
+ ).toBeVisible()
+ // Module-local links stay in the installation they render under.
+ await page.getByRole('link', { name: 'Profile' }).click()
+ await expect(page).toHaveURL('/orgs/globex/settings/profile')
+ await expect(page.getByTestId('profile-kind')).toHaveText('organization')
+
+ await page.goto('/')
+ await page.getByRole('link', { name: "Ada's profile" }).click()
+ await expect(page).toHaveURL('/people/ada/settings/profile')
+ await expect(
+ page.getByRole('heading', { name: 'Settings of Ada' }),
+ ).toBeVisible()
+ await expect(page.getByTestId('profile-kind')).toHaveText('person')
+ await page.getByRole('link', { name: 'All settings' }).click()
+ await expect(page).toHaveURL('/people/ada/settings')
+})
+
+test('a module that uses a module installed twice links to the installation above it', async ({
+ page,
+}) => {
+ await page.goto('/orgs/globex/billing')
+ const profile = page.getByRole('link', { name: 'Organization profile' })
+ await expect(profile).toHaveAttribute('href', '/orgs/globex/settings/profile')
+ await profile.click()
+ await expect(page.getByTestId('profile-kind')).toHaveText('organization')
+})
diff --git a/e2e/react-router/route-modules/e2e/scope-parity.spec.ts b/e2e/react-router/route-modules/e2e/scope-parity.spec.ts
new file mode 100644
index 0000000000..1e762a0d6c
--- /dev/null
+++ b/e2e/react-router/route-modules/e2e/scope-parity.spec.ts
@@ -0,0 +1,215 @@
+import { expect } from '@playwright/test'
+import { test } from '@tanstack/router-e2e-utils'
+
+for (const base of ['/orgs/globex/settings', '/people/ada/settings']) {
+ test(`RouteApi and custom links resolve ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await expect(
+ page.getByRole('link', { name: 'API members' }),
+ ).toHaveAttribute('href', `${base}/members`)
+ await expect(
+ page.getByRole('link', { name: 'Custom members' }),
+ ).toHaveAttribute('href', `${base}/members`)
+ expect(
+ await page
+ .getByRole('link', { name: 'API members' })
+ .getAttribute('_module'),
+ ).toBeNull()
+ expect(
+ await page
+ .getByRole('link', { name: 'Custom members' })
+ .getAttribute('_module'),
+ ).toBeNull()
+ const hostId = base.split('/')[2]!
+ const hostParams = base.startsWith('/orgs/')
+ ? { orgId: hostId }
+ : base.startsWith('/people/')
+ ? { personId: hostId }
+ : { userId: hostId }
+ await expect(page.getByTestId('runtime-params')).toHaveText(
+ JSON.stringify(hostParams),
+ )
+ await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible()
+ await expect(page.getByText('MEMBERS_MATCH', { exact: true })).toHaveCount(
+ 0,
+ )
+ await page.getByRole('link', { name: 'API members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test(`useLinkProps navigates within the document under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ await expect(
+ page.getByRole('link', { name: 'Custom members' }),
+ ).toBeVisible()
+ const documentRequests: Array = []
+ page.on('request', (request) => {
+ if (
+ request.isNavigationRequest() &&
+ request.frame() === page.mainFrame()
+ ) {
+ documentRequests.push(request.url())
+ }
+ })
+ await page.getByRole('link', { name: 'Custom members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ expect(documentRequests).toEqual([])
+ })
+
+ test(`RouteApi navigation resolves ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await page.getByRole('button', { name: 'Navigate members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test(`Navigate captures installation under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/forward`)
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test.describe(`component notFound under ${base}`, () => {
+ test.use({
+ // React reports the deliberately thrown value before the boundary handles it.
+ whitelistErrors: [
+ /^\{routeId: @route-modules\/settings:, isNotFound: true\}$/,
+ ],
+ })
+ test('reaches the module boundary', async ({ page }) => {
+ await page.goto(`${base}/missing`)
+ await expect(page.getByText('MODULE_NOT_FOUND')).toBeVisible()
+ })
+ })
+ for (const button of ['Route up', 'Explicit from home']) {
+ test(`${button} uses the route origin under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await page.getByRole('button', { name: button, exact: true }).click()
+ await expect(page).toHaveURL(base)
+ await expect(
+ page.getByRole('link', { name: 'Profile', exact: true }),
+ ).toHaveAttribute('href', `${base}/profile`)
+ })
+ }
+
+ test(`scoped router view builds and navigates under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ await expect(page.getByTestId('scoped-href')).toHaveText(`${base}/members`)
+ await page.getByRole('button', { name: 'Router members' }).click()
+ await expect(page).toHaveURL(`${base}/members`)
+ const profile = page.getByRole('link', { name: 'Profile', exact: true })
+ await expect(profile).toHaveAttribute('href', `${base}/profile`)
+ await profile.click()
+ await expect(page).toHaveURL(`${base}/profile`)
+ })
+
+ test(`Route.Link keeps the installation under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ const home = page.getByRole('link', { name: 'Route home', exact: true })
+ await expect(home).toHaveAttribute('href', base)
+ await home.click()
+ await expect(page).toHaveURL(base)
+ await expect(
+ page.getByRole('link', { name: 'Profile', exact: true }),
+ ).toHaveAttribute('href', `${base}/profile`)
+ })
+
+ test(`scoped lifecycle redirects retain the installation under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/legacy`)
+ await expect(page).toHaveURL(`${base}/profile`)
+ await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible()
+ })
+
+ test(`framework imports keep application coordinates inside ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ const host = page.getByRole('link', { name: 'Application host' })
+ await expect(host).toHaveAttribute('href', '/orgs/9')
+ await host.click()
+ await expect(page).toHaveURL('/orgs/9')
+ })
+}
+
+test('a local Link resolves options already wrapped by the same local scope', async ({
+ page,
+}) => {
+ await page.goto('/orgs/7/settings/profile')
+ const members = page.getByRole('link', {
+ name: 'Deferred members',
+ exact: true,
+ })
+ await expect(members).toHaveAttribute('href', '/orgs/7/settings/members')
+ await members.click()
+ await expect(page).toHaveURL('/orgs/7/settings/members')
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+})
+
+test('module observers and router views follow real installation changes', async ({
+ page,
+}) => {
+ await page.goto('/orgs/globex/settings/profile')
+ await expect(page.getByTestId('organization-profile')).toHaveText(
+ '@route-modules/settings#orgSettings:/profile',
+ )
+ await expect(page.getByTestId('scoped-href')).toHaveText(
+ '/orgs/globex/settings/members',
+ )
+ await page.getByRole('link', { name: 'API members' }).click()
+ await expect(page).toHaveURL('/orgs/globex/settings/members')
+ await page.getByRole('link', { name: 'Switch to person' }).click()
+ await expect(page).toHaveURL('/people/ada/settings/profile')
+ await expect(page.getByTestId('organization-profile')).toHaveText('none')
+ await expect(page.getByTestId('scoped-href')).toHaveText(
+ '/people/ada/settings/members',
+ )
+ await page.getByRole('link', { name: 'Switch to organization' }).click()
+ await expect(page).toHaveURL('/orgs/globex/settings/profile')
+ await expect(page.getByRole('link', { name: 'API members' })).toHaveAttribute(
+ 'href',
+ '/orgs/globex/settings/members',
+ )
+ const readObserved = () =>
+ page.evaluate(
+ () =>
+ (
+ window as Window & {
+ observedModuleMatches: Array
+ }
+ ).observedModuleMatches,
+ )
+ await expect
+ .poll(readObserved)
+ .toContain('@route-modules/settings#personSettings:/profile')
+ const observed = await readObserved()
+ expect(observed).toContain('@route-modules/settings#orgSettings:/profile')
+ expect(observed).not.toContain(undefined)
+})
+
+test('singleton scoped redirects and namespaced search input survive generation', async ({
+ page,
+}) => {
+ await page.goto('/shop/products/legacy')
+ await expect(
+ page.getByRole('heading', { name: 'Product 42', exact: true }),
+ ).toBeVisible()
+ expect(new URL(page.url()).pathname).toBe('/shop/products/42')
+ await expect(page.getByText('Dimensions, materials and care.')).toBeVisible()
+
+ await page.goto('/shop')
+ const compare = page.getByRole('link', { name: 'Compare', exact: true })
+ await expect(compare).toHaveAttribute(
+ 'href',
+ '/shop/products/compare?ids=%5B%221%22%2C%222%22%5D',
+ )
+ await compare.click()
+ await expect(page.getByText('Comparing products 1 and 2.')).toBeVisible()
+})
diff --git a/e2e/react-router/route-modules/package.json b/e2e/react-router/route-modules/package.json
new file mode 100644
index 0000000000..926b6a727a
--- /dev/null
+++ b/e2e/react-router/route-modules/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "tanstack-router-e2e-react-route-modules",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "test:e2e": "node scripts/prepare.mjs && pnpm --filter @route-modules/web generate && vitest run && playwright test --project=chromium && playwright test --config playwright.dev.config.ts --project=chromium",
+ "test:types": "node scripts/prepare.mjs && pnpm --filter @route-modules/web generate && pnpm --filter @route-modules/web check:contracts"
+ },
+ "devDependencies": {
+ "@playwright/test": "^1.61.0",
+ "@tanstack/router-e2e-utils": "workspace:^",
+ "@tanstack/router-generator": "workspace:^",
+ "@types/node": "catalog:",
+ "vitest": "catalog:",
+ "vite-plugin-solid": "^2.11.11"
+ },
+ "nx": {
+ "implicitDependencies": [
+ "@tanstack/react-start",
+ "@tanstack/solid-start",
+ "@tanstack/vue-start"
+ ]
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/account/package.json b/e2e/react-router/route-modules/packages/account/package.json
new file mode 100644
index 0000000000..f9e2d889d9
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/account/package.json
@@ -0,0 +1,43 @@
+{
+ "name": "@route-modules/account",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": {
+ "uses": [
+ "@route-modules/products"
+ ]
+ }
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json",
+ "./scope": {
+ "types": "./.tanstack/types/src/routeScope.gen.d.ts",
+ "default": "./src/routeScope.gen.ts"
+ }
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@route-modules/products": "workspace:*",
+ "@tanstack/react-router": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/account/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/account/src/routes/__root.tsx
new file mode 100644
index 0000000000..6941c2546a
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/account/src/routes/__root.tsx
@@ -0,0 +1,25 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+
+// Account pages need the signed-in user, provided by whatever host route the
+// application mounts the module under.
+export const Route = createModuleRoot<{ user: { id: string } }>()({
+ component: AccountRoom,
+})
+
+// The module's region: a room tagged with its package and where it is
+// mounted (with the URL it resolved to when the mount path has params).
+function AccountRoom() {
+ const pathname = Route.useMatch({ select: (match) => match.pathname })
+ return (
+
+
+ @route-modules/account {Route.fullPath}
+ {pathname !== Route.fullPath && (
+ → {pathname}
+ )}
+
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/account/src/routes/index.tsx b/e2e/react-router/route-modules/packages/account/src/routes/index.tsx
new file mode 100644
index 0000000000..bfaa88f9de
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/account/src/routes/index.tsx
@@ -0,0 +1,35 @@
+import { Link, createFileRoute, products } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/account:/')({
+ component: AccountHome,
+})
+
+function AccountHome() {
+ const { user } = Route.useRouteContext()
+ return (
+
+
{user.id}
+
+ Signed in. Your orders and what you looked at last.
+
+
+
+
+ Last order
+
+ Order 1
+
+
+
+ Last viewed product
+
+ Opens its reviews
+
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/account/src/routes/orders.$orderId.tsx b/e2e/react-router/route-modules/packages/account/src/routes/orders.$orderId.tsx
new file mode 100644
index 0000000000..21387d26d0
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/account/src/routes/orders.$orderId.tsx
@@ -0,0 +1,44 @@
+import { createFileRoute, getRouteApi, products } from '../routeScope.gen'
+
+const productRoute = getRouteApi('@route-modules/products:/$productId')
+
+export const Route = createFileRoute('@route-modules/account:/orders/$orderId')(
+ {
+ loader: ({ params }) => ({ orderId: params.orderId, productId: 'p-1' }),
+ component: OrderPage,
+ },
+)
+
+function OrderPage() {
+ const order = Route.useLoaderData()
+ const navigateToProduct = products.useNavigate()
+ return (
+
+
{order.orderId}
+
+ Status
+ Delivered
+ Product
+
+ {order.productId}
+
+
+
+ navigateToProduct({
+ to: '/$productId',
+ params: { productId: order.productId },
+ })
+ }
+ >
+ Ordered product
+
+
+ )
+}
+
+export function useOrderedProduct() {
+ return productRoute.useLoaderData()
+}
diff --git a/e2e/react-router/route-modules/packages/account/tsconfig.json b/e2e/react-router/route-modules/packages/account/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/account/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/account/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/account/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/account/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/billing/package.json b/e2e/react-router/route-modules/packages/billing/package.json
new file mode 100644
index 0000000000..cbba643a5a
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/billing/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "@route-modules/billing",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": {
+ "uses": [
+ "@route-modules/settings",
+ "@route-modules/team"
+ ]
+ }
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@route-modules/settings": "workspace:*",
+ "@route-modules/team": "workspace:*",
+ "@tanstack/react-router": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/billing/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/billing/src/routes/__root.tsx
new file mode 100644
index 0000000000..59673b7586
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/billing/src/routes/__root.tsx
@@ -0,0 +1,23 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+
+export const Route = createModuleRoot()({
+ component: BillingRoom,
+})
+
+// The module's region: a room tagged with its package and where it is
+// mounted (with the URL it resolved to when the mount path has params).
+function BillingRoom() {
+ const pathname = Route.useMatch({ select: (match) => match.pathname })
+ return (
+
+
+ @route-modules/billing {Route.fullPath}
+ {pathname !== Route.fullPath && (
+ → {pathname}
+ )}
+
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/billing/src/routes/index.tsx b/e2e/react-router/route-modules/packages/billing/src/routes/index.tsx
new file mode 100644
index 0000000000..78087ff2c0
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/billing/src/routes/index.tsx
@@ -0,0 +1,29 @@
+import { createFileRoute, settings, team } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/billing:/')({
+ component: Billing,
+})
+
+function Billing() {
+ return (
+
+
Billing
+
+ Plan
+ Team, billed monthly
+ Seats
+ 2
+
+ {/* Billing uses the team without mounting it: the organization comes
+ from the current location, below the same route as the team. */}
+
+
+ Billing contact
+
+ {/* The settings are installed for organizations and for people:
+ billing links to the installation of its own organization. */}
+ Organization profile
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/billing/tsconfig.json b/e2e/react-router/route-modules/packages/billing/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/billing/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/billing/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/billing/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/billing/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/products/package.json b/e2e/react-router/route-modules/packages/products/package.json
new file mode 100644
index 0000000000..61b3b459fb
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/package.json
@@ -0,0 +1,43 @@
+{
+ "name": "@route-modules/products",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./api": {
+ "types": "./.tanstack/types/src/api.d.ts",
+ "default": "./src/api.ts"
+ },
+ "./package.json": "./package.json",
+ "./scope": {
+ "types": "./.tanstack/types/src/routeScope.gen.d.ts",
+ "default": "./src/routeScope.gen.ts"
+ }
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "workspace:^",
+ "react": "^19.0.0",
+ "zod": "^4.4.3"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/products/src/api.ts b/e2e/react-router/route-modules/packages/products/src/api.ts
new file mode 100644
index 0000000000..49b3c720f6
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/api.ts
@@ -0,0 +1,12 @@
+export type Price = number & { readonly __brand: 'Price' }
+
+export interface Product {
+ id: string
+ name: string
+ price: Price
+}
+
+export interface ProductsApi {
+ getProduct: (id: string) => Promise
+ listProducts: () => Promise>
+}
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/$productId.tsx b/e2e/react-router/route-modules/packages/products/src/routes/$productId.tsx
new file mode 100644
index 0000000000..4ee4cbe25b
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/$productId.tsx
@@ -0,0 +1,49 @@
+import { createFileRoute } from '../routeScope.gen'
+import { productSearchSchema } from '../schemas'
+
+export const Route = createFileRoute('@route-modules/products:/$productId')({
+ validateSearch: productSearchSchema,
+ loader: ({ params, context }) =>
+ context.productsApi.getProduct(params.productId),
+ component: ProductPage,
+})
+
+function ProductPage() {
+ const product = Route.useLoaderData()
+ const { tab } = Route.useSearch()
+ return (
+
+ {product.name}
+
+ Price
+ {product.price.toFixed(2)}
+ Product id
+
+ {product.id}
+
+
+
+
+ Specs
+
+
+ Reviews
+
+
+
+ {tab === 'specs'
+ ? 'Dimensions, materials and care.'
+ : 'What customers say about it.'}
+
+ All products
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/products/src/routes/__root.tsx
new file mode 100644
index 0000000000..dae776c4c9
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/__root.tsx
@@ -0,0 +1,24 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+import type { ProductsApi } from '../api'
+
+export const Route = createModuleRoot<{ productsApi: ProductsApi }>()({
+ component: ProductsRoom,
+})
+
+// The module's region: a room tagged with its package and where it is
+// mounted (with the URL it resolved to when the mount path has params).
+function ProductsRoom() {
+ const pathname = Route.useMatch({ select: (match) => match.pathname })
+ return (
+
+
+ @route-modules/products {Route.fullPath}
+ {pathname !== Route.fullPath && (
+ → {pathname}
+ )}
+
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/_layout.tsx b/e2e/react-router/route-modules/packages/products/src/routes/_layout.tsx
new file mode 100644
index 0000000000..2193644739
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/_layout.tsx
@@ -0,0 +1,10 @@
+import { Outlet } from '@tanstack/react-router'
+import { createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/products:/_layout')({
+ component: () => (
+
+
+
+ ),
+})
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/_layout/deals.tsx b/e2e/react-router/route-modules/packages/products/src/routes/_layout/deals.tsx
new file mode 100644
index 0000000000..4b557668c5
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/_layout/deals.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from '../../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/products:/_layout/deals')({
+ component: () => (
+ <>
+ Deals
+
+ Rendered through a pathless layout of the products module.
+
+ >
+ ),
+})
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/catalog.{-$category}.tsx b/e2e/react-router/route-modules/packages/products/src/routes/catalog.{-$category}.tsx
new file mode 100644
index 0000000000..0afa1254c1
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/catalog.{-$category}.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute(
+ '@route-modules/products:/catalog/{-$category}',
+)({
+ component: () => (
+ <>
+ Catalog
+ The category segment of this path is optional.
+ >
+ ),
+})
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/compare.tsx b/e2e/react-router/route-modules/packages/products/src/routes/compare.tsx
new file mode 100644
index 0000000000..9c787a278d
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/compare.tsx
@@ -0,0 +1,17 @@
+import { z } from 'zod'
+import { createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/products:/compare')({
+ validateSearch: z.object({ ids: z.array(z.string()) }),
+ component: Compare,
+})
+
+function Compare() {
+ const { ids } = Route.useSearch()
+ return (
+ <>
+ Compare
+ Comparing products {ids.join(' and ')}.
+ >
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/files.$.tsx b/e2e/react-router/route-modules/packages/products/src/routes/files.$.tsx
new file mode 100644
index 0000000000..aee6d73969
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/files.$.tsx
@@ -0,0 +1,10 @@
+import { createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/products:/files/$')({
+ component: () => (
+ <>
+ Files
+ Every path below files/ lands here.
+ >
+ ),
+})
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/index.tsx b/e2e/react-router/route-modules/packages/products/src/routes/index.tsx
new file mode 100644
index 0000000000..1f7c159a3f
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/index.tsx
@@ -0,0 +1,22 @@
+import { Link, createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/products:/')({
+ loader: ({ context }) => context.productsApi.listProducts(),
+ component: ProductList,
+})
+
+function ProductList() {
+ const products = Route.useLoaderData()
+ return (
+
+ {products.map((product) => (
+
+
+ {product.name}
+
+ {product.price.toFixed(2)}
+
+ ))}
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/products/src/routes/legacy.tsx b/e2e/react-router/route-modules/packages/products/src/routes/legacy.tsx
new file mode 100644
index 0000000000..cb4643dbb0
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/routes/legacy.tsx
@@ -0,0 +1,10 @@
+import { createFileRoute, redirect } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/products:/legacy')({
+ beforeLoad: () => {
+ throw redirect({
+ to: '/$productId',
+ params: { productId: '42' },
+ search: { tab: 'specs' },
+ })
+ },
+})
diff --git a/e2e/react-router/route-modules/packages/products/src/schemas.ts b/e2e/react-router/route-modules/packages/products/src/schemas.ts
new file mode 100644
index 0000000000..9f7276a4fb
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/src/schemas.ts
@@ -0,0 +1,6 @@
+import { z } from 'zod'
+
+/** Search params of the product page: `tab` is optional when navigating. */
+export const productSearchSchema = z.object({
+ tab: z.enum(['specs', 'reviews']).default('specs'),
+})
diff --git a/e2e/react-router/route-modules/packages/products/tsconfig.json b/e2e/react-router/route-modules/packages/products/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/products/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/products/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/products/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/settings/package.json b/e2e/react-router/route-modules/packages/settings/package.json
new file mode 100644
index 0000000000..435fe0a77c
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/package.json
@@ -0,0 +1,38 @@
+{
+ "name": "@route-modules/settings",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json",
+ "./scope": {
+ "types": "./.tanstack/types/src/routeScope.gen.d.ts",
+ "default": "./src/routeScope.gen.ts"
+ }
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/__root.tsx
new file mode 100644
index 0000000000..ec3599af26
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/src/routes/__root.tsx
@@ -0,0 +1,44 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+import type { ComponentType } from 'react'
+
+/** Whose settings an installation shows, provided by its host route. */
+export interface Owner {
+ kind: 'organization' | 'person'
+ id: string
+ name: string
+}
+
+// The application installs the settings twice: below `/orgs/$orgId` and
+// below `/people/$personId`. Each host route provides its owner.
+export const Route = createModuleRoot<{
+ owner: Owner
+ onProfileMatch?: (routeId: string | undefined) => void
+ profileLinks?: ComponentType
+}>()({
+ component: SettingsRoom,
+ notFoundComponent: () => MODULE_NOT_FOUND
,
+})
+
+// The module's region: a room tagged with the installation it renders and
+// where that installation is mounted.
+function SettingsRoom() {
+ const { owner } = Route.useRouteContext()
+ const match = Route.useMatch({
+ select: ({ routeId, fullPath, pathname }) => ({
+ installation: routeId.slice(0, routeId.indexOf(':')),
+ fullPath,
+ pathname,
+ }),
+ })
+ return (
+
+
+ {match.installation} {match.fullPath}
+ → {match.pathname}
+
+ Settings of {owner.name}
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/forward.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/forward.tsx
new file mode 100644
index 0000000000..c9520d47a6
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/src/routes/forward.tsx
@@ -0,0 +1,5 @@
+import * as React from 'react'
+import { createFileRoute, Navigate } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/settings:/forward')({
+ component: () => ,
+})
diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/index.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/index.tsx
new file mode 100644
index 0000000000..8bdbffdb73
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/src/routes/index.tsx
@@ -0,0 +1,16 @@
+import { Link, createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/settings:/')({
+ component: SettingsIndex,
+})
+
+function SettingsIndex() {
+ return (
+
+
+ Profile
+ Name and contact
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/legacy.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/legacy.tsx
new file mode 100644
index 0000000000..93d42fe065
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/src/routes/legacy.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute, redirect } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/settings:/legacy')({
+ beforeLoad: () => {
+ throw redirect({ to: '/profile' })
+ },
+})
diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/members.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/members.tsx
new file mode 100644
index 0000000000..cc255a1964
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/src/routes/members.tsx
@@ -0,0 +1,12 @@
+import * as React from 'react'
+import { createFileRoute, getRouteApi } from '../routeScope.gen'
+const ProfileLink = getRouteApi('@route-modules/settings:/profile').Link
+export const Route = createFileRoute('@route-modules/settings:/members')({
+ loader: () => ({ label: 'members' as const }),
+ component: () => (
+ <>
+ MEMBERS_PAGE
+ Profile
+ >
+ ),
+})
diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/missing.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/missing.tsx
new file mode 100644
index 0000000000..61911c6a98
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/src/routes/missing.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute, notFound } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/settings:/missing')({
+ component: () => {
+ throw notFound({ routeId: '@route-modules/settings:' })
+ },
+})
diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx
new file mode 100644
index 0000000000..29e5fdec2b
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx
@@ -0,0 +1,81 @@
+import * as React from 'react'
+import { Link as ApplicationLink } from '@tanstack/react-router'
+import {
+ createFileRoute,
+ getRouteApi,
+ MatchRoute,
+ useLinkProps,
+ useRouter,
+ useNavigate,
+} from '../routeScope.gen'
+
+const api = getRouteApi('@route-modules/settings:/profile')
+
+export const Route = createFileRoute('@route-modules/settings:/profile')({
+ // Each installation loads the profile of the owner its host provides.
+ loader: ({ context }) => ({
+ kind: context.owner.kind,
+ handle: `@${context.owner.id}`,
+ }),
+ component: Profile,
+})
+
+function Profile() {
+ const profile = Route.useLoaderData()
+ const ProfileLinks = Route.useRouteContext().profileLinks
+ const navigate = api.useNavigate()
+ const anchor = useLinkProps({ to: '/members' })
+ const match = Route.useMatch({ shouldThrow: false })
+ const routeNavigate = Route.useNavigate()
+ const relativeNavigate = useNavigate({ from: '/profile' })
+ const scopedRouter = useRouter()
+ const observe = scopedRouter.options.context?.onProfileMatch
+ React.useEffect(() => {
+ observe?.(match?.routeId)
+ }, [observe, match?.routeId])
+ return (
+
+ Profile
+ {match?.routeId}
+ {match?.localRouteId}
+
+ {JSON.stringify(match?.params)}
+
+ API members
+ {ProfileLinks ? : null}
+ navigate({ to: '/members' })}>
+ Navigate members
+
+ Custom members
+
+ PROFILE_MATCH
+
+
+ MEMBERS_MATCH
+
+
+ {scopedRouter.buildLocation({ to: '/members' }).href}
+
+ scopedRouter.navigate({ to: '/members' })}>
+ Router members
+
+ routeNavigate({ to: '..' })}>Route up
+ relativeNavigate({ to: '..' })}>
+ Explicit from home
+
+ Route home
+
+ Application host
+
+
+ Kind
+ {profile.kind}
+ Handle
+
+ {profile.handle}
+
+
+ All settings
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/search.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/search.tsx
new file mode 100644
index 0000000000..bdd6fb1f94
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/src/routes/search.tsx
@@ -0,0 +1,4 @@
+import { createFileRoute } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/settings:/search')({
+ validateSearch: (search: { query: string }) => search,
+})
diff --git a/e2e/react-router/route-modules/packages/settings/tsconfig.json b/e2e/react-router/route-modules/packages/settings/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/settings/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/settings/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/settings/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/storefront/package.json b/e2e/react-router/route-modules/packages/storefront/package.json
new file mode 100644
index 0000000000..78420d0ede
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/storefront/package.json
@@ -0,0 +1,42 @@
+{
+ "name": "@route-modules/storefront",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": {
+ "includes": [
+ {
+ "module": "@route-modules/products",
+ "at": "/products"
+ }
+ ]
+ }
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@route-modules/products": "workspace:*",
+ "@tanstack/react-router": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/storefront/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/storefront/src/routes/__root.tsx
new file mode 100644
index 0000000000..c9ac060bc1
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/storefront/src/routes/__root.tsx
@@ -0,0 +1,26 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+import type { ProductsApi } from '@route-modules/products/api'
+
+// The products module mounted below requires `productsApi`: the storefront
+// requires it from its own host and passes it on.
+export const Route = createModuleRoot<{ productsApi: ProductsApi }>()({
+ component: StorefrontRoom,
+})
+
+// The module's region: a room tagged with its package and where it is
+// mounted (with the URL it resolved to when the mount path has params).
+function StorefrontRoom() {
+ const pathname = Route.useMatch({ select: (match) => match.pathname })
+ return (
+
+
+ @route-modules/storefront {Route.fullPath}
+ {pathname !== Route.fullPath && (
+ → {pathname}
+ )}
+
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/storefront/src/routes/cart.tsx b/e2e/react-router/route-modules/packages/storefront/src/routes/cart.tsx
new file mode 100644
index 0000000000..79f6644d2e
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/storefront/src/routes/cart.tsx
@@ -0,0 +1,30 @@
+import { createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/storefront:/cart')({
+ // The products API comes from the context the storefront requires.
+ loader: ({ context }) =>
+ Promise.all(['1', '2'].map((id) => context.productsApi.getProduct(id))),
+ component: Cart,
+})
+
+function Cart() {
+ const items = Route.useLoaderData()
+ const total = items.reduce((sum, item) => sum + item.price, 0)
+ return (
+ <>
+ Cart
+
+ {items.map((item) => (
+
+ {item.name}
+ {item.price.toFixed(2)}
+
+ ))}
+
+ Total
+ {total.toFixed(2)}
+
+
+ >
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/storefront/src/routes/index.tsx b/e2e/react-router/route-modules/packages/storefront/src/routes/index.tsx
new file mode 100644
index 0000000000..9963a42c5a
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/storefront/src/routes/index.tsx
@@ -0,0 +1,30 @@
+import { Link, createFileRoute, products } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/storefront:/')({
+ component: StorefrontHome,
+})
+
+function StorefrontHome() {
+ return (
+
+
+
+ Cart
+ Two products waiting
+
+
+
+ Featured product
+
+ Picked by the storefront
+
+
+
+ Compare
+
+ Products 1 and 2 side by side
+
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/storefront/tsconfig.json b/e2e/react-router/route-modules/packages/storefront/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/storefront/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/storefront/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/storefront/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/storefront/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/team/package.json b/e2e/react-router/route-modules/packages/team/package.json
new file mode 100644
index 0000000000..1574523fe5
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/team/package.json
@@ -0,0 +1,38 @@
+{
+ "name": "@route-modules/team",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json",
+ "./scope": {
+ "types": "./.tanstack/types/src/routeScope.gen.d.ts",
+ "default": "./src/routeScope.gen.ts"
+ }
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/team/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/team/src/routes/__root.tsx
new file mode 100644
index 0000000000..c3c342479f
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/team/src/routes/__root.tsx
@@ -0,0 +1,27 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+
+// The organization comes from the host route the application mounts the team
+// under, so the team works below any route that provides it.
+export const Route = createModuleRoot<{ org: { id: string; name: string } }>()({
+ component: TeamRoom,
+})
+
+// The module's region: a room tagged with its package and where it is
+// mounted (with the URL it resolved to when the mount path has params).
+function TeamRoom() {
+ const { org } = Route.useRouteContext()
+ const pathname = Route.useMatch({ select: (match) => match.pathname })
+ return (
+
+
+ @route-modules/team {Route.fullPath}
+ {pathname !== Route.fullPath && (
+ → {pathname}
+ )}
+
+ Team of {org.name}
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/team/src/routes/index.tsx b/e2e/react-router/route-modules/packages/team/src/routes/index.tsx
new file mode 100644
index 0000000000..ee221db55d
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/team/src/routes/index.tsx
@@ -0,0 +1,25 @@
+import { Link, createFileRoute } from '../routeScope.gen'
+
+const members = [
+ { id: 'ada', role: 'Engineering' },
+ { id: 'grace', role: 'Operations' },
+]
+
+export const Route = createFileRoute('@route-modules/team:/')({
+ component: Members,
+})
+
+function Members() {
+ return (
+
+ {members.map((member) => (
+
+
+ {member.id}
+
+ {member.role}
+
+ ))}
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/team/src/routes/members.$memberId.tsx b/e2e/react-router/route-modules/packages/team/src/routes/members.$memberId.tsx
new file mode 100644
index 0000000000..6ed53bd48d
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/team/src/routes/members.$memberId.tsx
@@ -0,0 +1,28 @@
+import { Link, createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/team:/members/$memberId')({
+ component: Member,
+})
+
+function Member() {
+ const { memberId } = Route.useParams()
+ const { org } = Route.useRouteContext()
+ return (
+
+
+ {memberId} at {org.name}
+
+
+ Organization
+
+ {org.id}
+
+ Member
+
+ {memberId}
+
+
+ All members
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/team/tsconfig.json b/e2e/react-router/route-modules/packages/team/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/team/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/team/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/team/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/team/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/web/index.html b/e2e/react-router/route-modules/packages/web/index.html
new file mode 100644
index 0000000000..df728d8f44
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/index.html
@@ -0,0 +1,11 @@
+
+
+
+
+ Acme Workspace
+
+
+
+
+
+
diff --git a/e2e/react-router/route-modules/packages/web/package.json b/e2e/react-router/route-modules/packages/web/package.json
new file mode 100644
index 0000000000..117353b05d
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "@route-modules/web",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "generate": "tsr generate",
+ "check": "tsc --noEmit",
+ "build": "vite build && tsc -p tsconfig.contracts.json --noEmit",
+ "dev": "vite",
+ "check:contracts": "tsc -p tsconfig.contracts.json --noEmit"
+ },
+ "dependencies": {
+ "@route-modules/account": "workspace:*",
+ "@route-modules/billing": "workspace:*",
+ "@route-modules/products": "workspace:*",
+ "@route-modules/settings": "workspace:*",
+ "@route-modules/storefront": "workspace:*",
+ "@route-modules/team": "workspace:*",
+ "@tanstack/react-router": "workspace:^",
+ "@tanstack/react-router-devtools": "workspace:^",
+ "react": "^19.0.0",
+ "react-dom": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-plugin": "workspace:^",
+ "@types/react": "^19.0.8",
+ "@types/react-dom": "^19.0.3",
+ "@vitejs/plugin-react": "^6.0.1",
+ "vite": "^8.0.14",
+ "vitest": "catalog:"
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/web/src/main.tsx b/e2e/react-router/route-modules/packages/web/src/main.tsx
new file mode 100644
index 0000000000..d5f7da7f39
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/main.tsx
@@ -0,0 +1,28 @@
+import ReactDOM from 'react-dom/client'
+import { RouterProvider } from '@tanstack/react-router'
+import { createAppRouter } from './router'
+import './styles.css'
+import type { Price, Product } from '@route-modules/products/api'
+
+// Fixture data: every price is derived from the product id.
+const product = (id: string): Product => ({
+ id,
+ name: `Product ${id}`,
+ price: (([...id].reduce((sum, char) => sum + char.charCodeAt(0), 0) % 90) +
+ 10) as Price,
+})
+
+const observedModuleMatches: Array = []
+Object.assign(window, { observedModuleMatches })
+const router = createAppRouter(
+ {
+ getProduct: (id) => Promise.resolve(product(id)),
+ listProducts: () =>
+ Promise.resolve([product('1'), product('2'), product('3')]),
+ },
+ (routeId) => observedModuleMatches.push(routeId),
+)
+
+ReactDOM.createRoot(document.getElementById('app')!).render(
+ ,
+)
diff --git a/e2e/react-router/route-modules/packages/web/src/profile-links.tsx b/e2e/react-router/route-modules/packages/web/src/profile-links.tsx
new file mode 100644
index 0000000000..f05267a00b
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/profile-links.tsx
@@ -0,0 +1,18 @@
+import * as settings from '@route-modules/settings/scope'
+import { orgSettings } from './routeScope.gen'
+
+const deferredMembers = settings.linkOptions(
+ orgSettings.linkOptions({ to: '/members', params: { orgId: '7' } }),
+)
+
+export function ProfileLinks() {
+ const organizationProfile = orgSettings.useMatch({
+ from: '@route-modules/settings:/profile',
+ shouldThrow: false,
+ })
+ // The host owns its installation namespace; the provider renders this slot
+ // inside the profile match so the local receiver has a real nearest scope.
+ return organizationProfile ? (
+ Deferred members
+ ) : null
+}
diff --git a/e2e/react-router/route-modules/packages/web/src/router.tsx b/e2e/react-router/route-modules/packages/web/src/router.tsx
new file mode 100644
index 0000000000..94fe903a8a
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/router.tsx
@@ -0,0 +1,20 @@
+import { createRouter } from '@tanstack/react-router'
+import { ProfileLinks } from './profile-links'
+import { routeTree } from './routeTree.gen'
+import type { ProductsApi } from '@route-modules/products/api'
+
+export function createAppRouter(
+ productsApi: ProductsApi,
+ onProfileMatch?: (routeId: string | undefined) => void,
+) {
+ return createRouter({
+ routeTree,
+ context: { productsApi, onProfileMatch, profileLinks: ProfileLinks },
+ })
+}
+
+declare module '@tanstack/react-router' {
+ interface Register {
+ router: ReturnType
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx
new file mode 100644
index 0000000000..72374fa0e4
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx
@@ -0,0 +1,94 @@
+import * as React from 'react'
+import {
+ Link,
+ Outlet,
+ createRootRouteWithContext,
+} from '@tanstack/react-router'
+import {
+ account,
+ products,
+ storefront,
+ team,
+ orgSettings,
+ personSettings,
+} from '../routeScope.gen'
+import type { ProductsApi } from '@route-modules/products/api'
+
+// The router devtools, in development only.
+const RouterDevtools = import.meta.env.DEV
+ ? React.lazy(() =>
+ import('@tanstack/react-router-devtools').then((module) => ({
+ default: module.TanStackRouterDevtools,
+ })),
+ )
+ : () => null
+
+export const Route = createRootRouteWithContext<{
+ productsApi: ProductsApi
+ onProfileMatch?: (routeId: string | undefined) => void
+ profileLinks?: React.ComponentType
+}>()({
+ component: AppShell,
+})
+
+function AppShell() {
+ const organizationProfile = orgSettings.useMatch({
+ from: '@route-modules/settings:/profile',
+ shouldThrow: false,
+ })
+ return (
+ <>
+
+
+
+ Acme Workspace
+
+
+ Shop
+ Products
+ Account
+
+ Organizations
+
+ Acme
+
+
+ Globex
+
+
+
+
+
+
+ Switch to organization
+
+
+ Switch to person
+
+
+ {organizationProfile?.routeId ?? 'none'}
+
+
+
+
+
+
+
+
+ >
+ )
+}
+
+/** A small floor plan: outer walls with a door, two inner walls. */
+function PlanMark() {
+ return (
+
+
+
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/web/src/routes/_authenticated.tsx b/e2e/react-router/route-modules/packages/web/src/routes/_authenticated.tsx
new file mode 100644
index 0000000000..9cad2d227a
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/routes/_authenticated.tsx
@@ -0,0 +1,6 @@
+import { Outlet, createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/_authenticated')({
+ beforeLoad: () => ({ user: { id: 'u-1' } }),
+ component: () => ,
+})
diff --git a/e2e/react-router/route-modules/packages/web/src/routes/index.tsx b/e2e/react-router/route-modules/packages/web/src/routes/index.tsx
new file mode 100644
index 0000000000..90e3aa0f76
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/routes/index.tsx
@@ -0,0 +1,122 @@
+import { createFileRoute, useMatch } from '@tanstack/react-router'
+import {
+ account,
+ billing,
+ orgSettings,
+ personSettings,
+ products,
+ storefront,
+ team,
+} from '../routeScope.gen'
+
+export const Route = createFileRoute('/')({
+ component: Home,
+})
+
+// A key plan of the workspace: every module's room where the workspace mounts
+// it, nested like the routes.
+function Home() {
+ const productMatch = useMatch({
+ from: '@route-modules/products:/$productId',
+ shouldThrow: false,
+ })
+ return (
+ <>
+ Acme workspace
+
+ Each region of this workspace is a route module, drawn as a room: its
+ tag names the package and where the workspace mounts it.
+
+
+
+
+ @route-modules/storefront /shop
+
+
+ Cart
+
+
+
+ @route-modules/products /shop/products
+
+
+
+ Pick of the day
+
+ {productMatch?.loaderData?.name}
+
+
+
+
+
+ @route-modules/account /account
+
+
+ Your account
+
+
+ {/* The organization route is the workspace's own: both modules below
+ it get `orgId` from the URL. */}
+
+
+ Host route /orgs/$orgId
+
+
+
+
+ @route-modules/team /team
+
+
+ {/* The team is mounted below `/orgs/$orgId`: links into it pass `orgId`. */}
+
+ Acme team
+
+
+
+
+
+ @route-modules/billing /billing
+
+
+
+ Globex billing
+
+
+
+
+
+ @route-modules/settings#orgSettings /settings
+
+
+
+ Globex settings
+
+
+
+
+
+ {/* The settings are installed a second time, per person. */}
+
+
+ Host route /people/$personId
+
+
+
+
+ @route-modules/settings#personSettings /settings
+
+
+
+ Ada's profile
+
+
+
+
+
+
+ >
+ )
+}
diff --git a/e2e/react-router/route-modules/packages/web/src/routes/orgs.$orgId.tsx b/e2e/react-router/route-modules/packages/web/src/routes/orgs.$orgId.tsx
new file mode 100644
index 0000000000..3c08aa0637
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/routes/orgs.$orgId.tsx
@@ -0,0 +1,15 @@
+import { Outlet, createFileRoute } from '@tanstack/react-router'
+
+// The host route of the modules mounted per organization: they get its path
+// params in their URLs and the organization as context, and its settings
+// installation the organization as their owner.
+export const Route = createFileRoute('/orgs/$orgId')({
+ beforeLoad: ({ params }) => {
+ const name = params.orgId.toUpperCase()
+ return {
+ org: { id: params.orgId, name },
+ owner: { kind: 'organization' as const, id: params.orgId, name },
+ }
+ },
+ component: () => ,
+})
diff --git a/e2e/react-router/route-modules/packages/web/src/routes/people.$personId.tsx b/e2e/react-router/route-modules/packages/web/src/routes/people.$personId.tsx
new file mode 100644
index 0000000000..19ac32e5c7
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/routes/people.$personId.tsx
@@ -0,0 +1,13 @@
+import { Outlet, createFileRoute } from '@tanstack/react-router'
+
+// The host route of the settings installation per person.
+export const Route = createFileRoute('/people/$personId')({
+ beforeLoad: ({ params }) => ({
+ owner: {
+ kind: 'person' as const,
+ id: params.personId,
+ name: params.personId[0]!.toUpperCase() + params.personId.slice(1),
+ },
+ }),
+ component: () => ,
+})
diff --git a/e2e/react-router/route-modules/packages/web/src/styles.css b/e2e/react-router/route-modules/packages/web/src/styles.css
new file mode 100644
index 0000000000..edcaf3ef9b
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/src/styles.css
@@ -0,0 +1,450 @@
+/*
+ * Acme: the route-module fixtures drawn as a floor plan. Every route module is
+ * a room: a wall line, a zoning tint and a room tag with its package and mount
+ * path. Violet marks the active route and nothing else.
+ */
+
+:root {
+ color-scheme: light;
+
+ --ground: #f4f6f9;
+ --sheet: #ffffff;
+ --ink: #1f2328;
+ --ink-2: #4b535c;
+ --ink-3: #59616b;
+ --line: #d3d7db;
+ --wall: #2a3036;
+ --route: #5b3fd1;
+ --route-wash: #e9e5fb;
+ /* Link underlines: 3:1 or better on the ground and on every zone. */
+ --underline: color-mix(in srgb, var(--wall) 55%, transparent);
+ --zone: #eef0f2;
+
+ --font:
+ ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto,
+ 'Helvetica Neue', Arial, sans-serif;
+ /* Plan lettering: a local condensed face where there is one. */
+ --font-lettering:
+ 'Avenir Next Condensed', 'Roboto Condensed', 'Arial Narrow', ui-sans-serif,
+ system-ui, sans-serif;
+ --mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
+
+ --s1: 4px;
+ --s2: 8px;
+ --s3: 12px;
+ --s4: 16px;
+ --s5: 20px;
+ --s6: 24px;
+ --s8: 32px;
+ --s10: 40px;
+ --s12: 48px;
+
+ /* A drafted wall: two lines with the wall's thickness between them. */
+ --wall-line: 6px double var(--wall);
+ --ease-out: cubic-bezier(0.16, 1, 0.3, 1);
+}
+
+/* Zoning: one tint per module, as on a zoning plan. */
+[data-route-module='@route-modules/storefront'] {
+ --zone: #e7e9e4;
+}
+[data-route-module='@route-modules/products'] {
+ --zone: #e1ebdd;
+}
+[data-route-module='@route-modules/account'] {
+ --zone: #dce7f2;
+}
+[data-route-module='@route-modules/team'] {
+ --zone: #d9eeeb;
+}
+[data-route-module='@route-modules/billing'] {
+ --zone: #f2e1e1;
+}
+[data-route-module='@route-modules/settings'] {
+ --zone: #efecd2;
+}
+
+*,
+*::before,
+*::after {
+ box-sizing: border-box;
+}
+
+html {
+ background: var(--ground);
+ scrollbar-color: var(--line) transparent;
+}
+
+body {
+ margin: 0;
+ color: var(--ink);
+ font: 400 15px/1.55 var(--font);
+ -webkit-font-smoothing: antialiased;
+}
+
+::selection {
+ background: var(--route-wash);
+ color: var(--ink);
+}
+
+:focus-visible {
+ outline: 2px solid var(--wall);
+ outline-offset: 2px;
+ border-radius: 2px;
+}
+
+h1,
+h2,
+h3 {
+ margin: 0 0 var(--s3);
+ font-weight: 650;
+ letter-spacing: -0.02em;
+ line-height: 1.2;
+ text-wrap: balance;
+}
+h1 {
+ font-size: 30px;
+}
+h2 {
+ font-size: 22px;
+}
+h3 {
+ font-size: 18px;
+}
+
+p {
+ margin: 0 0 var(--s3);
+ max-width: 68ch;
+}
+
+code {
+ font: 500 0.92em var(--mono);
+}
+
+a {
+ color: var(--ink);
+ text-decoration: underline;
+ text-decoration-color: var(--underline);
+ text-decoration-thickness: 1px;
+ text-underline-offset: 3px;
+ transition: text-decoration-color 160ms var(--ease-out);
+}
+a:hover {
+ text-decoration-color: var(--ink);
+}
+
+button {
+ font: inherit;
+}
+
+/* Shell */
+
+.topbar {
+ position: sticky;
+ top: 0;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ gap: var(--s8);
+ min-height: 52px;
+ padding: 0 var(--s6);
+ background: var(--sheet);
+ border-bottom: 1px solid var(--line);
+}
+
+.brand {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--s2);
+ font-weight: 650;
+ letter-spacing: -0.01em;
+ text-decoration: none;
+ white-space: nowrap;
+}
+.brand-mark {
+ flex: none;
+ width: 18px;
+ height: 18px;
+ color: var(--wall);
+}
+.brand small {
+ color: var(--ink-3);
+ font-size: 13px;
+ font-weight: 500;
+}
+
+.nav {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--s1) var(--s5);
+ font-size: 14px;
+}
+.nav a {
+ position: relative;
+ margin: 0 calc(-1 * var(--s1));
+ padding: var(--s3) var(--s1);
+ color: var(--ink-2);
+ text-decoration: none;
+}
+.nav a:hover {
+ color: var(--ink);
+}
+.nav a[data-status='active'] {
+ color: var(--route);
+}
+.nav a[data-status='active']::after {
+ content: '';
+ position: absolute;
+ inset: auto var(--s1) 0;
+ height: 2px;
+ background: var(--route);
+}
+.nav-group {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--s4);
+ padding-left: var(--s5);
+ border-left: 1px solid var(--line);
+}
+.nav-label {
+ color: var(--ink-3);
+ font-size: 13px;
+}
+
+.page {
+ max-width: 1080px;
+ margin: 0 auto;
+ padding: var(--s10) var(--s6) 120px;
+}
+
+.lead {
+ color: var(--ink-2);
+ font-size: 17px;
+}
+
+/* Rooms: the signature. A module's region is a room with a wall line, its
+ zoning tint, and a tag on the wall naming the package and its mount. */
+
+.room {
+ margin-top: var(--s5);
+ padding: 0 var(--s6) var(--s6);
+ background: var(--zone) padding-box;
+ border: var(--wall-line);
+ animation: room-in 420ms var(--ease-out);
+}
+.room .room {
+ margin-top: var(--s8);
+}
+.room > :last-child {
+ margin-bottom: 0;
+}
+/* A room's title has one size whatever its level. */
+.room h1 {
+ font-size: 22px;
+}
+
+/* The tag sits on the wall: pulled up onto its center line, it wraps on
+ narrow screens instead of clipping the resolved path. Names and paths keep
+ their source case: they are identifiers maintainers copy. */
+.room-tag {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: 0 var(--s2);
+ width: fit-content;
+ max-width: 100%;
+ margin: -14px 0 var(--s5) calc(var(--s4) - var(--s6));
+ padding: 2px var(--s2);
+ background: var(--sheet);
+ border: 1px solid var(--wall);
+ font: 600 12px/16px var(--font-lettering);
+ font-stretch: condensed;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: 0.04em;
+}
+.room-tag code {
+ font: 500 11px/16px var(--mono);
+ color: var(--ink-2);
+}
+.room-tag .resolved {
+ color: var(--route);
+}
+
+@keyframes room-in {
+ from {
+ background-color: var(--sheet);
+ }
+}
+
+/* Lists, facts and controls inside rooms */
+
+.rows {
+ margin: 0 0 var(--s4);
+ padding: 0;
+ list-style: none;
+ font-variant-numeric: tabular-nums;
+ border-top: 1px solid color-mix(in srgb, var(--wall) 22%, transparent);
+}
+.rows > li {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: var(--s4);
+ padding: var(--s3) 0;
+ border-bottom: 1px solid color-mix(in srgb, var(--wall) 22%, transparent);
+}
+.rows .meta {
+ color: var(--ink-3);
+ font-size: 13px;
+}
+
+.facts {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ align-items: baseline;
+ gap: var(--s2) var(--s6);
+ margin: 0 0 var(--s5);
+ font-variant-numeric: tabular-nums;
+}
+.facts dt {
+ color: var(--ink-3);
+ font-size: 13px;
+}
+.facts dd {
+ margin: 0;
+}
+
+.tabs {
+ display: flex;
+ gap: var(--s5);
+ margin: 0 0 var(--s4);
+ border-bottom: 1px solid color-mix(in srgb, var(--wall) 22%, transparent);
+ font-size: 14px;
+}
+.tabs a {
+ margin-bottom: -1px;
+ padding: var(--s2) 0;
+ color: var(--ink-2);
+ text-decoration: none;
+ border-bottom: 2px solid transparent;
+}
+.tabs a:hover {
+ color: var(--ink);
+}
+.tabs a[aria-current] {
+ color: var(--route);
+ border-bottom-color: var(--route);
+}
+
+.button {
+ display: inline-flex;
+ align-items: center;
+ min-height: 36px;
+ padding: 0 var(--s4);
+ color: var(--sheet);
+ background: var(--wall);
+ border: 0;
+ border-radius: 6px;
+ font-weight: 600;
+ font-size: 14px;
+ cursor: pointer;
+ transition:
+ background-color 160ms var(--ease-out),
+ transform 160ms var(--ease-out);
+}
+.button:hover {
+ background: var(--ink);
+}
+.button:active {
+ transform: translateY(1px);
+}
+
+/* Key plan on the home page: every room where the application mounts it.
+ A host route that is not a module is a plot boundary around its rooms. */
+
+.plan {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ align-items: start;
+ gap: var(--s8) var(--s6);
+ margin-top: var(--s10);
+}
+.plan .room {
+ margin-top: 0;
+}
+.plan .room .room {
+ margin-top: var(--s6);
+}
+.plan .room > p:not(.room-tag) {
+ color: var(--ink-2);
+}
+.plot {
+ grid-column: 1 / -1;
+ padding: 0 var(--s6) var(--s6);
+ border: 1.5px dashed var(--ink-3);
+}
+.plot-rooms {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ align-items: start;
+ gap: var(--s8) var(--s6);
+ padding-top: var(--s3);
+}
+.plot > .room-tag {
+ margin-top: -12px;
+ margin-bottom: var(--s4);
+ border-style: dashed;
+ border-color: var(--ink-3);
+ font-weight: 500;
+}
+
+@media (max-width: 720px) {
+ .topbar {
+ position: static;
+ flex-wrap: wrap;
+ gap: 0 var(--s4);
+ padding: var(--s2) var(--s4) 0;
+ }
+ /* One scrolling row below the brand. */
+ .nav {
+ order: 1;
+ flex-basis: 100%;
+ flex-wrap: nowrap;
+ gap: var(--s2);
+ overflow-x: auto;
+ scrollbar-width: none;
+ }
+ .nav a,
+ .nav-group {
+ flex: none;
+ }
+ .nav-group {
+ gap: var(--s2);
+ padding-left: var(--s2);
+ }
+ .nav-label {
+ display: none;
+ }
+ .page {
+ padding: var(--s6) var(--s4) 120px;
+ }
+ .room {
+ padding: 0 var(--s4) var(--s4);
+ }
+ .room-tag {
+ margin-left: 0;
+ }
+ .plan {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ .plot {
+ padding: 0 var(--s4) var(--s4);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .room {
+ animation: none;
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/web/tests/match-identity.test.tsx b/e2e/react-router/route-modules/packages/web/tests/match-identity.test.tsx
new file mode 100644
index 0000000000..7aedbb6ae6
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/tests/match-identity.test.tsx
@@ -0,0 +1,139 @@
+import { describe, expect, test } from 'vitest'
+import { createMemoryHistory, createRouter } from '@tanstack/react-router'
+import { routeTree } from '../src/routeTree.gen'
+import {
+ account,
+ products,
+ storefront,
+ orgSettings,
+ personSettings,
+} from '../src/routeScope.gen'
+import { isScopedMatch } from '@route-modules/settings/scope'
+
+function createApp(pathname: string) {
+ return createRouter({
+ routeTree,
+ history: createMemoryHistory({ initialEntries: [pathname] }),
+ // This server harness drives load explicitly. Browser e2e tests exercise
+ // the navigation subscription owned by a mounted RouterProvider.
+ isServer: true,
+ context: {
+ productsApi: {
+ getProduct: async (id) => ({ id, name: id, price: 10 as never }),
+ listProducts: async () => [],
+ },
+ },
+ })
+}
+
+describe('installed module match identity', () => {
+ test.each([
+ ['/orgs/globex/settings/profile', 'orgSettings', '/orgs/$orgId'],
+ ['/people/ada/settings/profile', 'personSettings', '/people/$personId'],
+ ])(
+ 'keeps final and module-local identities for %s',
+ async (pathname, installation, parent) => {
+ const router = createApp(pathname)
+ await router.load()
+ expect(
+ router.state.matches.map(({ routeId, localRouteId }) => ({
+ routeId,
+ localRouteId,
+ })),
+ ).toEqual([
+ { routeId: '__root__', localRouteId: undefined },
+ { routeId: parent, localRouteId: undefined },
+ {
+ routeId: `@route-modules/settings#${installation}:`,
+ localRouteId: '@route-modules/settings:',
+ },
+ {
+ routeId: `@route-modules/settings#${installation}:/profile`,
+ localRouteId: '@route-modules/settings:/profile',
+ },
+ ])
+ expect(Object.hasOwn(router.state.matches[0]!, 'localRouteId')).toBe(
+ false,
+ )
+ expect(Object.hasOwn(router.state.matches[1]!, 'localRouteId')).toBe(
+ false,
+ )
+ },
+ )
+
+ test('loading a new location keeps local identity across installations', async () => {
+ const router = createApp('/orgs/globex/settings/profile')
+ await router.load()
+ router.history.push('/people/ada/settings/profile')
+ await router.load()
+ expect(router.state.matches.at(-1)).toMatchObject({
+ routeId: '@route-modules/settings#personSettings:/profile',
+ localRouteId: '@route-modules/settings:/profile',
+ loaderData: { kind: 'person', handle: '@ada' },
+ })
+ })
+})
+
+test('context-free match guards select the installed subtree and exact namespace', async () => {
+ const router = createApp('/orgs/globex/settings/profile')
+ await router.load()
+ expect(
+ router.state.matches
+ .filter(orgSettings.isScopedMatch)
+ .map((match) => match.routeId),
+ ).toEqual([
+ '@route-modules/settings#orgSettings:',
+ '@route-modules/settings#orgSettings:/profile',
+ ])
+ expect(router.state.matches.filter(personSettings.isScopedMatch)).toEqual([])
+ expect(
+ router.state.matches
+ .filter(isScopedMatch)
+ .map((match) => match.localRouteId),
+ ).toEqual(['@route-modules/settings:', '@route-modules/settings:/profile'])
+
+ // The server load needs the canonical search value supplied by this route.
+ router.history.push('/shop/products/1?tab=specs')
+ await router.load()
+ // Descendant module matches belong to the storefront's installed subtree.
+ expect(
+ router.state.matches
+ .filter(storefront.isScopedMatch)
+ .map((match) => match.routeId),
+ ).toEqual([
+ '@route-modules/storefront:',
+ '@route-modules/products:',
+ '@route-modules/products:/$productId',
+ ])
+ // The host's namespace for the nested include selects the nested module only.
+ expect(
+ router.state.matches
+ .filter(products.isScopedMatch)
+ .map((match) => match.routeId),
+ ).toEqual(['@route-modules/products:', '@route-modules/products:/$productId'])
+ // Account only declares `uses: products`; that dependency is not installed
+ // beneath account and must not be classified as an account subtree match.
+ expect(router.state.matches.filter(account.isScopedMatch)).toEqual([])
+})
+
+test('application route objects expose the installed graph', async () => {
+ const router = createApp('/orgs/globex/settings/profile')
+ await router.load()
+ const root = router.routesById['@route-modules/settings#orgSettings:']
+ const profile =
+ router.routesById['@route-modules/settings#orgSettings:/profile']
+ // `path` is the normalized segment; options.path is the authored mount path.
+ expect(root.path).toBe('settings')
+ expect(root.options.path).toBe('/settings')
+ expect(root.fullPath).toBe('/orgs/$orgId/settings')
+ expect(profile.parentRoute).toBe(root)
+ expect(profile.options.getParentRoute?.()).toBe(root)
+ expect(profile.parentRoute.id).toBe('@route-modules/settings#orgSettings:')
+
+ const layout = router.routesById['@route-modules/products:/_layout']
+ const children = Object.values(layout.children ?? {})
+ expect(children.map((child) => child.fullPath)).toEqual([
+ '/shop/products/deals',
+ ])
+ expect(children[0]?.parentRoute).toBe(layout)
+})
diff --git a/e2e/react-router/route-modules/packages/web/tests/scope-options.test.tsx b/e2e/react-router/route-modules/packages/web/tests/scope-options.test.tsx
new file mode 100644
index 0000000000..df968f2f62
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/tests/scope-options.test.tsx
@@ -0,0 +1,140 @@
+import * as React from 'react'
+import { renderToString } from 'react-dom/server'
+import { expect, test } from 'vitest'
+import {
+ RouterContextProvider,
+ createMemoryHistory,
+ createRouter,
+} from '@tanstack/react-router'
+import { routeTree } from '../src/routeTree.gen'
+import { orgSettings, personSettings } from '../src/routeScope.gen'
+import * as settings from '@route-modules/settings/scope'
+
+async function createApp() {
+ const router = createRouter({
+ routeTree,
+ context: {
+ productsApi: {
+ getProduct: async (id) => ({ id, name: id, price: 10 as never }),
+ listProducts: async () => [],
+ },
+ },
+ history: createMemoryHistory({
+ initialEntries: ['/orgs/7/settings/profile'],
+ }),
+ })
+ await router.load()
+ return router
+}
+
+test('scoped consumers reject options from another named installation', async () => {
+ const router = await createApp()
+ // JSON is a realistic untyped source; typed conflicts are covered separately.
+ const foreign = JSON.parse(
+ JSON.stringify(
+ personSettings.linkOptions({
+ to: '/members',
+ params: { personId: 'u1' },
+ }),
+ ),
+ )
+ for (const Component of [
+ orgSettings.Link,
+ orgSettings.Navigate,
+ orgSettings.MatchRoute,
+ ]) {
+ expect(() =>
+ renderToString(
+
+ {React.createElement(Component as React.ComponentType, foreign)}
+ ,
+ ),
+ ).toThrow(/Cannot use route scope/)
+ }
+ expect(() => orgSettings.linkOptions(foreign)).toThrow(
+ /Cannot use route scope/,
+ )
+ expect(() => orgSettings.redirect(foreign)).toThrow(/Cannot use route scope/)
+})
+
+test('same-scope options and neutral consumers preserve their destination', async () => {
+ const router = await createApp()
+ const home = orgSettings.linkOptions({
+ to: '/members',
+ params: { orgId: '7' },
+ })
+ expect(router.buildLocation(home).href).toBe('/orgs/7/settings/members')
+ expect(
+ renderToString(
+
+ Members
+ ,
+ ),
+ ).toContain('href="/orgs/7/settings/members"')
+})
+
+test('a context-free local receiver preserves its constraint until navigation', async () => {
+ const router = await createApp()
+ const local = settings.linkOptions({ to: '/members' })
+ const explicit = personSettings.linkOptions({
+ to: '/members',
+ params: { personId: 'u1' },
+ })
+ const deferred = settings.linkOptions(explicit)
+ const redirect = settings.redirect(explicit)
+ function Receiver({ options }: { options: typeof local | typeof deferred }) {
+ // The generated namespace is the explicit receiving installation. The
+ // normal hook supplies its router view; no private origin is fabricated.
+ const scopedRouter = orgSettings.useRouter()
+ return {scopedRouter.buildLocation(options).href}
+ }
+ function renderOptions(options: typeof local | typeof deferred) {
+ return renderToString(
+
+
+ ,
+ )
+ }
+ expect(renderOptions(local)).toContain('/orgs/7/settings/members')
+ expect(() => renderOptions(deferred)).toThrow(/Cannot use route scope/)
+ // The redirect's public options keep the same unresolved receiving contract.
+ expect(() => renderOptions(redirect.options)).toThrow(
+ /Cannot use route scope/,
+ )
+})
+
+test('an explicit receiving scope resolves a deferred local constraint', async () => {
+ const router = await createApp()
+ const options = settings.linkOptions(
+ orgSettings.linkOptions({ to: '/members', params: { orgId: '7' } }),
+ )
+ function Receiver() {
+ const href = orgSettings.useRouter().buildLocation(options).href
+ return {href}
+ }
+ expect(
+ renderToString(
+
+
+ ,
+ ),
+ ).toContain('/orgs/7/settings/members')
+})
+
+test('stamped mask options cannot silently retarget a sibling installation', async () => {
+ const router = await createApp()
+ const mask = JSON.parse(
+ JSON.stringify(
+ personSettings.linkOptions({
+ to: '/members',
+ params: { personId: 'u1' },
+ }),
+ ),
+ )
+ const options = orgSettings.linkOptions({
+ to: '/members',
+ params: { orgId: '7' },
+ mask,
+ })
+ expect(() => router.buildLocation(options)).toThrow(/Cannot use route scope/)
+})
diff --git a/e2e/react-router/route-modules/packages/web/tsconfig.contracts.json b/e2e/react-router/route-modules/packages/web/tsconfig.contracts.json
new file mode 100644
index 0000000000..c783b45e43
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/tsconfig.contracts.json
@@ -0,0 +1,7 @@
+{
+ "extends": "./tsconfig.json",
+ "include": ["src", "type-tests"],
+ "compilerOptions": {
+ "skipLibCheck": false
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/web/tsconfig.json b/e2e/react-router/route-modules/packages/web/tsconfig.json
new file mode 100644
index 0000000000..44dff33802
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": ["vite/client"]
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-router/route-modules/packages/web/tsr.config.json b/e2e/react-router/route-modules/packages/web/tsr.config.json
new file mode 100644
index 0000000000..0b6ae92d38
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/tsr.config.json
@@ -0,0 +1,36 @@
+{
+ "routesDirectory": "./src/routes",
+ "generatedRouteTree": "./src/routeTree.gen.ts",
+ "routeModules": {
+ "includes": [
+ { "module": "@route-modules/storefront", "at": "/shop" },
+ {
+ "module": "@route-modules/account",
+ "parent": "/_authenticated",
+ "at": "/account"
+ },
+ {
+ "module": "@route-modules/team",
+ "parent": "/orgs/$orgId",
+ "at": "/team"
+ },
+ {
+ "module": "@route-modules/billing",
+ "parent": "/orgs/$orgId",
+ "at": "/billing"
+ },
+ {
+ "module": "@route-modules/settings",
+ "parent": "/orgs/$orgId",
+ "at": "/settings",
+ "as": "orgSettings"
+ },
+ {
+ "module": "@route-modules/settings",
+ "parent": "/people/$personId",
+ "at": "/settings",
+ "as": "personSettings"
+ }
+ ]
+ }
+}
diff --git a/e2e/react-router/route-modules/packages/web/type-tests/core-contracts.tsx b/e2e/react-router/route-modules/packages/web/type-tests/core-contracts.tsx
new file mode 100644
index 0000000000..4f12bdbdd4
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/type-tests/core-contracts.tsx
@@ -0,0 +1,211 @@
+import { describe, expectTypeOf, test } from 'vitest'
+import type { routeTree } from '../src/routeTree.gen'
+import type { createAppRouter } from '../src/router'
+import { routeModule as productsRouteModule } from '@route-modules/products/route-module'
+import {
+ useMatch as useProductMatch,
+ useRouter as useProductRouter,
+ useRouterState as useProductRouterState,
+ useLocation as useProductLocation,
+ useSearch as useProductSearch,
+ isScopedMatch as isProductMatch,
+} from '@route-modules/products/scope'
+import type {
+ Router as ProductsRouter,
+ OwnRoutesById,
+} from '@route-modules/products/route-types'
+import type { Product } from '@route-modules/products/api'
+import type {
+ AnyRouteMatch,
+ AnyRoute,
+ ForeignRouteMatch,
+ InstallationRoutesById,
+ MountedRoutesById,
+ MakeRouteMatch,
+ MakeRouteMatchUnion,
+} from '@tanstack/react-router'
+
+declare const ProductRoute: OwnRoutesById['@route-modules/products:/$productId']
+declare const foreignMatch: ForeignRouteMatch
+declare const routerMatch: AnyRouteMatch
+declare const mountedProduct: ReturnType<
+ typeof createAppRouter
+>['routesById']['@route-modules/products:/$productId']
+
+const applicationRoute: AnyRoute = mountedProduct
+void applicationRoute
+
+describe('installed route identity contracts', () => {
+ test('installation map values agree with their keys', () => {
+ type Installed = InstallationRoutesById<
+ { '@route-modules/products:/$productId': typeof ProductRoute },
+ '@route-modules/products',
+ 'shopProducts'
+ >
+ type Product = Installed['@route-modules/products#shopProducts:/$productId']
+
+ expectTypeOf<
+ Product['id']
+ >().toEqualTypeOf<'@route-modules/products#shopProducts:/$productId'>()
+ expectTypeOf<
+ Product['types']['id']
+ >().toEqualTypeOf<'@route-modules/products#shopProducts:/$productId'>()
+ expectTypeOf(
+ ProductRoute.id,
+ ).toEqualTypeOf<'@route-modules/products:/$productId'>()
+ type Mounted =
+ MountedRoutesById['@route-modules/products#shopProducts:/$productId']
+ expectTypeOf().toEqualTypeOf()
+ expectTypeOf().toEqualTypeOf()
+ expectTypeOf().toEqualTypeOf()
+ expectTypeOf(ProductRoute.fullPath).toEqualTypeOf<'/$productId'>()
+ })
+
+ test('known module matches have an exact required local identity', () => {
+ type ProductMatch = MakeRouteMatch<
+ typeof productsRouteModule,
+ '@route-modules/products:/$productId'
+ >
+ expectTypeOf<
+ ProductMatch['localRouteId']
+ >().toEqualTypeOf<'@route-modules/products:/$productId'>()
+ expectTypeOf().toEqualTypeOf<
+ string | undefined
+ >()
+ })
+
+ test('application records preserve ordinary path precision and mixed optional identity', () => {
+ type Tree = typeof routeTree
+ type Host = MakeRouteMatch
+ expectTypeOf().toEqualTypeOf<'/orgs/$orgId'>()
+ type Mixed = MakeRouteMatch<
+ Tree,
+ '/orgs/$orgId' | '@route-modules/settings#orgSettings:/profile'
+ >
+ expectTypeOf().toEqualTypeOf()
+ type Product = MakeRouteMatch<
+ Tree,
+ '@route-modules/settings#orgSettings:/profile'
+ >
+ expectTypeOf<
+ Product['routeId']
+ >().toEqualTypeOf<'@route-modules/settings#orgSettings:/profile'>()
+ expectTypeOf().toEqualTypeOf()
+ })
+
+ test('module hooks describe final installation identity honestly', () => {
+ const match = useProductMatch({
+ from: '@route-modules/products:/$productId',
+ })
+ expectTypeOf(match.fullPath).toEqualTypeOf()
+ expectTypeOf(match.routeId).toEqualTypeOf<
+ | '@route-modules/products:/$productId'
+ | `@route-modules/products#${string}:/$productId`
+ >()
+ expectTypeOf(
+ match.localRouteId,
+ ).toEqualTypeOf<'@route-modules/products:/$productId'>()
+ })
+
+ test('a full scoped match chain includes unknown host data', () => {
+ type Match = MakeRouteMatchUnion
+ expectTypeOf().toBeUnknown()
+ expectTypeOf().toBeUnknown()
+ expectTypeOf(useProductRouterState().matches[0]!.context).toBeUnknown()
+ expectTypeOf(useProductLocation().search).toEqualTypeOf<
+ Record
+ >()
+ expectTypeOf(useProductRouter().state.location.search).toEqualTypeOf<
+ Record
+ >()
+ expectTypeOf(
+ useProductSearch({ from: '@route-modules/products:/$productId' }).tab,
+ ).toEqualTypeOf<'specs' | 'reviews'>()
+ expectTypeOf(useProductRouter().state.matches[0]!.loaderData).toBeUnknown()
+ useProductRouterState({
+ select: (state) => {
+ expectTypeOf(state.matches[0]!.context).toBeUnknown()
+ return state.matches.length
+ },
+ })
+ })
+
+ test('scope membership narrows complete router matches', () => {
+ isProductMatch(routerMatch)
+ isProductMatch(foreignMatch)
+ for (const match of useProductRouterState().matches) {
+ if (
+ isProductMatch(match) &&
+ match.localRouteId === '@route-modules/products:/$productId'
+ ) {
+ expectTypeOf(match.loaderData).toEqualTypeOf()
+ }
+ }
+
+ // @ts-expect-error Scope membership cannot supply absent match data.
+ isProductMatch({
+ routeId: '@route-modules/products:/$productId',
+ localRouteId: '@route-modules/products:/$productId',
+ })
+ })
+
+ test('loose match selectors retain unknown foreign route data', () => {
+ useProductMatch({
+ strict: false,
+ select: (match) => {
+ expectTypeOf(match.loaderData).toBeUnknown()
+ expectTypeOf(match.context).toBeUnknown()
+ return match.routeId
+ },
+ })
+ })
+
+ test('raw scoped router maps do not promise module-local aliases', () => {
+ const router = useProductRouter()
+ expectTypeOf(
+ router.routesById['@route-modules/products:/$productId'],
+ ).toEqualTypeOf()
+ expectTypeOf(router.routesByPath['/$productId']).toEqualTypeOf<
+ AnyRoute | undefined
+ >()
+ })
+})
+
+test('application route records expose mounted paths and raw linked routes honestly', () => {
+ type Routes = ReturnType['routesById']
+ type Root = Routes['@route-modules/settings#orgSettings:']
+ type Profile = Routes['@route-modules/settings#orgSettings:/profile']
+ // These are values read from the real generated installation at runtime.
+ // They must be assignable to the public route object's declared fields.
+ expectTypeOf<'settings'>().toMatchTypeOf()
+ expectTypeOf<'settings'>().toMatchTypeOf()
+ expectTypeOf<'/settings'>().toMatchTypeOf<
+ NonNullable
+ >()
+ expectTypeOf<'@route-modules/settings#orgSettings:'>().toMatchTypeOf<
+ Profile['parentRoute']['id']
+ >()
+ expectTypeOf<'@route-modules/settings#orgSettings:'>().toMatchTypeOf<
+ Profile['types']['parentRoute']['id']
+ >()
+ type ParentFromOptions = ReturnType<
+ NonNullable
+ >
+ expectTypeOf<'@route-modules/settings#orgSettings:'>().toMatchTypeOf<
+ ParentFromOptions['id']
+ >()
+
+ type Layout = Routes['@route-modules/products:/_layout']
+ type Children = NonNullable
+ type Child =
+ Children extends ReadonlyArray ? Item : Children[keyof Children]
+ expectTypeOf<'/shop/products/deals'>().toMatchTypeOf()
+
+ // Precision that the application can prove remains intact.
+ expectTypeOf<
+ Profile['id']
+ >().toEqualTypeOf<'@route-modules/settings#orgSettings:/profile'>()
+ expectTypeOf<
+ Routes['/orgs/$orgId']['fullPath']
+ >().toEqualTypeOf<'/orgs/$orgId'>()
+})
diff --git a/e2e/react-router/route-modules/packages/web/type-tests/module-apis.tsx b/e2e/react-router/route-modules/packages/web/type-tests/module-apis.tsx
new file mode 100644
index 0000000000..c25a115af5
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/type-tests/module-apis.tsx
@@ -0,0 +1,207 @@
+import * as React from 'react'
+import { describe, expectTypeOf, test } from 'vitest'
+import { Link, useMatch } from '@tanstack/react-router'
+import {
+ Link as ProductsLink,
+ getRouteApi as productsGetRouteApi,
+ linkOptions as productsLinkOptions,
+ redirect as productsRedirect,
+ useLoaderData as productsUseLoaderData,
+ useNavigate as productsUseNavigate,
+ useRouter as productsUseRouter,
+} from '@route-modules/products/scope'
+import {
+ Link as AccountLink,
+ getRouteApi as accountGetRouteApi,
+ products,
+} from '@route-modules/account/scope'
+import * as localTeam from '@route-modules/team/scope'
+import { team as hostedTeam } from '../src/routeScope.gen'
+import type { createAppRouter } from '../src/router'
+import type { Price, Product, ProductsApi } from '@route-modules/products/api'
+import type {
+ Router as ProductsRouter,
+ OwnRoutesById,
+} from '@route-modules/products/route-types'
+import type { ScopedRouterView } from '@tanstack/react-router'
+
+declare const ProductRoute: OwnRoutesById['@route-modules/products:/$productId']
+declare const ProductsRootRoute: OwnRoutesById['@route-modules/products:']
+
+describe('module route types', () => {
+ test('ids are qualified, full paths are module-local', () => {
+ expectTypeOf(
+ ProductRoute.id,
+ ).toEqualTypeOf<'@route-modules/products:/$productId'>()
+ expectTypeOf(ProductRoute.fullPath).toEqualTypeOf<'/$productId'>()
+ expectTypeOf(
+ ProductsRootRoute.id,
+ ).toEqualTypeOf<'@route-modules/products:'>()
+ })
+
+ test('route-bound hooks resolve through the module scope', () => {
+ const product = ProductRoute.useLoaderData()
+ expectTypeOf(product).not.toBeAny()
+ expectTypeOf(product).toEqualTypeOf()
+ expectTypeOf(product.price).toEqualTypeOf()
+
+ expectTypeOf(ProductRoute.useParams()).toEqualTypeOf<{
+ productId: string
+ }>()
+ expectTypeOf(ProductRoute.useSearch()).toEqualTypeOf<{
+ tab: 'specs' | 'reviews'
+ }>()
+ expectTypeOf(ProductRoute.useRouteContext()).toEqualTypeOf<{
+ productsApi: ProductsApi
+ }>()
+ })
+
+ test('the module root requires its router context', () => {
+ expectTypeOf(ProductsRootRoute.types.routerContext).toEqualTypeOf<{
+ productsApi: ProductsApi
+ }>()
+ })
+})
+
+describe('scoped path-based APIs', () => {
+ test('Link takes module-local paths only', () => {
+ ;
+ ;
+ ;
+ // @ts-expect-error unknown module-local path
+ ;
+ // @ts-expect-error final application paths are not module-local paths
+ ;
+ // @ts-expect-error missing params
+ ;
+ // @ts-expect-error required search input is missing
+ ;
+ ;
+ })
+
+ test('useNavigate, redirect and linkOptions use the module router', () => {
+ const navigate = productsUseNavigate()
+ navigate({ to: '/$productId', params: { productId: '1' } })
+ // @ts-expect-error unknown module-local path
+ navigate({ to: '/nope' })
+
+ productsRedirect({ to: '/compare', search: { ids: [] } })
+ // @ts-expect-error required search input is missing
+ productsRedirect({ to: '/compare' })
+
+ productsLinkOptions({ to: '/$productId', params: { productId: '1' } })
+ // @ts-expect-error unknown module-local path
+ productsLinkOptions({ to: '/nope' })
+ })
+
+ test('the scoped router view navigates in module coordinates', () => {
+ const router = productsUseRouter()
+ expectTypeOf(router).toEqualTypeOf>()
+ router.navigate({ to: '/compare', search: { ids: ['1'] } })
+ // @ts-expect-error unknown module-local path
+ router.navigate({ to: '/nope' })
+ })
+
+ test('Route.Link and Route.useNavigate are module-local', () => {
+ ;
+ ;
+ // @ts-expect-error unknown module-local path
+ ;
+ const navigate = ProductRoute.useNavigate()
+ navigate({ to: '/compare', search: { ids: [] } })
+ // @ts-expect-error unknown module-local path
+ navigate({ to: '/nope' })
+ })
+})
+
+describe('scoped id-based APIs', () => {
+ test('getRouteApi and hooks take qualified ids', () => {
+ const product = productsGetRouteApi(
+ '@route-modules/products:/$productId',
+ ).useLoaderData()
+ expectTypeOf(product).toEqualTypeOf()
+ expectTypeOf(
+ productsUseLoaderData({ from: '@route-modules/products:/$productId' }),
+ ).toEqualTypeOf()
+ // @ts-expect-error unknown qualified id
+ productsGetRouteApi('@route-modules/products:/nope')
+ // @ts-expect-error module-local paths are not route ids
+ productsGetRouteApi('/$productId')
+ })
+})
+
+describe('a module that uses another module', () => {
+ test('the namespace links into the used module', () => {
+ ;
+ // @ts-expect-error account paths are not products paths
+ ;
+ ;
+ // @ts-expect-error products paths are not account paths
+ ;
+ })
+
+ test('both modules own "/" without colliding', () => {
+ ;
+ ;
+ })
+
+ test('used module routes are visible by qualified id', () => {
+ expectTypeOf(
+ accountGetRouteApi('@route-modules/products:/$productId').useLoaderData(),
+ ).toEqualTypeOf()
+ expectTypeOf(
+ accountGetRouteApi(
+ '@route-modules/account:/orders/$orderId',
+ ).useLoaderData(),
+ ).toEqualTypeOf<{ orderId: string; productId: string }>()
+ })
+})
+
+describe('a module mounted under path params', () => {
+ test('the actual generated host namespace takes host and module params', () => {
+ ;
+ ;
+ // @ts-expect-error the host parameter is missing
+ ;
+ // @ts-expect-error a route without local params still needs host params
+ ;
+ hostedTeam.linkOptions({ to: '/', params: { orgId: 'acme' } })
+ })
+
+ test('the published module-local API does not require host params', () => {
+ ;
+ ;
+ })
+})
+
+describe('the application', () => {
+ type AppRouter = ReturnType
+
+ test('addresses its own routes by path and module routes by id', () => {
+ ;
+ to="/orgs/$orgId"
+ params={{ orgId: 'acme' }}
+ />
+ ;
+ // @ts-expect-error module routes are not addressed by final path
+ to="/shop/products/$productId"
+ />
+ expectTypeOf(
+ useMatch({
+ from: '@route-modules/products:/$productId',
+ }).loaderData,
+ ).toEqualTypeOf()
+ })
+})
diff --git a/e2e/react-router/route-modules/packages/web/type-tests/scope-contracts.tsx b/e2e/react-router/route-modules/packages/web/type-tests/scope-contracts.tsx
new file mode 100644
index 0000000000..7ce5a914ef
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/type-tests/scope-contracts.tsx
@@ -0,0 +1,96 @@
+import * as React from 'react'
+import { expectTypeOf, test } from 'vitest'
+import { orgSettings, personSettings } from '../src/routeScope.gen'
+import * as settings from '@route-modules/settings/scope'
+
+test('reusable options preserve their installation through spreads and arrays', () => {
+ const user = personSettings.linkOptions({
+ to: '/members',
+ params: () => ({ personId: 'u1', orgId: '7' }),
+ })
+ expectTypeOf(
+ user._module,
+ ).toEqualTypeOf<'@route-modules/settings#personSettings'>()
+ const same =
+ const { _module, ...neutral } = user
+ const compatiblePathsAndParams =
+ void compatiblePathsAndParams
+ void _module
+ // @ts-expect-error An explicit sibling installation is a conflicting scope.
+ const different =
+ // @ts-expect-error Rewrapping must not erase the conflicting scope.
+ orgSettings.linkOptions({ ...user })
+ // @ts-expect-error Arrays preserve each entry's destination scope.
+ orgSettings.linkOptions([user])
+ // @ts-expect-error Redirects enforce the same receiving-scope contract.
+ orgSettings.redirect(user)
+ orgSettings.linkOptions({
+ to: '/members',
+ params: { orgId: '7' },
+ // @ts-expect-error A mask cannot silently retarget another installation's options.
+ mask: user,
+ })
+ // @ts-expect-error Hook defaults must retain and check a reusable scope stamp.
+ orgSettings.useNavigate({ ...user, from: '/profile' })
+ // @ts-expect-error The callback checks the same destination stamp.
+ orgSettings.useNavigate()(user)
+ void same
+ void different
+})
+
+test('module-typed helper targets only known route IDs', () => {
+ settings.notFound({ routeId: '@route-modules/settings:' })
+ settings.notFound()
+ // @ts-expect-error This route is not declared by the module.
+ settings.notFound({ routeId: '@route-modules/settings:/absent' })
+})
+
+test('blocker locations describe the entire application and raw URL values', () => {
+ settings.useBlocker({
+ shouldBlockFn: ({ current, next }) => {
+ expectTypeOf(current.routeId).toEqualTypeOf()
+ expectTypeOf(next.fullPath).toEqualTypeOf()
+ expectTypeOf(next.params).toEqualTypeOf<
+ Record
+ >()
+ expectTypeOf(next.search).toEqualTypeOf>()
+ return false
+ },
+ })
+})
+
+test('match selectors expose foreign data and the generated guard restores known data', () => {
+ settings.useMatch({
+ strict: false,
+ select: (match) => {
+ expectTypeOf(match.context).toBeUnknown()
+ expectTypeOf(match.loaderData).toBeUnknown()
+ return match.routeId
+ },
+ })
+ settings.useMatches({
+ select: (matches) => {
+ expectTypeOf(matches[0]!.context).toBeUnknown()
+ for (const match of matches) {
+ if (
+ settings.isScopedMatch(match) &&
+ match.localRouteId === '@route-modules/settings:/members'
+ ) {
+ expectTypeOf(match.loaderData).toEqualTypeOf<
+ { label: 'members' } | undefined
+ >()
+ expectTypeOf(match.fullPath).toEqualTypeOf()
+ }
+ }
+ return matches.length
+ },
+ })
+})
+
+test('MatchRoute accepts only the scope paths in JSX', () => {
+ const own =
+ // @ts-expect-error This path is not a module route.
+ const foreign =
+ void own
+ void foreign
+})
diff --git a/e2e/react-router/route-modules/packages/web/type-tests/validation-aliases.tsx b/e2e/react-router/route-modules/packages/web/type-tests/validation-aliases.tsx
new file mode 100644
index 0000000000..34bc1dec8d
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/type-tests/validation-aliases.tsx
@@ -0,0 +1,110 @@
+import { expectTypeOf, test } from 'vitest'
+import type { orgSettings } from '../src/routeScope.gen'
+
+test('every generated validation alias preserves its namespace contract', () => {
+ type Options = { to: '/profile'; params: { orgId: '7' } }
+ const options: Options = { to: '/profile', params: { orgId: '7' } }
+ const link: orgSettings.ValidateLinkOptions = options
+ const links: orgSettings.ValidateLinkOptionsArray = [
+ options,
+ ]
+ const navigate: orgSettings.ValidateNavigateOptions = options
+ const navigations: orgSettings.ValidateNavigateOptionsArray<
+ readonly [Options]
+ > = [options]
+ const redirect: orgSettings.ValidateRedirectOptions = options
+ const redirects: orgSettings.ValidateRedirectOptionsArray<
+ readonly [Options]
+ > = [options]
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+
+ const from: orgSettings.ValidateFromPath<'/profile'> = '/profile'
+ const to: orgSettings.ValidateToPath<'/profile'> = '/profile'
+ const search: orgSettings.ValidateSearch<'/search'> = {
+ search: { query: 'hello' },
+ }
+ const params: orgSettings.ValidateParams<'/profile'> = {
+ params: { orgId: '7' },
+ }
+ const id: orgSettings.ValidateId<'@route-modules/settings:/profile'> =
+ '@route-modules/settings:/profile'
+ const useSearch: orgSettings.ValidateUseSearchOptions<{
+ from: '@route-modules/settings:/profile'
+ }> = { from: '@route-modules/settings:/profile' }
+ const useParams: orgSettings.ValidateUseParamsOptions<{
+ from: '@route-modules/settings:/profile'
+ }> = { from: '@route-modules/settings:/profile' }
+ void [from, to, search, params, id, useSearch, useParams]
+
+ const foreignPath = {
+ to: '/orgs/$orgId',
+ params: { orgId: '7' },
+ } as const
+ const foreignPaths = [foreignPath] as const
+ const foreignOrigin = { from: '/orgs/$orgId' } as const
+ const wrongSearch = { search: { query: 42 } }
+ const wrongParams = { params: { userId: 'u1' } }
+
+ // @ts-expect-error The validation alias is bound to this module's paths.
+ const invalidLink: orgSettings.ValidateLinkOptions =
+ foreignPath
+ // @ts-expect-error Tuple entries retain the generated scope.
+ const invalidLinks: orgSettings.ValidateLinkOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error Navigation wrappers cannot escape the module paths.
+ const invalidNavigate: orgSettings.ValidateNavigateOptions<
+ typeof foreignPath
+ > = foreignPath
+ // @ts-expect-error Every navigation array entry is checked.
+ const invalidNavigations: orgSettings.ValidateNavigateOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error Redirect wrappers retain module path validation.
+ const invalidRedirect: orgSettings.ValidateRedirectOptions<
+ typeof foreignPath
+ > = foreignPath
+ // @ts-expect-error Every redirect array entry is checked.
+ const invalidRedirects: orgSettings.ValidateRedirectOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error A route origin must be a path in the module.
+ const invalidFrom: orgSettings.ValidateFromPath<'/profile'> = '/orgs/$orgId'
+ // @ts-expect-error A destination must be a path in the module.
+ const invalidTo: orgSettings.ValidateToPath<'/profile'> = '/orgs/$orgId'
+ // @ts-expect-error Search validation follows the generated route schema.
+ const invalidSearch: orgSettings.ValidateSearch<'/search'> = wrongSearch
+ // @ts-expect-error The named installation requires its own host parameter.
+ const invalidParams: orgSettings.ValidateParams<'/profile'> = wrongParams
+ // @ts-expect-error A foreign route ID is not a module route.
+ const invalidId: orgSettings.ValidateId<'@route-modules/settings:/profile'> =
+ '/orgs/$orgId'
+ // @ts-expect-error Search selectors must name a route in this module.
+ const invalidUseSearch: orgSettings.ValidateUseSearchOptions<
+ typeof foreignOrigin
+ > = foreignOrigin
+ // @ts-expect-error Parameter selectors must name a route in this module.
+ const invalidUseParams: orgSettings.ValidateUseParamsOptions<
+ typeof foreignOrigin
+ > = foreignOrigin
+ void [
+ invalidLink,
+ invalidLinks,
+ invalidNavigate,
+ invalidNavigations,
+ invalidRedirect,
+ invalidRedirects,
+ invalidFrom,
+ invalidTo,
+ invalidSearch,
+ invalidParams,
+ invalidId,
+ invalidUseSearch,
+ invalidUseParams,
+ ]
+})
diff --git a/e2e/react-router/route-modules/packages/web/vite.config.ts b/e2e/react-router/route-modules/packages/web/vite.config.ts
new file mode 100644
index 0000000000..02d676f946
--- /dev/null
+++ b/e2e/react-router/route-modules/packages/web/vite.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
+import { tanstackRouter } from '@tanstack/router-plugin/vite'
+
+// The router plugin reads `tsr.config.json`, including the route modules this
+// application mounts.
+export default defineConfig({
+ plugins: [
+ tanstackRouter({ target: 'react', autoCodeSplitting: true }),
+ react(),
+ ],
+})
diff --git a/e2e/react-router/route-modules/playwright.config.ts b/e2e/react-router/route-modules/playwright.config.ts
new file mode 100644
index 0000000000..7c30ba6f79
--- /dev/null
+++ b/e2e/react-router/route-modules/playwright.config.ts
@@ -0,0 +1,29 @@
+import { defineConfig, devices } from '@playwright/test'
+import { appServerReady } from '@tanstack/router-e2e-utils'
+
+const PORT = Number(process.env.E2E_APP_PORT ?? 0)
+const baseURL = `http://localhost:${PORT}`
+// Publish the route modules, then build and serve the application that mounts
+// them. Only the application is bundled; modules are compiled from source.
+const command = `node scripts/prepare.mjs && pnpm --filter @route-modules/web build && pnpm --filter @route-modules/web exec vite preview --host 0.0.0.0 --port ${PORT}`
+
+export default defineConfig({
+ testDir: './e2e',
+ workers: 1,
+ reporter: [['line']],
+ use: {
+ baseURL,
+ },
+ webServer: {
+ command,
+ wait: appServerReady,
+ reuseExistingServer: false,
+ stdout: 'pipe',
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: { ...devices['Desktop Chrome'] },
+ },
+ ],
+})
diff --git a/e2e/react-router/route-modules/playwright.dev.config.ts b/e2e/react-router/route-modules/playwright.dev.config.ts
new file mode 100644
index 0000000000..a244db6ea7
--- /dev/null
+++ b/e2e/react-router/route-modules/playwright.dev.config.ts
@@ -0,0 +1,29 @@
+import { defineConfig, devices } from '@playwright/test'
+import { appServerReady } from '@tanstack/router-e2e-utils'
+
+const PORT = Number(process.env.E2E_APP_PORT ?? 0)
+const baseURL = `http://localhost:${PORT}`
+// Development: the application's dev server compiles module route files from
+// their packages, code-splits them and hot-updates them.
+const command = `node scripts/prepare.mjs && pnpm --filter @route-modules/web exec vite --host 0.0.0.0 --port ${PORT}`
+
+export default defineConfig({
+ testDir: './e2e-dev',
+ workers: 1,
+ reporter: [['line']],
+ use: {
+ baseURL,
+ },
+ webServer: {
+ command,
+ wait: appServerReady,
+ reuseExistingServer: false,
+ stdout: 'pipe',
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: { ...devices['Desktop Chrome'] },
+ },
+ ],
+})
diff --git a/e2e/react-router/route-modules/scripts/prepare.mjs b/e2e/react-router/route-modules/scripts/prepare.mjs
new file mode 100644
index 0000000000..20d431c48c
--- /dev/null
+++ b/e2e/react-router/route-modules/scripts/prepare.mjs
@@ -0,0 +1,49 @@
+// Generates routes and builds declarations in dependency order using the
+// fixture packages' ordinary TypeScript build.
+//
+// The modules list `@tanstack/router-core` as a dev dependency only because
+// the fixture links `@tanstack/react-router` from the workspace: TypeScript
+// names the types of a linked package's dependencies by their own package
+// name. Installed from a registry, the declarations name them through
+// `@tanstack/react-router`, the only router package modules need.
+import { spawnSync } from 'node:child_process'
+import { rmSync } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { Generator, getConfig } from '@tanstack/router-generator'
+
+const packages = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../packages',
+)
+
+const tsc = path.resolve(
+ packages,
+ '../../../../node_modules/.bin',
+ process.platform === 'win32' ? 'tsc.cmd' : 'tsc',
+)
+
+for (const name of [
+ 'products',
+ 'storefront',
+ 'account',
+ 'team',
+ 'settings',
+ 'billing',
+]) {
+ const root = path.join(packages, name)
+ const config = getConfig({ disableLogging: true }, root)
+ await new Generator({ config, root }).run()
+ rmSync(path.join(root, '.tanstack/types'), { recursive: true, force: true })
+ const result = spawnSync(
+ tsc,
+ ['-p', 'tsconfig.route-types.json', '--pretty', 'false'],
+ { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' },
+ )
+ if (result.error) {
+ throw result.error
+ }
+ if (result.status !== 0) {
+ process.exit(result.status ?? 1)
+ }
+}
diff --git a/e2e/react-router/route-modules/tests/generated-api-bundles.test.ts b/e2e/react-router/route-modules/tests/generated-api-bundles.test.ts
new file mode 100644
index 0000000000..2c451cea8d
--- /dev/null
+++ b/e2e/react-router/route-modules/tests/generated-api-bundles.test.ts
@@ -0,0 +1,446 @@
+import fs from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { realpathSync } from 'node:fs'
+import { spawnSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+import { brotliCompressSync, gzipSync } from 'node:zlib'
+import { afterEach, expect, test } from 'vitest'
+import { Generator, getConfig } from '@tanstack/router-generator'
+import { build } from 'vite'
+import solid from 'vite-plugin-solid'
+
+type Framework = 'react' | 'solid' | 'vue'
+const repository = fileURLToPath(new URL('../../../../', import.meta.url))
+const workspaces: Array = []
+const neutralEntry = `globalThis.__routeModuleBundleProbe = 'retained'`
+
+afterEach(async () => {
+ for (const workspace of workspaces.splice(0)) {
+ await fs.rm(workspace, { recursive: true, force: true })
+ }
+})
+
+async function write(file: string, source: string) {
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ await fs.writeFile(file, source)
+}
+
+async function link(root: string, name: string, target: string) {
+ const file = path.join(root, 'node_modules', name)
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ await fs.symlink(target, file, 'dir')
+}
+
+async function fixtures(framework: Framework) {
+ const workspace = realpathSync(
+ await fs.mkdtemp(path.join(os.tmpdir(), 'route-module-bundles-')),
+ )
+ workspaces.push(workspace)
+ // Third-party dependencies resolve exactly as in the installed workspace;
+ // framework imports below still go through their published package exports.
+ await fs.symlink(
+ path.join(repository, 'node_modules'),
+ path.join(workspace, 'node_modules'),
+ 'dir',
+ )
+ const routerPackage = `@tanstack/${framework}-router`
+ const startPackage = `@tanstack/${framework}-start`
+ const dependency = path.join(workspace, 'dependency')
+ const provider = path.join(workspace, 'provider')
+ const host = path.join(workspace, 'host')
+ for (const [root, name, isModule] of [
+ [dependency, '@bundle/dependency', true],
+ [provider, '@bundle/provider', true],
+ [host, '@bundle/host', false],
+ ] as const) {
+ await write(
+ path.join(root, 'package.json'),
+ JSON.stringify({
+ name,
+ type: 'module',
+ dependencies: {
+ [routerPackage]: '*',
+ ...(root === provider
+ ? { [startPackage]: '*', '@bundle/dependency': '*' }
+ : {}),
+ ...(root === host
+ ? { '@bundle/provider': '*', '@bundle/dependency': '*' }
+ : {}),
+ },
+ exports: {
+ './route-module': './src/routeModule.gen.ts',
+ './route-types': './src/routeContract.gen.ts',
+ },
+ ...(isModule
+ ? {
+ tanstack: {
+ router: {
+ module:
+ root === provider ? { uses: ['@bundle/dependency'] } : true,
+ },
+ },
+ }
+ : {}),
+ }),
+ )
+ await link(
+ root,
+ routerPackage,
+ path.join(repository, 'packages', `${framework}-router`),
+ )
+ if (root === provider) {
+ await link(
+ root,
+ startPackage,
+ path.join(repository, 'packages', `${framework}-start`),
+ )
+ }
+ await write(
+ path.join(root, 'src/routes/__root.tsx'),
+ isModule
+ ? `import { createModuleRoot } from '../routeScope.gen'
+${root === provider ? "export type {} from '../requirements'" : ''}
+export const Route = createModuleRoot()({})`
+ : `import { createRootRoute } from '${routerPackage}'
+export const Route = createRootRoute()`,
+ )
+ if (isModule) {
+ await write(
+ path.join(root, 'src/routes/page.tsx'),
+ `import { createFileRoute } from '../routeScope.gen'
+export const Route = createFileRoute('${name}:/page')({})`,
+ )
+ }
+ }
+ await link(provider, '@bundle/dependency', dependency)
+ await link(host, '@bundle/provider', provider)
+ await link(host, '@bundle/dependency', dependency)
+ await write(
+ path.join(provider, 'src/requirements.ts'),
+ `export type { StartModuleRequirements } from '${startPackage}'
+declare module '${startPackage}' {
+ interface StartModuleRequirements {
+ '@bundle/provider': { requestContext: { requiredByBundleFixture: string } }
+ }
+}`,
+ )
+ for (const root of [dependency, provider, host]) {
+ const config = getConfig(
+ {
+ target: framework,
+ disableLogging: true,
+ routesDirectory: './src/routes',
+ generatedRouteTree: './src/routeTree.gen.ts',
+ ...(root === host
+ ? {
+ routeModules: {
+ includes: [
+ { module: '@bundle/provider', at: '/provider' },
+ { module: '@bundle/dependency', at: '/dependency' },
+ ],
+ },
+ }
+ : {}),
+ },
+ root,
+ )
+ await new Generator({ root, config }).run()
+ }
+ return { workspace, provider, host, routerPackage, startPackage }
+}
+
+interface Bundle {
+ source: string
+ code: string
+ moduleIds: Array
+ raw: number
+ gzip: number
+ brotli: number
+}
+
+async function bundle(
+ framework: Framework,
+ root: string,
+ name: string,
+ entry: string,
+): Promise {
+ const directory = path.join(root, 'bundle-cases', name)
+ const input = path.join(directory, 'index.html')
+ await write(path.join(directory, 'entry.ts'), entry)
+ await write(
+ input,
+ '',
+ )
+ const output: Array = []
+ const moduleIds = new Set()
+ for (const minify of [false, true]) {
+ const result = await build({
+ root: directory,
+ configFile: false,
+ mode: 'production',
+ plugins: framework === 'solid' ? [solid({ dev: false })] : [],
+ resolve: {
+ conditions: [
+ ...(framework === 'solid' ? ['solid'] : []),
+ 'module',
+ 'browser',
+ 'production',
+ ],
+ },
+ logLevel: 'silent',
+ define: { 'process.env.NODE_ENV': JSON.stringify('production') },
+ build: {
+ write: false,
+ minify,
+ sourcemap: false,
+ rolldownOptions: { input },
+ },
+ })
+ if (!('output' in result)) {
+ throw new Error('Expected a single application bundle')
+ }
+ for (const chunk of result.output) {
+ if (chunk.type === 'chunk') {
+ for (const id of Object.keys(chunk.modules)) {
+ moduleIds.add(id.replaceAll('\\', '/'))
+ }
+ }
+ }
+ output.push(
+ result.output
+ .filter((file) => file.type === 'chunk')
+ .map((file) => file.code)
+ .join('\n'),
+ )
+ }
+ const code = output[1]!
+ return {
+ source: output[0]!,
+ code,
+ moduleIds: [...moduleIds],
+ raw: Buffer.byteLength(code),
+ gzip: gzipSync(code).byteLength,
+ brotli: brotliCompressSync(code).byteLength,
+ }
+}
+
+const scopedApis = [
+ 'Link',
+ 'CreateLink',
+ 'LinkOptions',
+ 'Navigate',
+ 'UseNavigate',
+ 'Redirect',
+ 'MatchRoute',
+ 'UseMatchRoute',
+ 'UseRouter',
+ 'GetRouteApi',
+ 'UseMatch',
+ 'UseMatches',
+ 'UseParentMatches',
+ 'UseChildMatches',
+ 'UseLoaderData',
+ 'UseLoaderDeps',
+ 'UseSearch',
+ 'UseParams',
+ 'UseRouteContext',
+ 'UseLocation',
+ 'UseRouterState',
+ 'UseLinkProps',
+ 'UseBlocker',
+ 'NotFound',
+]
+
+function expectIndependentApi(result: Bundle, retained?: string) {
+ for (const api of scopedApis) {
+ if (api !== retained) {
+ expect(result.source).not.toMatch(
+ new RegExp(`\\bfunction\\s+bindRouteScope${api}\\b`),
+ )
+ }
+ }
+}
+
+function sizes(bundle: Bundle) {
+ return { raw: bundle.raw, gzip: bundle.gzip, brotli: bundle.brotli }
+}
+
+test.each(['react', 'solid', 'vue'] as const)(
+ '%s generated APIs and static namespaces discard unused initializers',
+ async (framework) => {
+ const { provider, host, routerPackage, startPackage } =
+ await fixtures(framework)
+ const own = JSON.stringify(path.join(provider, 'src/routeScope.gen.ts'))
+ const namespaces = JSON.stringify(path.join(host, 'src/routeScope.gen.ts'))
+ const results: Record> = {}
+ const measure = async (name: string, entry: string) => {
+ const result = await bundle(framework, provider, name, entry)
+ results[name] = sizes(result)
+ return result
+ }
+ const neutral = await measure('neutral', neutralEntry)
+ for (const [name, entry] of [
+ ['unused-own-scope', `import ${own}; ${neutralEntry}`],
+ ['unused-namespaces', `import ${namespaces}; ${neutralEntry}`],
+ [
+ 'type-only-validator',
+ `import type { ValidateLinkOptions } from ${own}; ${neutralEntry}`,
+ ],
+ [
+ 'type-only-requirements',
+ `import ${JSON.stringify(path.join(provider, 'src/requirements.ts'))}; ${neutralEntry}`,
+ ],
+ ]) {
+ const result = await measure(name!, entry!)
+ expect(result.code).toBe(neutral.code)
+ }
+
+ // Import the direct API first in both cases to stabilize bundler naming.
+ // The second reference proves the generated alias adds no runtime wrapper.
+ const directFactory = await measure(
+ 'framework-file-factory',
+ `import { createFileRoute } from '${routerPackage}'; globalThis.__routeModuleBundleProbe = [createFileRoute, createFileRoute]`,
+ )
+ const scopedFactory = await measure(
+ 'generated-file-factory',
+ `import { createFileRoute } from '${routerPackage}'; import { createFileRoute as scoped } from ${own}; globalThis.__routeModuleBundleProbe = [createFileRoute, scoped]`,
+ )
+ expectIndependentApi(scopedFactory)
+ expect(scopedFactory.source).not.toContain('@bundle/provider')
+ expect(sizes(scopedFactory)).toEqual(sizes(directFactory))
+ const moduleRootFactory = await measure(
+ 'generated-module-root',
+ `import { createModuleRoot } from ${own}; globalThis.__routeModuleBundleProbe = createModuleRoot`,
+ )
+ expectIndependentApi(moduleRootFactory)
+ expect(moduleRootFactory.source).not.toMatch(
+ /\bfunction\s+createFileRoute\b/,
+ )
+
+ const ownOptions = await measure(
+ 'own-link-options',
+ `import { linkOptions } from ${own}; globalThis.__routeModuleBundleProbe = linkOptions({ to: '/page' })`,
+ )
+ const namespaceOptions = await measure(
+ 'namespace-link-options',
+ `import { provider } from ${namespaces}; globalThis.__routeModuleBundleProbe = provider.linkOptions({ to: '/page' })`,
+ )
+ expectIndependentApi(ownOptions, 'LinkOptions')
+ expectIndependentApi(namespaceOptions, 'LinkOptions')
+ expect(sizes(namespaceOptions)).toEqual(sizes(ownOptions))
+
+ for (const [api, suffix] of [
+ ['Link', 'Link'],
+ ['Navigate', 'Navigate'],
+ ['getRouteApi', 'GetRouteApi'],
+ ['useRouter', 'UseRouter'],
+ ['useLinkProps', 'UseLinkProps'],
+ ['useBlocker', 'UseBlocker'],
+ ['notFound', 'NotFound'],
+ ]) {
+ const result = await measure(
+ api!,
+ `import { ${api} } from ${own}; globalThis.__routeModuleBundleProbe = ${api}`,
+ )
+ expectIndependentApi(result, suffix)
+ if (framework === 'solid' && api === 'Link') {
+ // Real Solid applications select source exports and compile their JSX.
+ expect(result.moduleIds).toContain(
+ path
+ .join(
+ repository,
+ 'packages/solid-router/dist/source/routeModule.jsx',
+ )
+ .replaceAll('\\', '/'),
+ )
+ }
+ const namespace = await measure(
+ `namespace-${api}`,
+ `import { provider } from ${namespaces}; globalThis.__routeModuleBundleProbe = provider.${api}`,
+ )
+ expectIndependentApi(namespace, suffix)
+ expect(sizes(namespace)).toEqual(sizes(result))
+ }
+ for (const api of ['createServerFn', 'createMiddleware']) {
+ const direct = await measure(
+ `framework-${api}`,
+ `import { ${api} } from '${startPackage}'; globalThis.__routeModuleBundleProbe = [${api}, ${api}]`,
+ )
+ const generated = await measure(
+ `generated-${api}`,
+ `import { ${api} } from '${startPackage}'; import { ${api} as scoped } from ${own}; globalThis.__routeModuleBundleProbe = [${api}, scoped]`,
+ )
+ expectIndependentApi(generated)
+ expect(sizes(generated)).toEqual(sizes(direct))
+ }
+ const fragmentFactory = await measure(
+ 'createStartModule',
+ `import { createStartModule } from ${own}; globalThis.__routeModuleBundleProbe = createStartModule`,
+ )
+ expectIndependentApi(fragmentFactory)
+ expect(fragmentFactory.source).not.toContain('requiredByBundleFixture')
+
+ // Keep real production-byte evidence in the test log for before/after
+ // comparison; assertion builds include all runtime dependencies, no externals.
+ console.info(JSON.stringify({ generatedApiBundles: framework, results }))
+ },
+)
+
+test.each(['react', 'solid', 'vue'] as const)(
+ '%s requirements augmentation emits declarations without runtime imports',
+ async (framework) => {
+ const { provider } = await fixtures(framework)
+ await write(
+ path.join(provider, 'tsconfig.requirements.json'),
+ JSON.stringify({
+ compilerOptions: {
+ target: 'ES2022',
+ module: 'ESNext',
+ moduleResolution: 'Bundler',
+ strict: true,
+ skipLibCheck: false,
+ declaration: true,
+ rootDir: './src',
+ outDir: './emitted-requirements',
+ types: ['node'],
+ },
+ files: ['src/requirements.ts'],
+ }),
+ )
+ const result = spawnSync(
+ process.execPath,
+ [
+ path.join(repository, 'node_modules/typescript59/lib/tsc.js'),
+ '--pretty',
+ 'false',
+ '-p',
+ path.join(provider, 'tsconfig.requirements.json'),
+ ],
+ { encoding: 'utf8' },
+ )
+ if (result.error) {
+ throw result.error
+ }
+ expect({
+ status: result.status,
+ diagnostics: result.stdout + result.stderr,
+ }).toEqual({ status: 0, diagnostics: '' })
+ expect(
+ (
+ await fs.readFile(
+ path.join(provider, 'emitted-requirements/requirements.js'),
+ 'utf8',
+ )
+ ).trim(),
+ ).toBe('export {};')
+ const declaration = await fs.readFile(
+ path.join(provider, 'emitted-requirements/requirements.d.ts'),
+ 'utf8',
+ )
+ expect(declaration).toContain(
+ `declare module '@tanstack/${framework}-start'`,
+ )
+ expect(declaration).toContain('requiredByBundleFixture')
+ },
+)
diff --git a/e2e/react-router/route-modules/tests/generated-scope-cache.test.ts b/e2e/react-router/route-modules/tests/generated-scope-cache.test.ts
new file mode 100644
index 0000000000..91244879b2
--- /dev/null
+++ b/e2e/react-router/route-modules/tests/generated-scope-cache.test.ts
@@ -0,0 +1,114 @@
+import { execFileSync } from 'node:child_process'
+import { symlinkSync } from 'node:fs'
+import { pathToFileURL } from 'node:url'
+import { expect, test } from 'vitest'
+import { build } from 'vite'
+import { Workspace } from './workspace'
+
+test('a generated package named constructor gets a working scoped router', async () => {
+ const ws = new Workspace(['settings', 'web'])
+ try {
+ // A valid unscoped package name must work even when it is also a property
+ // of Object.prototype. Generate the provider and host exactly as packages do.
+ ws.edit('settings', 'package.json', (source) => {
+ const pkg = JSON.parse(source)
+ pkg.name = 'constructor'
+ return JSON.stringify(pkg)
+ })
+ ws.remove('settings', 'src')
+ ws.write(
+ 'settings',
+ 'src/routes/__root.tsx',
+ `import { createModuleRoot } from '../routeScope.gen'
+export const Route = createModuleRoot()({})
+`,
+ )
+ ws.write(
+ 'settings',
+ 'src/routes/profile.tsx',
+ `import { createFileRoute } from '../routeScope.gen'
+export const Route = createFileRoute('constructor:/profile')({})
+`,
+ )
+
+ ws.edit('web', 'package.json', (source) => {
+ const pkg = JSON.parse(source)
+ for (const dependency of Object.keys(pkg.dependencies)) {
+ if (dependency.startsWith('@route-modules/')) {
+ delete pkg.dependencies[dependency]
+ }
+ }
+ pkg.dependencies.constructor = 'workspace:*'
+ return JSON.stringify(pkg)
+ })
+ symlinkSync(
+ ws.pkg('settings'),
+ ws.file('web', 'node_modules/constructor'),
+ 'dir',
+ )
+ ws.remove('web', 'src')
+ ws.write(
+ 'web',
+ 'tsr.config.json',
+ JSON.stringify({
+ routeModules: {
+ includes: [{ module: 'constructor', at: '/settings' }],
+ },
+ }),
+ )
+ ws.write(
+ 'web',
+ 'src/routes/__root.tsx',
+ `import { createRootRoute } from '@tanstack/react-router'
+export const Route = createRootRoute()
+`,
+ )
+ ws.write(
+ 'web',
+ 'src/probe.tsx',
+ `import * as React from 'react'
+import { renderToString } from 'react-dom/server'
+import { RouterContextProvider, createMemoryHistory, createRouter } from '@tanstack/react-router'
+import { useRouter } from 'constructor/scope'
+import { routeTree } from './routeTree.gen'
+
+export async function render() {
+ const router = createRouter({
+ routeTree,
+ history: createMemoryHistory({ initialEntries: ['/settings/profile'] }),
+ isServer: true,
+ })
+ await router.load()
+ function Observer() {
+ return {useRouter().buildLocation({ to: '/profile' }).href}
+ }
+ return renderToString( )
+}
+`,
+ )
+ await ws.buildGraph(['settings', 'web'], ['settings'])
+ await build({
+ root: ws.pkg('web'),
+ configFile: false,
+ logLevel: 'silent',
+ ssr: { noExternal: ['constructor'] },
+ build: {
+ ssr: ws.file('web', 'src/probe.tsx'),
+ outDir: ws.file('web', 'dist'),
+ rolldownOptions: { output: { entryFileNames: 'probe.mjs' } },
+ },
+ })
+ const output = execFileSync(
+ process.execPath,
+ [
+ '--input-type=module',
+ '--eval',
+ `import { render } from ${JSON.stringify(pathToFileURL(ws.file('web', 'dist/probe.mjs')).href)}; console.log(JSON.stringify(await render()));`,
+ ],
+ { cwd: ws.pkg('web'), encoding: 'utf8' },
+ )
+ expect(JSON.parse(output)).toBe('/settings/profile ')
+ } finally {
+ ws.dispose()
+ }
+})
diff --git a/e2e/react-router/route-modules/tests/host-context-contracts.test.ts b/e2e/react-router/route-modules/tests/host-context-contracts.test.ts
new file mode 100644
index 0000000000..bcf02dd04c
--- /dev/null
+++ b/e2e/react-router/route-modules/tests/host-context-contracts.test.ts
@@ -0,0 +1,52 @@
+import { afterEach, expect, test } from 'vitest'
+import { Workspace, errorsIn } from './workspace'
+
+let workspace: Workspace | undefined
+
+afterEach(() => {
+ workspace?.dispose()
+ workspace = undefined
+})
+
+test('generated mounts reject incompatible context and required host search', async () => {
+ const ws = (workspace = new Workspace())
+ const modules = [
+ 'products',
+ 'storefront',
+ 'account',
+ 'team',
+ 'settings',
+ 'billing',
+ ]
+ await ws.buildGraph([...modules, 'web'], modules)
+ const originalAuthentication = ws.read('web', 'src/routes/_authenticated.tsx')
+ ws.edit('web', 'src/routes/_authenticated.tsx', (source) => {
+ expect(source).toContain("user: { id: 'u-1' }")
+ return source.replace("user: { id: 'u-1' }", "user: 'invalid-context'")
+ })
+ const incompatible = await ws.check('web')
+ expect(incompatible.ok).toBe(false)
+ expect(
+ errorsIn(incompatible.diagnostics, 'src/routeTree.gen.ts').join('\n'),
+ ).toMatch(/compatible types/)
+
+ ws.write('web', 'src/routes/_authenticated.tsx', originalAuthentication)
+ const originalOrganization = ws.read('web', 'src/routes/orgs.$orgId.tsx')
+ ws.edit('web', 'src/routes/orgs.$orgId.tsx', (source) => {
+ expect(source).toContain(' beforeLoad:')
+ return source.replace(
+ ' beforeLoad:',
+ ' validateSearch: (search: { region: string }) => search,\n beforeLoad:',
+ )
+ })
+ const requiredSearch = await ws.check('web')
+ expect(requiredSearch.ok).toBe(false)
+ expect(
+ errorsIn(requiredSearch.diagnostics, 'src/routeTree.gen.ts').join('\n'),
+ ).toMatch(/requires search params/)
+
+ ws.write('web', 'src/routes/orgs.$orgId.tsx', originalOrganization)
+ const valid = await ws.check('web')
+ expect(valid.diagnostics).toEqual([])
+ expect(valid.ok).toBe(true)
+})
diff --git a/e2e/react-router/route-modules/tests/host-parameter-contracts.test.ts b/e2e/react-router/route-modules/tests/host-parameter-contracts.test.ts
new file mode 100644
index 0000000000..416c018105
--- /dev/null
+++ b/e2e/react-router/route-modules/tests/host-parameter-contracts.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, expect, test } from 'vitest'
+import { Workspace, errorsIn } from './workspace'
+
+let workspace: Workspace | undefined
+
+afterEach(() => {
+ workspace?.dispose()
+ workspace = undefined
+})
+
+test('generated mounts reject a parsed host key overwritten by module descendants', async () => {
+ const ws = (workspace = new Workspace())
+ ws.write(
+ 'settings',
+ 'src/routes/members.$memberId.tsx',
+ `import { createFileRoute } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/settings:/members/$memberId')({
+ loader: ({ params }) => ({ member: params.memberId }),
+})
+`,
+ )
+ ws.edit('web', 'src/routes/orgs.$orgId.tsx', (source) => {
+ expect(source).toContain(' beforeLoad:')
+ return source.replace(
+ ' beforeLoad:',
+ ` params: {
+ parse: ({ orgId }) => ({ orgId, memberId: 'host-member' }),
+ stringify: ({ orgId }) => ({ orgId }),
+ },
+ beforeLoad:`,
+ )
+ })
+ const modules = [
+ 'products',
+ 'storefront',
+ 'account',
+ 'team',
+ 'settings',
+ 'billing',
+ ]
+ await ws.buildGraph([...modules, 'web'], modules)
+ const collision = await ws.check('web')
+ expect(collision.ok).toBe(false)
+ expect(
+ errorsIn(collision.diagnostics, 'src/routeTree.gen.ts').join('\n'),
+ ).toMatch(/memberId/)
+
+ // A distinct parsed host key is valid. Type changes need only the normal
+ // consumer recheck; the route topology and generated mount are unchanged.
+ ws.edit('web', 'src/routes/orgs.$orgId.tsx', (source) =>
+ source.replace(
+ "memberId: 'host-member'",
+ "organizationMemberId: 'host-member'",
+ ),
+ )
+ for (const file of ['src/routes/__root.tsx', 'src/routes/index.tsx']) {
+ ws.edit('web', file, (source) =>
+ source.replaceAll(
+ /(params=\{\{ orgId: '[^']+') \}\}/g,
+ "$1, organizationMemberId: 'host-member' }}",
+ ),
+ )
+ }
+ ws.edit('web', 'src/profile-links.tsx', (source) =>
+ source.replace(
+ "params: { orgId: '7' }",
+ "params: { orgId: '7', organizationMemberId: 'host-member' }",
+ ),
+ )
+ const valid = await ws.check('web')
+ expect(valid.diagnostics).toEqual([])
+ expect(valid.ok).toBe(true)
+})
diff --git a/e2e/react-router/route-modules/tests/route-modules.test.ts b/e2e/react-router/route-modules/tests/route-modules.test.ts
new file mode 100644
index 0000000000..09397d91d4
--- /dev/null
+++ b/e2e/react-router/route-modules/tests/route-modules.test.ts
@@ -0,0 +1,511 @@
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, test } from 'vitest'
+import { Workspace, errorsIn } from './workspace'
+
+/**
+ * The fixture is a diamond:
+ *
+ * web ──► storefront ──► products (storefront mounts products)
+ * └────► account ─────► products (account only links to products)
+ *
+ * and modules web mounts below `/orgs/$orgId`, one of them twice:
+ *
+ * web ──► team
+ * ├────► settings (also below `/people/$personId`)
+ * └────► billing ─────► team (billing only links to team
+ * └───► settings and to the settings of its org)
+ *
+ * Every test copies the packages into a temporary workspace and drives the
+ * route generation through public APIs, followed by ordinary TypeScript
+ * declaration builds and source checks. JavaScript is never built.
+ */
+const order = [
+ 'products',
+ 'storefront',
+ 'account',
+ 'team',
+ 'settings',
+ 'billing',
+ 'web',
+]
+const modules = [
+ 'products',
+ 'storefront',
+ 'account',
+ 'team',
+ 'settings',
+ 'billing',
+]
+
+let ws: Workspace
+
+beforeEach(() => {
+ ws = new Workspace()
+})
+
+afterEach(() => {
+ ws.dispose()
+})
+
+async function expectChecksPass(...names: Array) {
+ for (const name of names) {
+ const result = await ws.check(name)
+ expect(result.diagnostics, `check of ${name}`).toEqual([])
+ expect(result.ok).toBe(true)
+ }
+}
+
+const renamedProductRoute = `import { createFileRoute } from '../routeScope.gen'
+import { productSearchSchema } from '../schemas'
+
+export const Route = createFileRoute('@route-modules/products:/$sku')({
+ validateSearch: productSearchSchema,
+ loader: ({ params, context }) => context.productsApi.getProduct(params.sku),
+ component: ProductPage,
+})
+
+function ProductPage() {
+ const product = Route.useLoaderData()
+ return {product.name}
+}
+`
+
+const brandsRoute = `import { createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@route-modules/products:/brands')({
+ component: () => Brands ,
+})
+`
+
+describe('clean checkout', () => {
+ test('generates, emits and checks the diamond from nothing', async () => {
+ for (const name of order) {
+ expect(ws.exists(name, 'src/routeTree.gen.ts')).toBe(false)
+ expect(ws.exists(name, '.tanstack')).toBe(false)
+ }
+
+ await ws.buildGraph(order, modules)
+ await expectChecksPass(...order)
+
+ expect(ws.log.some((entry) => entry.operation === 'build')).toBe(false)
+ for (const name of order) {
+ expect(ws.exists(name, 'dist')).toBe(false)
+ }
+ })
+
+ test('a module checks standalone, without any application', async () => {
+ const standalone = new Workspace(['products', 'account'])
+ try {
+ await standalone.buildGraph(
+ ['products', 'account'],
+ ['products', 'account'],
+ )
+ const result = await standalone.check('account')
+ expect(result.diagnostics).toEqual([])
+ } finally {
+ standalone.dispose()
+ }
+ })
+
+ test.each([
+ { name: 'default', header: undefined },
+ { name: 'custom', header: ['// Package license header'] },
+ { name: 'empty', header: [] },
+ ])(
+ 'emits portable client-view declarations with a $name header',
+ async ({ header }) => {
+ for (const name of ['products', 'storefront']) {
+ if (header !== undefined) {
+ ws.write(
+ name,
+ 'tsr.config.json',
+ JSON.stringify({ routeTreeFileHeader: header }),
+ )
+ }
+ await ws.generate(name)
+ // Both packages use an ordinary src-inclusive declaration build. The
+ // storefront's client view also references a mounted module's tree.
+ const emitted = await ws.emitTypes(name)
+ expect(emitted.diagnostics, `declarations of ${name}`).toEqual([])
+ expect(emitted.ok).toBe(true)
+ expect(
+ ws.exists(name, '.tanstack/types/src/routeTree.gen.client.d.ts'),
+ ).toBe(true)
+ }
+ await expectChecksPass('products', 'storefront')
+ },
+ )
+})
+
+describe('published declaration updates', () => {
+ test('a provider param rename reaches consumers through unchanged intermediate declarations', async () => {
+ await ws.buildGraph(order, modules)
+ const storefrontDeclarations = ws.snapshot('storefront', '.tanstack/types')
+ const storefrontSources = ws.snapshot('storefront', 'src')
+ const logBefore = ws.log.length
+
+ // Rename the product route param: products updates its own links,
+ // regenerates and re-emits.
+ ws.remove('products', 'src/routes/$productId.tsx')
+ ws.write('products', 'src/routes/$sku.tsx', renamedProductRoute)
+ ws.edit('products', 'src/routes/index.tsx', (source) =>
+ source
+ .replace('to="/$productId"', 'to="/$sku"')
+ .replace('{ productId: product.id }', '{ sku: product.id }'),
+ )
+ ws.edit('products', 'src/routes/legacy.tsx', (source) =>
+ source
+ .replace("to: '/$productId'", "to: '/$sku'")
+ .replace("productId: '42'", "sku: '42'"),
+ )
+ await ws.generate('products')
+ expect((await ws.emitTypes('products')).ok).toBe(true)
+
+ // Consumers only recheck their source.
+ const account = await ws.check('account')
+ expect(account.ok).toBe(false)
+ expect(errorsIn(account.diagnostics, 'src/routes/index.tsx')).not.toEqual(
+ [],
+ )
+ expect(
+ errorsIn(account.diagnostics, 'src/routes/orders.$orderId.tsx'),
+ ).not.toEqual([])
+
+ // The application reaches products only through storefront's contract,
+ // whose declarations were neither regenerated nor re-emitted.
+ const web = await ws.check('web')
+ expect(web.ok).toBe(false)
+ expect(
+ errorsIn(web.diagnostics, 'src/routes/index.tsx').join('\n'),
+ ).toMatch(/productId|\$productId/)
+ expect(ws.snapshot('storefront', '.tanstack/types')).toEqual(
+ storefrontDeclarations,
+ )
+ expect(ws.snapshot('storefront', 'src')).toEqual(storefrontSources)
+ expect(
+ ws.log
+ .slice(logBefore)
+ .filter((entry) => entry.pkg !== 'products')
+ .map((entry) => entry.operation),
+ ).toEqual(['check', 'check'])
+
+ // Updating the consumer links makes the graph valid again.
+ ws.edit('account', 'src/routes/index.tsx', (source) =>
+ source
+ .replace('to="/$productId"', 'to="/$sku"')
+ .replace("{ productId: 'last-viewed' }", "{ sku: 'last-viewed' }"),
+ )
+ ws.edit('account', 'src/routes/orders.$orderId.tsx', (source) =>
+ source
+ .replace(
+ "'@route-modules/products:/$productId'",
+ "'@route-modules/products:/$sku'",
+ )
+ .replace("to: '/$productId'", "to: '/$sku'")
+ .replace('{ productId: order.productId }', '{ sku: order.productId }'),
+ )
+ ws.edit('storefront', 'src/routes/index.tsx', (source) =>
+ source
+ .replace('to="/$productId"', 'to="/$sku"')
+ .replace("{ productId: 'featured' }", "{ sku: 'featured' }"),
+ )
+ ws.edit('web', 'src/routes/index.tsx', (source) =>
+ source
+ .replace(
+ "'@route-modules/products:/$productId'",
+ "'@route-modules/products:/$sku'",
+ )
+ .replace('to="/$productId"', 'to="/$sku"')
+ .replace("{ productId: 'home-pick' }", "{ sku: 'home-pick' }"),
+ )
+ await expectChecksPass('account', 'storefront', 'web')
+ })
+
+ test('route generation does not depend on declaration emits', async () => {
+ // Task runners cache generation by its inputs: emitting must not change
+ // what the next generation writes.
+ await ws.generate('products')
+ const manifest = ws.read('products', '.tanstack/route-module.json')
+ expect((await ws.emitTypes('products')).ok).toBe(true)
+ await ws.generate('products')
+ expect(ws.read('products', '.tanstack/route-module.json')).toBe(manifest)
+ })
+
+ test('a schema-only edit refreshes types without changing the topology', async () => {
+ await ws.buildGraph(order, modules)
+ const routeTree = ws.read('products', 'src/routeTree.gen.ts')
+ const { topologyToken } = ws.manifest('products')
+
+ // `tab` becomes a required search param; products updates its own link.
+ ws.edit('products', 'src/schemas.ts', (source) =>
+ source.replace(".default('specs')", ''),
+ )
+ ws.edit('products', 'src/routes/index.tsx', (source) =>
+ source.replace(
+ 'params={{ productId: product.id }}',
+ "params={{ productId: product.id }}\n search={{ tab: 'specs' }}",
+ ),
+ )
+ await ws.generate('products')
+ expect(ws.read('products', 'src/routeTree.gen.ts')).toBe(routeTree)
+ expect(ws.manifest('products').topologyToken).toBe(topologyToken)
+ expect((await ws.emitTypes('products')).ok).toBe(true)
+
+ // Navigations without `tab` now fail; the account link passes `tab`.
+ const web = await ws.check('web')
+ expect(errorsIn(web.diagnostics, 'src/routes/index.tsx')).not.toEqual([])
+ const storefront = await ws.check('storefront')
+ expect(
+ errorsIn(storefront.diagnostics, 'src/routes/index.tsx'),
+ ).not.toEqual([])
+ const account = await ws.check('account')
+ expect(errorsIn(account.diagnostics, 'src/routes/index.tsx')).toEqual([])
+ expect(
+ errorsIn(account.diagnostics, 'src/routes/orders.$orderId.tsx').join(
+ '\n',
+ ),
+ ).toMatch(/search/)
+ })
+
+ test('a deleted provider route fails the obsolete consumer link', async () => {
+ await ws.buildGraph(order, modules)
+
+ ws.remove('products', 'src/routes/compare.tsx')
+ await ws.generate('products')
+ expect(
+ ws.manifest('products').routes.map((route) => route.id),
+ ).not.toContain('@route-modules/products:/compare')
+ expect((await ws.emitTypes('products')).ok).toBe(true)
+ expect(
+ ws.exists('products', '.tanstack/types/src/routes/compare.d.ts'),
+ ).toBe(false)
+
+ const storefront = await ws.check('storefront')
+ expect(storefront.ok).toBe(false)
+ expect(
+ errorsIn(storefront.diagnostics, 'src/routes/index.tsx').join('\n'),
+ ).toMatch(/compare/)
+ })
+
+ test('a new provider route becomes visible to consumers', async () => {
+ await ws.buildGraph(order, modules)
+ ws.edit('web', 'src/routes/index.tsx', (source) =>
+ source.replace(
+ '',
+ 'Brands \n ',
+ ),
+ )
+ expect((await ws.check('web')).ok).toBe(false)
+
+ ws.write('products', 'src/routes/brands.tsx', brandsRoute)
+ await ws.generate('products')
+ expect((await ws.emitTypes('products')).ok).toBe(true)
+ await expectChecksPass('web')
+ })
+})
+
+describe('the declaration boundary', () => {
+ test('consumers load provider declarations, never provider sources', async () => {
+ await ws.buildGraph(order, modules)
+ const files = ws.listProgramFiles('account')
+ expect(
+ files.some((file) => file.includes('/products/.tanstack/types/')),
+ ).toBe(true)
+ expect(files.some((file) => file.includes('/products/src/'))).toBe(false)
+ })
+
+ test('consumers check against declarations only, without library skipping', async () => {
+ await ws.buildGraph(order, modules)
+ ws.remove('products', 'src')
+ ws.edit('account', 'tsconfig.json', (source) =>
+ source.replace('"skipLibCheck": true', '"skipLibCheck": false'),
+ )
+ await expectChecksPass('account')
+
+ // A missing declaration fails instead of falling back to sources.
+ ws.remove('products', '.tanstack/types/src/api.d.ts')
+ const result = await ws.check('account')
+ expect(result.ok).toBe(false)
+ expect(result.diagnostics.join('\n')).toMatch(/\.\/api/)
+ })
+
+ test('module types stay precise across the boundary', async () => {
+ await ws.buildGraph(order, modules)
+ ws.write(
+ 'account',
+ 'src/type-assertions.tsx',
+ `import { Route as AccountIndexRoute } from './routes/index'
+import { getRouteApi, products } from './routeScope.gen'
+import type { Price, Product } from '@route-modules/products/api'
+
+type Equal =
+ (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2
+ ? true
+ : false
+type IsAny = 0 extends 1 & T ? true : false
+
+const productApi = getRouteApi('@route-modules/products:/$productId')
+
+export function useAssertions() {
+ const product = productApi.useLoaderData()
+ const loaderData: Equal = true
+ const notAny: IsAny = false
+ const brand: Equal = true
+
+ // Validated search output: \`tab\` has a default, so it is always set.
+ const search = productApi.useSearch()
+ const output: Equal = true
+
+ // Context the module root requires from its host.
+ const context = AccountIndexRoute.useRouteContext()
+ const user: Equal = true
+
+ return [loaderData, notAny, brand, output, user]
+}
+
+export const links = (
+ <>
+ {/* Navigation input: \`tab\` is optional. */}
+
+
+ {/* @ts-expect-error a required search input is missing */}
+
+
+ {/* Nested routing survives the boundary. */}
+
+
+
+
+ {/* @ts-expect-error pathless layout segments are not part of paths */}
+
+ {/* @ts-expect-error unknown module-local path */}
+
+ >
+)
+`,
+ )
+ await expectChecksPass('account')
+ })
+
+ test('declaration maps lead to the module sources from any output directory', async () => {
+ ws.edit('products', 'tsconfig.route-types.json', (source) =>
+ source.replace('".tanstack/types"', '"route-types"'),
+ )
+ ws.edit('products', 'package.json', (source) =>
+ source.replaceAll('./.tanstack/types/', './route-types/'),
+ )
+ await ws.buildGraph(order, modules)
+ await expectChecksPass('account')
+
+ const map = 'route-types/src/routes/$productId.d.ts.map'
+ const { sources } = JSON.parse(ws.read('products', map))
+ expect(sources).toHaveLength(1)
+ expect(
+ path.resolve(path.dirname(ws.file('products', map)), sources[0]),
+ ).toBe(ws.file('products', 'src/routes/$productId.tsx'))
+ })
+})
+
+describe('composition', () => {
+ test('a missing provider fails the application generation', async () => {
+ await ws.buildGraph(modules, modules)
+ ws.edit('web', 'tsr.config.json', (source) =>
+ source.replace(
+ '{ "module": "@route-modules/storefront", "at": "/shop" },',
+ '',
+ ),
+ )
+ await expect(ws.generate('web')).rejects.toThrow(
+ /uses routes of "@route-modules\/products", which is not installed/,
+ )
+ })
+
+ test('a host route without the required context fails the check', async () => {
+ await ws.buildGraph(modules, modules)
+ // Mount account at the root, which provides no `user`.
+ ws.edit('web', 'tsr.config.json', (source) =>
+ source.replace('"parent": "/_authenticated",', ''),
+ )
+ ws.remove('web', 'src/routes/_authenticated.tsx')
+ await ws.generate('web')
+ const result = await ws.check('web')
+ expect(result.ok).toBe(false)
+ expect(
+ errorsIn(result.diagnostics, 'src/routeTree.gen.ts').join('\n'),
+ ).toMatch(/requires router context 'user'/)
+ })
+
+ test('mounting a module twice is rejected', async () => {
+ await ws.buildGraph(modules, modules)
+ ws.edit('web', 'tsr.config.json', (source) =>
+ source.replace(
+ '"includes": [',
+ '"includes": [\n { "module": "@route-modules/products", "at": "/p" },',
+ ),
+ )
+ await expect(ws.generate('web')).rejects.toThrow(/installed twice/)
+ })
+
+ test('a mount path with path params is rejected', async () => {
+ await ws.buildGraph(modules, modules)
+ ws.edit('web', 'tsr.config.json', (source) =>
+ source.replace('"at": "/shop"', '"at": "/$tenant"'),
+ )
+ await expect(ws.generate('web')).rejects.toThrow(/static path/)
+ })
+
+ test('two applications compose the same modules independently', async () => {
+ ws.addPackage('admin', 'web')
+ ws.edit('admin', 'package.json', (source) =>
+ source.replace('@route-modules/web', '@route-modules/admin'),
+ )
+ ws.edit('admin', 'tsr.config.json', (source) =>
+ source.replace('"at": "/shop"', '"at": "/store"'),
+ )
+ await ws.buildGraph([...order, 'admin'], modules)
+ await expectChecksPass('web', 'admin')
+
+ const productsDeclarations = Object.keys(
+ ws.snapshot('products', '.tanstack/types'),
+ )
+ .map((file) => ws.read('products', `.tanstack/types/${file}`))
+ .join('\n')
+ expect(productsDeclarations).not.toMatch(/@route-modules\/(web|admin)/)
+ expect(productsDeclarations).not.toMatch(/interface Register\b/)
+ })
+})
+
+describe('mounting under path params', () => {
+ test('the application passes the path params above a module it mounts', async () => {
+ await ws.buildGraph(order, modules)
+ ws.edit('web', 'src/routes/index.tsx', (source) =>
+ source.replace(" params={{ orgId: 'acme' }}", ''),
+ )
+
+ const web = await ws.check('web')
+ // `/` has no params of its own: the host params make them required.
+ expect(
+ errorsIn(web.diagnostics, 'src/routes/index.tsx').join('\n'),
+ ).toMatch(/'params' is missing.*@route-modules\/team/)
+ })
+
+ test('a module that links into a module under path params is mounted below them', async () => {
+ await ws.buildGraph(order, modules)
+ ws.edit('web', 'tsr.config.json', (source) =>
+ source.replace(
+ `"module": "@route-modules/billing",
+ "parent": "/orgs/$orgId",`,
+ '"module": "@route-modules/billing",',
+ ),
+ )
+
+ await expect(ws.generate('web')).rejects.toThrow(
+ '"@route-modules/billing" links into "@route-modules/team", which is mounted below "/orgs/$orgId", but "@route-modules/billing" is mounted at "/billing"',
+ )
+ })
+})
diff --git a/e2e/react-router/route-modules/tests/workspace.ts b/e2e/react-router/route-modules/tests/workspace.ts
new file mode 100644
index 0000000000..32783d63f7
--- /dev/null
+++ b/e2e/react-router/route-modules/tests/workspace.ts
@@ -0,0 +1,287 @@
+import path from 'node:path'
+import os from 'node:os'
+import crypto from 'node:crypto'
+import { spawnSync } from 'node:child_process'
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ realpathSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import { cpSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import {
+ Generator,
+ getConfig,
+ readRouteModuleManifest,
+} from '@tanstack/router-generator'
+import type { RouteModuleManifest } from '@tanstack/router-generator'
+
+const here = path.dirname(fileURLToPath(import.meta.url))
+const fixtureRoot = path.resolve(here, '../packages')
+const repoRoot = path.resolve(here, '../../../..')
+/** The repository's TypeScript compiler (`tsc` of `@typescript/native`). */
+export const tsc = path.join(repoRoot, 'node_modules', '.bin', 'tsc')
+
+const workspaceScope = '@route-modules/'
+const generatedFile = /\.gen(?:\.[^.]+)?\.tsx?$/
+
+export type Operation = 'generate' | 'emit-types' | 'check' | 'build'
+
+export interface LoggedOperation {
+ operation: Operation
+ pkg: string
+ ok: boolean
+}
+
+function listDependencies(nodeModules: string): Array {
+ if (!existsSync(nodeModules)) {
+ return []
+ }
+ const entries: Array = []
+ for (const entry of readdirSync(nodeModules)) {
+ if (entry.startsWith('.')) {
+ continue
+ }
+ if (entry.startsWith('@')) {
+ for (const scoped of readdirSync(path.join(nodeModules, entry))) {
+ entries.push(`${entry}/${scoped}`)
+ }
+ } else {
+ entries.push(entry)
+ }
+ }
+ return entries
+}
+
+/**
+ * A copy of the fixture packages in a temporary directory. Workspace route
+ * modules are linked to their copies; every other dependency is linked to the
+ * package the repository installed, so the copy resolves like the original.
+ * Nothing generated or built is copied: every test starts from a clean
+ * checkout.
+ */
+export class Workspace {
+ readonly root: string
+ readonly log: Array = []
+
+ constructor(
+ packages: Array = [
+ 'products',
+ 'storefront',
+ 'account',
+ 'team',
+ 'settings',
+ 'billing',
+ 'web',
+ ],
+ ) {
+ this.root = realpathSync(
+ require_mkdtemp(path.join(os.tmpdir(), 'tsr-route-modules-')),
+ )
+ for (const name of packages) {
+ this.addPackage(name, name)
+ }
+ }
+
+ /** Copies fixture package `source` as `name` into the workspace. */
+ addPackage(name: string, source: string) {
+ const from = path.join(fixtureRoot, source)
+ const to = this.pkg(name)
+ cpSync(from, to, {
+ recursive: true,
+ filter: (file) =>
+ !file.includes(`${path.sep}node_modules`) &&
+ !file.includes(`${path.sep}.tanstack`) &&
+ !file.includes(`${path.sep}dist`) &&
+ !generatedFile.test(file),
+ })
+ for (const dependency of listDependencies(
+ path.join(from, 'node_modules'),
+ )) {
+ const link = path.join(to, 'node_modules', dependency)
+ mkdirSync(path.dirname(link), { recursive: true })
+ const target = dependency.startsWith(workspaceScope)
+ ? this.pkg(dependency.slice(workspaceScope.length))
+ : realpathSync(path.join(from, 'node_modules', dependency))
+ symlinkSync(target, link, 'dir')
+ }
+ }
+
+ pkg(name: string) {
+ return path.join(this.root, name)
+ }
+
+ file(name: string, file: string) {
+ return path.join(this.pkg(name), file)
+ }
+
+ read(name: string, file: string) {
+ return readFileSync(this.file(name, file), 'utf8')
+ }
+
+ write(name: string, file: string, content: string) {
+ mkdirSync(path.dirname(this.file(name, file)), { recursive: true })
+ writeFileSync(this.file(name, file), content)
+ }
+
+ edit(name: string, file: string, edit: (content: string) => string) {
+ const before = this.read(name, file)
+ const after = edit(before)
+ if (after === before) {
+ throw new Error(`The edit of ${name}/${file} changed nothing`)
+ }
+ this.write(name, file, after)
+ }
+
+ remove(name: string, file: string) {
+ rmSync(this.file(name, file), { recursive: true, force: true })
+ }
+
+ exists(name: string, file: string) {
+ return existsSync(this.file(name, file))
+ }
+
+ /** Pass A: route generation of one package. */
+ async generate(name: string) {
+ const packageRoot = this.pkg(name)
+ const config = getConfig(
+ { disableLogging: true, tmpDir: path.join(this.root, '.tmp') },
+ packageRoot,
+ )
+ try {
+ await new Generator({ config, root: packageRoot }).run()
+ this.log.push({ operation: 'generate', pkg: name, ok: true })
+ } catch (error) {
+ this.log.push({ operation: 'generate', pkg: name, ok: false })
+ throw error
+ }
+ }
+
+ /** The fixture package's ordinary clean TypeScript declaration build. */
+ async emitTypes(name: string) {
+ const project = JSON.parse(this.read(name, 'tsconfig.route-types.json'))
+ this.remove(
+ name,
+ project.compilerOptions.declarationDir ?? project.compilerOptions.outDir,
+ )
+ const result = this.compile(name, ['-p', 'tsconfig.route-types.json'])
+ this.log.push({ operation: 'emit-types', pkg: name, ok: result.ok })
+ return result
+ }
+
+ /** Source check of one package against current module declarations. */
+ async check(name: string) {
+ const result = this.compile(name, ['-p', 'tsconfig.json', '--noEmit'])
+ this.log.push({ operation: 'check', pkg: name, ok: result.ok })
+ return result
+ }
+
+ /** Generates, emits and checks every package in dependency order. */
+ async buildGraph(order: Array, modules: Array) {
+ for (const name of order) {
+ await this.generate(name)
+ if (modules.includes(name)) {
+ const emitted = await this.emitTypes(name)
+ if (!emitted.ok) {
+ throw new Error(emitted.diagnostics.join('\n'))
+ }
+ }
+ }
+ }
+
+ manifest(name: string): RouteModuleManifest {
+ return readRouteModuleManifest(this.pkg(name))!
+ }
+
+ private compile(name: string, args: Array) {
+ const result = spawnSync(tsc, [...args, '--pretty', 'false'], {
+ cwd: this.pkg(name),
+ encoding: 'utf8',
+ })
+ return {
+ ok: result.status === 0,
+ diagnostics: result.error
+ ? [result.error.message]
+ : `${result.stdout ?? ''}${result.stderr ?? ''}`
+ .split(/\r?\n/)
+ .filter((line) => line.trim() !== ''),
+ }
+ }
+
+ /** Content hash and modification time of every file below `dir`. */
+ snapshot(name: string, dir: string): Record {
+ const base = this.file(name, dir)
+ const result: Record = {}
+ const walk = (current: string) => {
+ for (const entry of readdirSync(current)) {
+ const full = path.join(current, entry)
+ const stat = statSync(full)
+ if (stat.isDirectory()) {
+ walk(full)
+ } else {
+ result[path.relative(base, full)] = `${crypto
+ .createHash('sha256')
+ .update(readFileSync(full))
+ .digest('hex')
+ .slice(0, 12)}@${stat.mtimeMs}`
+ }
+ }
+ }
+ if (existsSync(base)) {
+ walk(base)
+ }
+ return result
+ }
+
+ /** The files a package's type check loads (`tsc --listFilesOnly`). */
+ listProgramFiles(name: string): Array {
+ const result = spawnSync(tsc, ['-p', 'tsconfig.json', '--listFilesOnly'], {
+ cwd: this.pkg(name),
+ encoding: 'utf8',
+ })
+ return result.stdout.split(/\r?\n/).filter(Boolean)
+ }
+
+ dispose() {
+ rmSync(this.root, { recursive: true, force: true })
+ }
+}
+
+function require_mkdtemp(prefix: string) {
+ // `fs.mkdtempSync` without importing the whole promises API.
+ const dir = `${prefix}${crypto.randomBytes(4).toString('hex')}`
+ mkdirSync(dir, { recursive: true })
+ return dir
+}
+
+/**
+ * The diagnostics of a failed check that point into `file`, each with its
+ * indented continuation lines (where elaborated messages appear).
+ */
+export function errorsIn(diagnostics: Array, file: string) {
+ const errors: Array = []
+ let current: string | undefined
+ for (const line of diagnostics) {
+ if (/^\s/.test(line)) {
+ if (current !== undefined) {
+ current += `\n${line}`
+ }
+ continue
+ }
+ if (current !== undefined) {
+ errors.push(current)
+ }
+ current =
+ line.startsWith(file) || line.includes(`/${file}(`) ? line : undefined
+ }
+ if (current !== undefined) {
+ errors.push(current)
+ }
+ return errors
+}
diff --git a/e2e/react-router/route-modules/tsconfig.json b/e2e/react-router/route-modules/tsconfig.json
new file mode 100644
index 0000000000..341902faed
--- /dev/null
+++ b/e2e/react-router/route-modules/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": [
+ "tests",
+ "e2e",
+ "e2e-dev",
+ "scripts",
+ "vitest.config.ts",
+ "playwright.config.ts",
+ "playwright.dev.config.ts"
+ ]
+}
diff --git a/e2e/react-router/route-modules/vitest.config.ts b/e2e/react-router/route-modules/vitest.config.ts
new file mode 100644
index 0000000000..b8e3ec784a
--- /dev/null
+++ b/e2e/react-router/route-modules/vitest.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.ts', 'packages/web/tests/**/*.test.tsx'],
+ // Each test runs the generator and the TypeScript compiler on a workspace.
+ testTimeout: 120_000,
+ hookTimeout: 120_000,
+ fileParallelism: false,
+ },
+})
diff --git a/e2e/react-start/route-modules/.gitignore b/e2e/react-start/route-modules/.gitignore
new file mode 100644
index 0000000000..92efdd2694
--- /dev/null
+++ b/e2e/react-start/route-modules/.gitignore
@@ -0,0 +1,9 @@
+# Generated by the route generator and TypeScript; the tests generate
+# them from a clean copy of the packages.
+**/routeTree.gen.ts
+**/routeScope.gen.ts
+**/routeContract.gen.ts
+**/routeModule.gen.ts
+**/startModules.gen.ts
+**/routeScope.gen.*.ts
+**/routeTree.gen.*.ts
diff --git a/e2e/react-start/route-modules/e2e-dev/devtools.spec.ts b/e2e/react-start/route-modules/e2e-dev/devtools.spec.ts
new file mode 100644
index 0000000000..59ebbb9ecd
--- /dev/null
+++ b/e2e/react-start/route-modules/e2e-dev/devtools.spec.ts
@@ -0,0 +1,50 @@
+import { expect, test } from '@playwright/test'
+
+test('the router devtools group the routes of mounted modules', async ({
+ page,
+}) => {
+ await page.goto('/shop/lamp')
+ await page.getByTestId('hydrated').waitFor()
+ await page
+ .getByRole('button', { name: 'Open TanStack Router Devtools' })
+ .click()
+
+ await expect(
+ page.getByRole('group', {
+ name: 'Route module @start-route-modules/catalog',
+ }),
+ ).toBeVisible()
+ await expect(
+ page.getByRole('group', {
+ name: 'Route module @start-route-modules/notes',
+ }),
+ ).toBeVisible()
+
+ await page
+ .getByRole('button', {
+ name: 'Open module details for @start-route-modules/catalog',
+ })
+ .first()
+ .click()
+ const details = page.getByRole('region', { name: 'Module details' })
+ await expect(details).toContainText('Mount path:/shop')
+ await expect(details).toContainText('Parent module:Application')
+})
+
+test('the router devtools show each installation of a module installed twice', async ({
+ page,
+}) => {
+ await page.goto('/people/ada/settings')
+ await page.getByTestId('hydrated').waitFor()
+ await page
+ .getByRole('button', { name: 'Open TanStack Router Devtools' })
+ .click()
+
+ for (const installation of ['orgSettings', 'personSettings']) {
+ await expect(
+ page.getByRole('group', {
+ name: `Route module @start-route-modules/settings#${installation}`,
+ }),
+ ).toBeVisible()
+ }
+})
diff --git a/e2e/react-start/route-modules/e2e-dev/hmr.spec.ts b/e2e/react-start/route-modules/e2e-dev/hmr.spec.ts
new file mode 100644
index 0000000000..0d4df29277
--- /dev/null
+++ b/e2e/react-start/route-modules/e2e-dev/hmr.spec.ts
@@ -0,0 +1,169 @@
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { expect } from '@playwright/test'
+import { createHmrFileEditor, test } from '@tanstack/router-e2e-utils'
+import { Generator, getConfig } from '@tanstack/router-generator'
+import type { Page } from '@playwright/test'
+
+const catalog = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../packages/catalog',
+)
+
+const editor = createHmrFileEditor({
+ rootDir: catalog,
+ files: {
+ product: 'src/routes/$productId.tsx',
+ api: 'src/api.ts',
+ index: 'src/routes/index.tsx',
+ },
+})
+const settingsEditor = createHmrFileEditor({
+ rootDir: path.resolve(catalog, '../settings'),
+ files: {
+ profile: 'src/routes/profile.tsx',
+ },
+})
+
+test.afterEach(async () => {
+ await editor.restoreFiles()
+ await settingsEditor.restoreFiles()
+})
+
+// The server-rendered page shows the product before the browser has loaded
+// the route module. Edit only after hydration: an edit before it is served to
+// the hydrating browser, which then mismatches the server's HTML instead of
+// receiving a hot update.
+async function gotoHydrated(page: Page, url: string) {
+ await page.goto(url)
+ await page.getByTestId('hydrated').waitFor()
+}
+
+test('editing a module route file hot-updates it in the application', async ({
+ page,
+}) => {
+ await gotoHydrated(page, '/shop/lamp')
+ await expect(page.getByRole('heading', { name: 'Desk lamp' })).toBeVisible()
+ await page.evaluate(() => {
+ ;(window as any).__beforeHmr = true
+ })
+
+ await editor.replaceText(
+ 'product',
+ '{product.name} ',
+ 'Updated {product.name} ',
+ )
+ await expect(
+ page.getByRole('heading', { name: 'Updated Desk lamp' }),
+ ).toBeVisible()
+ // A hot update, not a reload: page state survives.
+ expect(await page.evaluate(() => (window as any).__beforeHmr)).toBe(true)
+
+ // Restore while the page is open. Server rendering reads the file again,
+ // but the browser gets the client's compiled module until Vite processes
+ // the change; the hot update shows it has, so the next page load hydrates.
+ await editor.restoreFiles()
+ await expect(
+ page.getByRole('heading', { name: 'Desk lamp', exact: true }),
+ ).toBeVisible()
+})
+
+test('a module server function runs its edited implementation', async ({
+ page,
+}) => {
+ await gotoHydrated(page, '/shop/lamp')
+ await expect(page.getByRole('heading', { name: 'Desk lamp' })).toBeVisible()
+
+ await editor.replaceText('api', "name: 'Desk lamp'", "name: 'Reading lamp'")
+ await expect(async () => {
+ await page.getByRole('button', { name: 'Refresh' }).click()
+ await expect(
+ page.getByRole('heading', { name: 'Reading lamp' }),
+ ).toBeVisible({ timeout: 1000 })
+ }).toPass()
+ await expect(page.getByTestId('price')).toHaveText('49.00 EUR')
+})
+
+test('editing a route of a module installed twice hot-updates every installation', async ({
+ page,
+}) => {
+ await gotoHydrated(page, '/people/ada/settings/profile')
+ await expect(page.getByRole('heading', { name: 'Profile' })).toBeVisible()
+ await page.evaluate(() => {
+ ;(window as any).__beforeHmr = true
+ })
+
+ await settingsEditor.replaceText(
+ 'profile',
+ 'Profile ',
+ 'Updated profile ',
+ )
+ await expect(
+ page.getByRole('heading', { name: 'Updated profile' }),
+ ).toBeVisible()
+
+ // The installation of the organizations runs the updated route too.
+ await page.evaluate(() =>
+ (window as any).__TSR_ROUTER__.navigate({
+ to: '/orgs/acme/settings/profile',
+ }),
+ )
+ await expect(page.getByTestId('profile-kind')).toHaveText('organization')
+ await expect(
+ page.getByRole('heading', { name: 'Updated profile' }),
+ ).toBeVisible()
+ // Hot updates, not reloads: page state survives.
+ expect(await page.evaluate(() => (window as any).__beforeHmr)).toBe(true)
+})
+
+test('provider classification changes refresh the client tree and preserve server endpoints', async ({
+ page,
+ request,
+}) => {
+ await editor.capturePromise
+ const providerGenerator = new Generator({
+ root: catalog,
+ config: getConfig({ disableLogging: true }, catalog),
+ })
+ const hasCatalogPage = () =>
+ page.evaluate(() => {
+ const router = (window as any).__TSR_ROUTER__
+ return router
+ ? Object.hasOwn(router.routesById, '@start-route-modules/catalog:/')
+ : undefined
+ })
+ const expectCatalogPage = (present: boolean) =>
+ expect(async () => {
+ // Topology publication may reload the document; retry through navigation
+ // and require an initialized router before checking its route inventory.
+ expect(await hasCatalogPage()).toBe(present)
+ }).toPass()
+ await gotoHydrated(page, '/')
+ await expectCatalogPage(true)
+ try {
+ await editor.rewriteFile(
+ 'index',
+ () => `import { createFileRoute } from '../routeScope.gen'
+export const Route = createFileRoute('@start-route-modules/catalog:/')({
+ server: { handlers: { GET: () => new Response('catalog endpoint') } },
+})
+`,
+ )
+ await providerGenerator.run()
+ await expectCatalogPage(false)
+ await expect(async () => {
+ const response = await request.get('/shop')
+ expect(response.status()).toBe(200)
+ expect(await response.text()).toBe('catalog endpoint')
+ }).toPass()
+
+ await editor.restoreFiles()
+ await providerGenerator.run()
+ await expectCatalogPage(true)
+ await gotoHydrated(page, '/shop')
+ await expect(page.getByTestId('price-chair')).toHaveText('129.00 EUR')
+ } finally {
+ await editor.restoreFiles()
+ await providerGenerator.run()
+ }
+})
diff --git a/e2e/react-start/route-modules/e2e/app.spec.ts b/e2e/react-start/route-modules/e2e/app.spec.ts
new file mode 100644
index 0000000000..4309a6d1ea
--- /dev/null
+++ b/e2e/react-start/route-modules/e2e/app.spec.ts
@@ -0,0 +1,160 @@
+import { expect, test } from '@playwright/test'
+
+test('the server renders module routes with the context the application provides', async ({
+ request,
+}) => {
+ const html = await (await request.get('/shop/lamp')).text()
+ expect(html).toContain('Desk lamp')
+ // `shopper` comes from the application's request middleware, the currency
+ // from the catalog's own pricing middleware.
+ expect(html).toContain('49.00 EUR')
+ expect(html).toContain('Shopper: ada')
+})
+
+test('module data hydrates through the module serialization adapter', async ({
+ page,
+}) => {
+ await page.goto('/shop/lamp')
+ await expect(page.getByTestId('price')).toHaveText('49.00 EUR')
+ const renderedAt = await page.getByTestId('rendered-at').textContent()
+
+ // The route's loader runs again on the client and calls the module's
+ // server function; its result goes through the serialization adapter.
+ await page.getByRole('button', { name: 'Refresh' }).click()
+ await expect(page.getByTestId('rendered-at')).not.toHaveText(renderedAt!)
+ await expect(page.getByTestId('price')).toHaveText('49.00 EUR')
+ await expect(page.getByTestId('shopper')).toHaveText('Shopper: ada')
+})
+
+test('client navigation loads module routes through their server functions', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await expect(page.getByRole('heading', { name: 'Home' })).toBeVisible()
+ await page.getByRole('link', { name: 'Catalog' }).click()
+ await expect(page).toHaveURL('/shop')
+ await expect(page.getByTestId('price-chair')).toHaveText('129.00 EUR')
+
+ await page.getByRole('link', { name: 'Office chair' }).click()
+ await expect(page).toHaveURL('/shop/chair')
+ await expect(
+ page.getByRole('heading', { name: 'Office chair' }),
+ ).toBeVisible()
+
+ await page.getByRole('link', { name: 'All products' }).click()
+ await expect(page).toHaveURL('/shop')
+})
+
+test('a router-only module renders in the Start application', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await page.getByRole('link', { name: 'Notes' }).click()
+ await expect(page).toHaveURL('/notes')
+ await expect(page.getByTestId('notes')).toContainText('Compose route modules')
+})
+
+test('module routes are code-split from the application bundle', async ({
+ page,
+}) => {
+ // Chunk names differ between toolchains: find the product page's code by
+ // its text in the scripts the browser loads.
+ const scripts: Array> = []
+ page.on('response', (response) => {
+ if (response.request().resourceType() === 'script') {
+ scripts.push(response.text())
+ }
+ })
+ const loadsProductPage = async () =>
+ (await Promise.all(scripts)).some((script) =>
+ script.includes('Rendered at'),
+ )
+ await page.goto('/')
+ await expect(page.getByRole('heading', { name: 'Home' })).toBeVisible()
+ expect(await loadsProductPage()).toBe(false)
+
+ await page.getByRole('link', { name: 'Lamp' }).click()
+ await expect(page.getByRole('heading', { name: 'Desk lamp' })).toBeVisible()
+ await expect.poll(loadsProductPage).toBe(true)
+})
+
+test('the server renders a module mounted under path params', async ({
+ request,
+}) => {
+ const html = await (await request.get('/orgs/acme/team')).text()
+ expect(html).toContain('Team of ACME')
+ // The module's server function loads the members of the organization in the URL.
+ expect(html).toContain('grace (acme)')
+})
+
+test('links into and inside a module mounted under path params', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await page.getByTestId('hydrated').waitFor()
+ // The application passes the path params above the module.
+ await page.getByRole('link', { name: 'Acme team' }).click()
+ await expect(page).toHaveURL('/orgs/acme/team')
+ await expect(
+ page.getByRole('heading', { name: 'Team of ACME' }),
+ ).toBeVisible()
+
+ // Module-local links keep the path params of the current location.
+ await page.getByRole('link', { name: 'grace (acme)' }).click()
+ await expect(page).toHaveURL('/orgs/acme/team/members/grace')
+ await expect(
+ page.getByRole('heading', { name: 'grace at ACME' }),
+ ).toBeVisible()
+ await page.getByRole('link', { name: 'All members' }).click()
+ await expect(page).toHaveURL('/orgs/acme/team')
+})
+
+test('the server renders each installation of a module installed twice', async ({
+ request,
+}) => {
+ const person = await (
+ await request.get('/people/ada/settings/profile')
+ ).text()
+ expect(person).toContain('Settings of Ada')
+ expect(person).toContain('@ada')
+ const organization = await (
+ await request.get('/orgs/acme/settings/profile')
+ ).text()
+ expect(organization).toContain('Settings of ACME')
+ expect(organization).toContain('@acme')
+})
+
+test('links of a module installed twice stay in their installation', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await page.getByTestId('hydrated').waitFor()
+ await page.getByRole('link', { name: 'Globex settings' }).click()
+ await expect(page).toHaveURL('/orgs/globex/settings')
+ await expect(
+ page.getByRole('heading', { name: 'Settings of GLOBEX' }),
+ ).toBeVisible()
+ // The profile loads through the module's server function.
+ await page.getByRole('link', { name: 'Profile' }).click()
+ await expect(page).toHaveURL('/orgs/globex/settings/profile')
+ await expect(page.getByTestId('profile-kind')).toHaveText('organization')
+
+ await page.goto('/')
+ await page.getByTestId('hydrated').waitFor()
+ await page.getByRole('link', { name: "Ada's profile" }).click()
+ await expect(page).toHaveURL('/people/ada/settings/profile')
+ await expect(page.getByTestId('profile-kind')).toHaveText('person')
+ await page.getByRole('link', { name: 'All settings' }).click()
+ await expect(page).toHaveURL('/people/ada/settings')
+})
+
+test('a module that uses a module installed twice links to the installation above it', async ({
+ page,
+}) => {
+ await page.goto('/orgs/acme/team')
+ await page.getByTestId('hydrated').waitFor()
+ const profile = page.getByRole('link', { name: 'Organization profile' })
+ await expect(profile).toHaveAttribute('href', '/orgs/acme/settings/profile')
+ await profile.click()
+ await expect(page.getByTestId('profile-kind')).toHaveText('organization')
+})
diff --git a/e2e/react-start/route-modules/package.json b/e2e/react-start/route-modules/package.json
new file mode 100644
index 0000000000..ce088f7363
--- /dev/null
+++ b/e2e/react-start/route-modules/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "tanstack-react-start-e2e-route-modules",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "test:e2e": "vitest run && pnpm test:e2e:dev",
+ "test:e2e:dev": "pnpm test:e2e:dev:vite && pnpm test:e2e:dev:rsbuild",
+ "test:e2e:dev:vite": "E2E_TOOLCHAIN=vite playwright test --config playwright.dev.config.ts --project=chromium",
+ "test:e2e:dev:rsbuild": "E2E_TOOLCHAIN=rsbuild playwright test --config playwright.dev.config.ts --project=chromium"
+ },
+ "devDependencies": {
+ "@playwright/test": "^1.61.0",
+ "@start-route-modules/web": "workspace:*",
+ "@tanstack/router-e2e-utils": "workspace:^",
+ "@tanstack/router-generator": "workspace:^",
+ "@types/node": "catalog:",
+ "vitest": "catalog:"
+ },
+ "nx": {
+ "targets": {
+ "test:e2e": {
+ "parallelism": false
+ },
+ "build:vite:ssr": {
+ "options": {
+ "command": "node scripts/prepare.mjs && pnpm --filter @start-route-modules/web build:vite"
+ },
+ "outputs": [
+ "{projectRoot}/packages/web/dist-vite-ssr"
+ ]
+ },
+ "build:rsbuild:ssr": {
+ "options": {
+ "command": "node scripts/prepare.mjs && pnpm --filter @start-route-modules/web build:rsbuild"
+ },
+ "outputs": [
+ "{projectRoot}/packages/web/dist-rsbuild-ssr"
+ ]
+ }
+ },
+ "metadata": {
+ "playwrightModes": [
+ {
+ "toolchain": "vite",
+ "mode": "ssr"
+ },
+ {
+ "toolchain": "rsbuild",
+ "mode": "ssr"
+ }
+ ]
+ }
+ }
+}
diff --git a/e2e/react-start/route-modules/packages/catalog/package.json b/e2e/react-start/route-modules/packages/catalog/package.json
new file mode 100644
index 0000000000..7f0729e3ce
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "@start-route-modules/catalog",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "workspace:^",
+ "@tanstack/react-start": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@tanstack/start-client-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-start/route-modules/packages/catalog/src/api.ts b/e2e/react-start/route-modules/packages/catalog/src/api.ts
new file mode 100644
index 0000000000..263b078d00
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/src/api.ts
@@ -0,0 +1,41 @@
+import { notFound } from '@tanstack/react-router'
+import { createServerFn, createMiddleware } from './routeScope.gen'
+import { Money } from './money'
+
+// Module-local: only the catalog's server functions run it.
+const pricing = createMiddleware({ type: 'function' }).server(
+ ({ context, next }) =>
+ next({ context: { currency: context.shopper === 'ada' ? 'EUR' : 'USD' } }),
+)
+
+const products = [
+ { id: 'lamp', name: 'Desk lamp', cents: 4900 },
+ { id: 'chair', name: 'Office chair', cents: 12900 },
+]
+
+export const listProducts = createServerFn()
+ .middleware([pricing])
+ .handler(({ context }) =>
+ products.map((product) => ({
+ id: product.id,
+ name: product.name,
+ price: new Money(product.cents, context.currency),
+ })),
+ )
+
+export const getProduct = createServerFn()
+ .middleware([pricing])
+ .validator((id: string) => id)
+ .handler(({ data, context }) => {
+ const product = products.find((candidate) => candidate.id === data)
+ if (!product) {
+ throw notFound()
+ }
+ return {
+ id: product.id,
+ name: product.name,
+ price: new Money(product.cents, context.currency),
+ shopper: context.shopper,
+ renderedAt: Date.now(),
+ }
+ })
diff --git a/e2e/react-start/route-modules/packages/catalog/src/money.ts b/e2e/react-start/route-modules/packages/catalog/src/money.ts
new file mode 100644
index 0000000000..fbd146447c
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/src/money.ts
@@ -0,0 +1,20 @@
+import { createSerializationAdapter } from '@tanstack/react-router'
+
+/** An amount of money. Server functions and loaders return it as is. */
+export class Money {
+ constructor(
+ readonly cents: number,
+ readonly currency: string,
+ ) {}
+
+ format() {
+ return `${(this.cents / 100).toFixed(2)} ${this.currency}`
+ }
+}
+
+export const moneyAdapter = createSerializationAdapter({
+ key: 'catalog-money',
+ test: (value): value is Money => value instanceof Money,
+ toSerializable: (money) => ({ cents: money.cents, currency: money.currency }),
+ fromSerializable: (value) => new Money(value.cents, value.currency),
+})
diff --git a/e2e/react-start/route-modules/packages/catalog/src/requirements.ts b/e2e/react-start/route-modules/packages/catalog/src/requirements.ts
new file mode 100644
index 0000000000..1c91f7bdf0
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/src/requirements.ts
@@ -0,0 +1,7 @@
+export type { StartModuleRequirements } from '@tanstack/react-start'
+
+declare module '@tanstack/react-start' {
+ interface StartModuleRequirements {
+ '@start-route-modules/catalog': { requestContext: { shopper: string } }
+ }
+}
diff --git a/e2e/react-start/route-modules/packages/catalog/src/routes/$productId.tsx b/e2e/react-start/route-modules/packages/catalog/src/routes/$productId.tsx
new file mode 100644
index 0000000000..34ff20347c
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/src/routes/$productId.tsx
@@ -0,0 +1,62 @@
+import { useRef } from 'react'
+import { createFileRoute, useRouter } from '../routeScope.gen'
+import { getProduct } from '../api'
+
+export const Route = createFileRoute(
+ '@start-route-modules/catalog:/$productId',
+)({
+ loader: ({ params }) => getProduct({ data: params.productId }),
+ component: ProductPage,
+})
+
+function ProductPage() {
+ const product = Route.useLoaderData()
+ const router = useRouter()
+ const refreshing = Route.useMatch({
+ select: (match) => match.isFetching !== false,
+ })
+ // A render after the first one came from a refresh.
+ const firstRenderedAt = useRef(product.renderedAt).current
+ return (
+
+ {product.name}
+
+ {product.price.format()}
+
+
+
Shopper: {product.shopper}
+
+ Rendered at{' '}
+ {/* Highlighted once each time a refresh brings a new render. */}
+
+ {new Date(product.renderedAt).toISOString().slice(11, 23)}
+ {' '}
+ UTC
+
+
+
+
+ router.invalidate({
+ filter: (match) => match.routeId === Route.id,
+ })
+ }
+ >
+ Refresh
+
+ All products
+
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/catalog/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/catalog/src/routes/__root.tsx
new file mode 100644
index 0000000000..e245ab4549
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/src/routes/__root.tsx
@@ -0,0 +1,21 @@
+export type {} from '../requirements'
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+
+export const Route = createModuleRoot()({
+ component: CatalogRoom,
+})
+
+// The module's region: a room tagged with its package and where it is
+// mounted.
+function CatalogRoom() {
+ return (
+
+
+ @start-route-modules/catalog {Route.fullPath}
+
+ Catalog
+
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/catalog/src/routes/index.tsx b/e2e/react-start/route-modules/packages/catalog/src/routes/index.tsx
new file mode 100644
index 0000000000..4b399ce36c
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/src/routes/index.tsx
@@ -0,0 +1,25 @@
+import { createFileRoute } from '../routeScope.gen'
+import { listProducts } from '../api'
+
+export const Route = createFileRoute('@start-route-modules/catalog:/')({
+ loader: () => listProducts(),
+ component: CatalogPage,
+})
+
+function CatalogPage() {
+ const products = Route.useLoaderData()
+ return (
+
+ {products.map((product) => (
+
+
+ {product.name}
+
+
+ {product.price.format()}
+
+
+ ))}
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/catalog/src/start.ts b/e2e/react-start/route-modules/packages/catalog/src/start.ts
new file mode 100644
index 0000000000..010339ba76
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/src/start.ts
@@ -0,0 +1,8 @@
+export type {} from './requirements'
+import { createStartModule } from './routeScope.gen'
+import { moneyAdapter } from './money'
+
+export const start = createStartModule(() => ({
+ // Contributed: `Money` values cross the network in every application route.
+ serializationAdapters: [moneyAdapter],
+}))
diff --git a/e2e/react-start/route-modules/packages/catalog/tsconfig.json b/e2e/react-start/route-modules/packages/catalog/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-start/route-modules/packages/catalog/tsconfig.route-types.json b/e2e/react-start/route-modules/packages/catalog/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/catalog/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-start/route-modules/packages/notes/package.json b/e2e/react-start/route-modules/packages/notes/package.json
new file mode 100644
index 0000000000..87d6fe06d5
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/notes/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@start-route-modules/notes",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-start/route-modules/packages/notes/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/notes/src/routes/__root.tsx
new file mode 100644
index 0000000000..b2bf618003
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/notes/src/routes/__root.tsx
@@ -0,0 +1,18 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+
+export const Route = createModuleRoot()({ component: NotesRoom })
+
+// The module's region: a room tagged with its package and where it is
+// mounted.
+function NotesRoom() {
+ return (
+
+
+ @start-route-modules/notes {Route.fullPath}
+
+ Notes
+
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/notes/src/routes/index.tsx b/e2e/react-start/route-modules/packages/notes/src/routes/index.tsx
new file mode 100644
index 0000000000..085fd35834
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/notes/src/routes/index.tsx
@@ -0,0 +1,18 @@
+import { createFileRoute } from '../routeScope.gen'
+
+// A router-only module: the application that mounts it serializes this result.
+export const Route = createFileRoute('@start-route-modules/notes:/')({
+ loader: () => ({ notes: ['Compose route modules', 'Ship it'] }),
+ component: NotesPage,
+})
+
+function NotesPage() {
+ const { notes } = Route.useLoaderData()
+ return (
+
+ {notes.map((note) => (
+ {note}
+ ))}
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/notes/tsconfig.json b/e2e/react-start/route-modules/packages/notes/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/notes/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-start/route-modules/packages/notes/tsconfig.route-types.json b/e2e/react-start/route-modules/packages/notes/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/notes/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-start/route-modules/packages/settings/package.json b/e2e/react-start/route-modules/packages/settings/package.json
new file mode 100644
index 0000000000..58223e6483
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/settings/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "@start-route-modules/settings",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "workspace:^",
+ "@tanstack/react-start": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@tanstack/start-client-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-start/route-modules/packages/settings/src/api.ts b/e2e/react-start/route-modules/packages/settings/src/api.ts
new file mode 100644
index 0000000000..2699f06ded
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/settings/src/api.ts
@@ -0,0 +1,6 @@
+import { createServerFn } from './routeScope.gen'
+
+/** The profile of an owner, loaded on the server. */
+export const getProfile = createServerFn()
+ .validator((owner: { kind: string; id: string }) => owner)
+ .handler(({ data }) => ({ kind: data.kind, handle: `@${data.id}` }))
diff --git a/e2e/react-start/route-modules/packages/settings/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/settings/src/routes/__root.tsx
new file mode 100644
index 0000000000..db49802df7
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/settings/src/routes/__root.tsx
@@ -0,0 +1,38 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+
+/** Whose settings an installation shows, provided by its host route. */
+export interface Owner {
+ kind: 'organization' | 'person'
+ id: string
+ name: string
+}
+
+// The store installs the settings twice: below `/orgs/$orgId` and below
+// `/people/$personId`. Each host route provides its owner.
+export const Route = createModuleRoot<{ owner: Owner }>()({
+ component: SettingsRoom,
+})
+
+// The module's region: a room tagged with the installation it renders and
+// where that installation is mounted.
+function SettingsRoom() {
+ const { owner } = Route.useRouteContext()
+ const match = Route.useMatch({
+ select: ({ routeId, fullPath, pathname }) => ({
+ installation: routeId.slice(0, routeId.indexOf(':')),
+ fullPath,
+ pathname,
+ }),
+ })
+ return (
+
+
+ {match.installation} {match.fullPath}
+ → {match.pathname}
+
+ {`Settings of ${owner.name}`}
+
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/settings/src/routes/index.tsx b/e2e/react-start/route-modules/packages/settings/src/routes/index.tsx
new file mode 100644
index 0000000000..86e80418f9
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/settings/src/routes/index.tsx
@@ -0,0 +1,15 @@
+import { Link, createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute('@start-route-modules/settings:/')({
+ component: SettingsIndex,
+})
+
+function SettingsIndex() {
+ return (
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/settings/src/routes/profile.tsx b/e2e/react-start/route-modules/packages/settings/src/routes/profile.tsx
new file mode 100644
index 0000000000..88f10273ba
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/settings/src/routes/profile.tsx
@@ -0,0 +1,27 @@
+import { createFileRoute } from '../routeScope.gen'
+import { getProfile } from '../api'
+
+export const Route = createFileRoute('@start-route-modules/settings:/profile')({
+ // Each installation loads the profile of the owner its host provides.
+ loader: ({ context }) =>
+ getProfile({ data: { kind: context.owner.kind, id: context.owner.id } }),
+ component: Profile,
+})
+
+function Profile() {
+ const profile = Route.useLoaderData()
+ return (
+
+ Profile
+
+ Kind
+ {profile.kind}
+ Handle
+
+ {profile.handle}
+
+
+ All settings
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/settings/tsconfig.json b/e2e/react-start/route-modules/packages/settings/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/settings/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-start/route-modules/packages/settings/tsconfig.route-types.json b/e2e/react-start/route-modules/packages/settings/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/settings/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-start/route-modules/packages/team/package.json b/e2e/react-start/route-modules/packages/team/package.json
new file mode 100644
index 0000000000..cb8b8d1f05
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/team/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "@start-route-modules/team",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": {
+ "uses": [
+ "@start-route-modules/settings"
+ ]
+ }
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@start-route-modules/settings": "workspace:*",
+ "@tanstack/react-router": "workspace:^",
+ "@tanstack/react-start": "workspace:^",
+ "react": "^19.0.0"
+ },
+ "devDependencies": {
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@tanstack/start-client-core": "workspace:^",
+ "@types/react": "^19.0.8"
+ }
+}
diff --git a/e2e/react-start/route-modules/packages/team/src/api.ts b/e2e/react-start/route-modules/packages/team/src/api.ts
new file mode 100644
index 0000000000..a0df5ce0c6
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/team/src/api.ts
@@ -0,0 +1,8 @@
+import { createServerFn } from './routeScope.gen'
+
+/** The members of an organization, loaded on the server. */
+export const listMembers = createServerFn()
+ .validator((orgId: string) => orgId)
+ .handler(({ data }) =>
+ ['ada', 'grace'].map((name) => ({ id: name, label: `${name} (${data})` })),
+ )
diff --git a/e2e/react-start/route-modules/packages/team/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/team/src/routes/__root.tsx
new file mode 100644
index 0000000000..f6976ed6d0
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/team/src/routes/__root.tsx
@@ -0,0 +1,25 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+
+// The organization comes from the host route the application mounts the team
+// under, so the team works below any route that provides it.
+export const Route = createModuleRoot<{ org: { id: string; name: string } }>()({
+ component: TeamLayout,
+})
+
+// The module's region: a room tagged with its package and where it is
+// mounted, with the URL its mount path resolved to.
+function TeamLayout() {
+ const { org } = Route.useRouteContext()
+ const pathname = Route.useMatch({ select: (match) => match.pathname })
+ return (
+
+
+ @start-route-modules/team {Route.fullPath}
+ → {pathname}
+
+ {`Team of ${org.name}`}
+
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/team/src/routes/index.tsx b/e2e/react-start/route-modules/packages/team/src/routes/index.tsx
new file mode 100644
index 0000000000..d7c8dec462
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/team/src/routes/index.tsx
@@ -0,0 +1,27 @@
+import { Link, createFileRoute, settings } from '../routeScope.gen'
+import { listMembers } from '../api'
+
+export const Route = createFileRoute('@start-route-modules/team:/')({
+ loader: ({ context }) => listMembers({ data: context.org.id }),
+ component: Members,
+})
+
+function Members() {
+ const members = Route.useLoaderData()
+ return (
+ <>
+
+ {members.map((member) => (
+
+
+ {member.label}
+
+
+ ))}
+
+ {/* The settings are installed for organizations and for people: the
+ team links to the installation of its own organization. */}
+ Organization profile
+ >
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/team/src/routes/members.$memberId.tsx b/e2e/react-start/route-modules/packages/team/src/routes/members.$memberId.tsx
new file mode 100644
index 0000000000..a51df6a1d9
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/team/src/routes/members.$memberId.tsx
@@ -0,0 +1,28 @@
+import { Link, createFileRoute } from '../routeScope.gen'
+
+export const Route = createFileRoute(
+ '@start-route-modules/team:/members/$memberId',
+)({
+ component: Member,
+})
+
+function Member() {
+ const { memberId } = Route.useParams()
+ const { org } = Route.useRouteContext()
+ return (
+
+ {`${memberId} at ${org.name}`}
+
+ Organization
+
+ {org.id}
+
+ Member
+
+ {memberId}
+
+
+ All members
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/team/tsconfig.json b/e2e/react-start/route-modules/packages/team/tsconfig.json
new file mode 100644
index 0000000000..1de72ddc24
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/team/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-start/route-modules/packages/team/tsconfig.route-types.json b/e2e/react-start/route-modules/packages/team/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/team/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/react-start/route-modules/packages/web/package.json b/e2e/react-start/route-modules/packages/web/package.json
new file mode 100644
index 0000000000..f1f50b148b
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@start-route-modules/web",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev:vite": "vite dev",
+ "dev:rsbuild": "rsbuild dev",
+ "build:vite": "vite build && tsc --noEmit",
+ "build:rsbuild": "rsbuild build && tsc --noEmit",
+ "start": "node server.js"
+ },
+ "dependencies": {
+ "@start-route-modules/catalog": "workspace:*",
+ "@start-route-modules/notes": "workspace:*",
+ "@start-route-modules/settings": "workspace:*",
+ "@start-route-modules/team": "workspace:*",
+ "@tanstack/react-router": "workspace:^",
+ "@tanstack/react-router-devtools": "workspace:^",
+ "@tanstack/react-start": "workspace:^",
+ "react": "^19.0.0",
+ "react-dom": "^19.0.0"
+ },
+ "devDependencies": {
+ "@rsbuild/core": "^2.1.0",
+ "@rsbuild/plugin-react": "^2.0.0",
+ "@types/node": "^22.10.2",
+ "@types/react": "^19.0.8",
+ "@types/react-dom": "^19.0.3",
+ "@typescript/native": "npm:typescript@^7.0.2",
+ "@vitejs/plugin-react": "^6.0.1",
+ "srvx": "^1.0.0",
+ "vite": "^8.0.14"
+ }
+}
diff --git a/e2e/react-start/route-modules/packages/web/route-modules.ts b/e2e/react-start/route-modules/packages/web/route-modules.ts
new file mode 100644
index 0000000000..40dc69e6f6
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/route-modules.ts
@@ -0,0 +1,28 @@
+/**
+ * The route modules the store installs, shared by the Vite and the Rsbuild
+ * configuration. `tests/workspace.ts` mirrors it for the generation tests.
+ */
+export const routeModules = {
+ includes: [
+ { module: '@start-route-modules/catalog', at: '/shop' },
+ { module: '@start-route-modules/notes', at: '/notes' },
+ {
+ module: '@start-route-modules/team',
+ parent: '/orgs/$orgId',
+ at: '/team',
+ },
+ // Installed twice: per organization and per person.
+ {
+ module: '@start-route-modules/settings',
+ parent: '/orgs/$orgId',
+ at: '/settings',
+ as: 'orgSettings',
+ },
+ {
+ module: '@start-route-modules/settings',
+ parent: '/people/$personId',
+ at: '/settings',
+ as: 'personSettings',
+ },
+ ],
+}
diff --git a/e2e/react-start/route-modules/packages/web/rsbuild.config.ts b/e2e/react-start/route-modules/packages/web/rsbuild.config.ts
new file mode 100644
index 0000000000..fcbb669602
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/rsbuild.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from '@rsbuild/core'
+import { pluginReact } from '@rsbuild/plugin-react'
+import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
+import { routeModules } from './route-modules'
+
+// The e2e build of each toolchain and mode writes to its own directory.
+const outDir = process.env.E2E_DIST_DIR ?? 'dist'
+
+export default defineConfig({
+ plugins: [pluginReact(), tanstackStart({ router: { routeModules } })],
+ output: {
+ distPath: {
+ root: outDir,
+ },
+ },
+})
diff --git a/e2e/react-start/route-modules/packages/web/server.js b/e2e/react-start/route-modules/packages/web/server.js
new file mode 100644
index 0000000000..3f18062992
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/server.js
@@ -0,0 +1,19 @@
+// Serves a production build of either toolchain: Vite writes the server
+// entry to `server/server.js`, Rsbuild to `server/index.js`.
+import { spawn } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import path from 'node:path'
+
+const distDir = process.env.E2E_DIST_DIR || 'dist'
+const serverEntry =
+ ['server.js', 'index.js']
+ .map((file) => path.resolve(distDir, 'server', file))
+ .find((file) => existsSync(file)) ??
+ path.resolve(distDir, 'server', 'server.js')
+
+const child = spawn(
+ 'srvx',
+ ['--prod', '-s', path.resolve(distDir, 'client'), serverEntry],
+ { stdio: 'inherit', shell: process.platform === 'win32' },
+)
+child.on('exit', (code) => process.exit(code ?? 0))
diff --git a/e2e/react-start/route-modules/packages/web/src/router.tsx b/e2e/react-start/route-modules/packages/web/src/router.tsx
new file mode 100644
index 0000000000..b54237fd92
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/src/router.tsx
@@ -0,0 +1,6 @@
+import { createRouter } from '@tanstack/react-router'
+import { routeTree } from './routeTree.gen'
+
+export function getRouter() {
+ return createRouter({ routeTree, scrollRestoration: true })
+}
diff --git a/e2e/react-start/route-modules/packages/web/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/web/src/routes/__root.tsx
new file mode 100644
index 0000000000..b6a3041deb
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/src/routes/__root.tsx
@@ -0,0 +1,90 @@
+///
+import * as React from 'react'
+import type { ReactNode } from 'react'
+import {
+ ClientOnly,
+ HeadContent,
+ Link,
+ Scripts,
+ createRootRoute,
+} from '@tanstack/react-router'
+import { catalog, notes, team } from '../routeScope.gen'
+import '../styles.css'
+
+// The router devtools, in development only.
+const RouterDevtools = import.meta.env.DEV
+ ? React.lazy(() =>
+ import('@tanstack/react-router-devtools').then((module) => ({
+ default: module.TanStackRouterDevtools,
+ })),
+ )
+ : () => null
+
+export const Route = createRootRoute({
+ head: () => ({
+ meta: [
+ { charSet: 'utf-8' },
+ { name: 'viewport', content: 'width=device-width, initial-scale=1' },
+ { title: 'Acme Store' },
+ ],
+ }),
+ shellComponent: RootDocument,
+})
+
+function RootDocument({ children }: { children: ReactNode }) {
+ return (
+
+
+
+
+
+
+
+
+ Acme Store
+
+
+ Catalog
+
+ Desk lamp
+
+ Notes
+
+ {/* The team is mounted below `/orgs/$orgId`: links into it pass `orgId`. */}
+
+ Acme team
+
+
+ Globex team
+
+
+
+ server-rendered
}>
+
+ hydrated
+
+
+
+ {children}
+
+
+
+
+
+
+ )
+}
+
+/** A small floor plan: outer walls with a door, two inner walls. */
+function PlanMark() {
+ return (
+
+
+
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/web/src/routes/index.tsx b/e2e/react-start/route-modules/packages/web/src/routes/index.tsx
new file mode 100644
index 0000000000..471165e1be
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/src/routes/index.tsx
@@ -0,0 +1,90 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { orgSettings, personSettings } from '../routeScope.gen'
+
+export const Route = createFileRoute('/')({
+ component: Home,
+})
+
+// A key plan of the store: every module's room where the store mounts it,
+// nested like the routes.
+function Home() {
+ return (
+ <>
+ Home
+
+ The Acme storefront, rendered on the server. Each region is a route
+ module, drawn as a room: its tag names the package and where the store
+ mounts it.
+
+
+
+
+ @start-route-modules/catalog /shop
+
+
+ Prices for the signed-in shopper, refreshed through a server
+ function.
+
+
+
+
+ @start-route-modules/notes /notes
+
+
A router-only module; the store serializes its data.
+
+ {/* The organization route is the store's own: the team below it gets
+ `orgId` from the URL. */}
+
+
+ Host route /orgs/$orgId
+
+
+
+
+ @start-route-modules/team /team
+
+
+ Members of the organization in the URL, loaded on the server.
+
+
+
+
+ @start-route-modules/settings#orgSettings /settings
+
+
+
+ Globex settings
+
+
+
+
+
+ {/* The settings are installed a second time, per person. */}
+
+
+ Host route /people/$personId
+
+
+
+
+ @start-route-modules/settings#personSettings{' '}
+ /settings
+
+
+
+ Ada's profile
+
+
+
+
+
+
+ >
+ )
+}
diff --git a/e2e/react-start/route-modules/packages/web/src/routes/orgs.$orgId.tsx b/e2e/react-start/route-modules/packages/web/src/routes/orgs.$orgId.tsx
new file mode 100644
index 0000000000..3c08aa0637
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/src/routes/orgs.$orgId.tsx
@@ -0,0 +1,15 @@
+import { Outlet, createFileRoute } from '@tanstack/react-router'
+
+// The host route of the modules mounted per organization: they get its path
+// params in their URLs and the organization as context, and its settings
+// installation the organization as their owner.
+export const Route = createFileRoute('/orgs/$orgId')({
+ beforeLoad: ({ params }) => {
+ const name = params.orgId.toUpperCase()
+ return {
+ org: { id: params.orgId, name },
+ owner: { kind: 'organization' as const, id: params.orgId, name },
+ }
+ },
+ component: () => ,
+})
diff --git a/e2e/react-start/route-modules/packages/web/src/routes/people.$personId.tsx b/e2e/react-start/route-modules/packages/web/src/routes/people.$personId.tsx
new file mode 100644
index 0000000000..19ac32e5c7
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/src/routes/people.$personId.tsx
@@ -0,0 +1,13 @@
+import { Outlet, createFileRoute } from '@tanstack/react-router'
+
+// The host route of the settings installation per person.
+export const Route = createFileRoute('/people/$personId')({
+ beforeLoad: ({ params }) => ({
+ owner: {
+ kind: 'person' as const,
+ id: params.personId,
+ name: params.personId[0]!.toUpperCase() + params.personId.slice(1),
+ },
+ }),
+ component: () => ,
+})
diff --git a/e2e/react-start/route-modules/packages/web/src/start.ts b/e2e/react-start/route-modules/packages/web/src/start.ts
new file mode 100644
index 0000000000..5d11d4c173
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/src/start.ts
@@ -0,0 +1,12 @@
+import { createMiddleware, createStart } from '@tanstack/react-start'
+import { startModules } from './startModules.gen'
+
+// Provides the request context the catalog requires.
+const shopper = createMiddleware().server(({ next }) =>
+ next({ context: { shopper: 'ada' } }),
+)
+
+export const startInstance = createStart(() => ({
+ extends: startModules,
+ requestMiddleware: [shopper],
+}))
diff --git a/e2e/react-start/route-modules/packages/web/src/styles.css b/e2e/react-start/route-modules/packages/web/src/styles.css
new file mode 100644
index 0000000000..e90577b1bd
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/src/styles.css
@@ -0,0 +1,486 @@
+/*
+ * Acme Store: the route-module fixtures drawn as a floor plan. Every route
+ * module is a room: a wall line, a zoning tint and a room tag with its package
+ * and mount path. Violet marks the active route and nothing else.
+ */
+
+:root {
+ color-scheme: light;
+
+ --ground: #f4f6f9;
+ --sheet: #ffffff;
+ --ink: #1f2328;
+ --ink-2: #4b535c;
+ --ink-3: #59616b;
+ --line: #d3d7db;
+ --wall: #2a3036;
+ --route: #5b3fd1;
+ --route-wash: #e9e5fb;
+ /* Link underlines: 3:1 or better on the ground and on every zone. */
+ --underline: color-mix(in srgb, var(--wall) 55%, transparent);
+ --zone: #eef0f2;
+
+ --font:
+ ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto,
+ 'Helvetica Neue', Arial, sans-serif;
+ /* Plan lettering: a local condensed face where there is one. */
+ --font-lettering:
+ 'Avenir Next Condensed', 'Roboto Condensed', 'Arial Narrow', ui-sans-serif,
+ system-ui, sans-serif;
+ --mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
+
+ --s1: 4px;
+ --s2: 8px;
+ --s3: 12px;
+ --s4: 16px;
+ --s5: 20px;
+ --s6: 24px;
+ --s8: 32px;
+ --s10: 40px;
+ --s12: 48px;
+
+ /* A drafted wall: two lines with the wall's thickness between them. */
+ --wall-line: 6px double var(--wall);
+ --ease-out: cubic-bezier(0.16, 1, 0.3, 1);
+}
+
+/* Zoning: one tint per module, as on a zoning plan. */
+[data-route-module='@start-route-modules/catalog'] {
+ --zone: #e1ebdd;
+}
+[data-route-module='@start-route-modules/notes'] {
+ --zone: #e7e9e4;
+}
+[data-route-module='@start-route-modules/team'] {
+ --zone: #d9eeeb;
+}
+[data-route-module='@start-route-modules/settings'] {
+ --zone: #efecd2;
+}
+
+*,
+*::before,
+*::after {
+ box-sizing: border-box;
+}
+
+html {
+ background: var(--ground);
+ scrollbar-color: var(--line) transparent;
+}
+
+body {
+ margin: 0;
+ color: var(--ink);
+ font: 400 15px/1.55 var(--font);
+ -webkit-font-smoothing: antialiased;
+}
+
+::selection {
+ background: var(--route-wash);
+ color: var(--ink);
+}
+
+:focus-visible {
+ outline: 2px solid var(--wall);
+ outline-offset: 2px;
+ border-radius: 2px;
+}
+
+h1,
+h2,
+h3 {
+ margin: 0 0 var(--s3);
+ font-weight: 650;
+ letter-spacing: -0.02em;
+ line-height: 1.2;
+ text-wrap: balance;
+}
+h1 {
+ font-size: 30px;
+}
+h2 {
+ font-size: 22px;
+}
+h3 {
+ font-size: 18px;
+}
+
+p {
+ margin: 0 0 var(--s3);
+ max-width: 68ch;
+}
+
+code {
+ font: 500 0.92em var(--mono);
+}
+
+a {
+ color: var(--ink);
+ text-decoration: underline;
+ text-decoration-color: var(--underline);
+ text-decoration-thickness: 1px;
+ text-underline-offset: 3px;
+ transition: text-decoration-color 160ms var(--ease-out);
+}
+a:hover {
+ text-decoration-color: var(--ink);
+}
+
+button {
+ font: inherit;
+}
+
+/* Shell */
+
+.topbar {
+ position: sticky;
+ top: 0;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ gap: var(--s8);
+ min-height: 52px;
+ padding: 0 var(--s6);
+ background: var(--sheet);
+ border-bottom: 1px solid var(--line);
+}
+
+.brand {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--s2);
+ font-weight: 650;
+ letter-spacing: -0.01em;
+ text-decoration: none;
+ white-space: nowrap;
+}
+.brand-mark {
+ flex: none;
+ width: 18px;
+ height: 18px;
+ color: var(--wall);
+}
+.brand small {
+ color: var(--ink-3);
+ font-size: 13px;
+ font-weight: 500;
+}
+
+.nav {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--s1) var(--s5);
+ font-size: 14px;
+}
+.nav a {
+ position: relative;
+ margin: 0 calc(-1 * var(--s1));
+ padding: var(--s3) var(--s1);
+ color: var(--ink-2);
+ text-decoration: none;
+}
+.nav a:hover {
+ color: var(--ink);
+}
+.nav a[data-status='active'] {
+ color: var(--route);
+}
+.nav a[data-status='active']::after {
+ content: '';
+ position: absolute;
+ inset: auto var(--s1) 0;
+ height: 2px;
+ background: var(--route);
+}
+.nav-group {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--s4);
+ padding-left: var(--s5);
+ border-left: 1px solid var(--line);
+}
+
+/* Whether the page has hydrated: a hollow plan dot until then. */
+.status {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--s2);
+ margin: 0 0 0 auto;
+ color: var(--ink-3);
+ font-size: 13px;
+ white-space: nowrap;
+}
+.status::before {
+ content: '';
+ width: 8px;
+ height: 8px;
+ border: 2px solid var(--ink-3);
+ border-radius: 50%;
+}
+.status.hydrated {
+ color: var(--ink);
+}
+.status.hydrated::before {
+ background: var(--wall);
+ border-color: var(--wall);
+}
+
+.page {
+ max-width: 1080px;
+ margin: 0 auto;
+ padding: var(--s10) var(--s6) 120px;
+}
+
+.lead {
+ color: var(--ink-2);
+ font-size: 17px;
+}
+
+/* Rooms: the signature. A module's region is a room with a wall line, its
+ zoning tint, and a tag on the wall naming the package and its mount. */
+
+.room {
+ margin-top: var(--s5);
+ padding: 0 var(--s6) var(--s6);
+ background: var(--zone) padding-box;
+ border: var(--wall-line);
+ animation: room-in 420ms var(--ease-out);
+}
+.room .room {
+ margin-top: var(--s8);
+}
+.room > :last-child {
+ margin-bottom: 0;
+}
+/* A room's title has one size whatever its level. */
+.room h1 {
+ font-size: 22px;
+}
+
+/* The tag sits on the wall: pulled up onto its center line, it wraps on
+ narrow screens instead of clipping the resolved path. Names and paths keep
+ their source case: they are identifiers maintainers copy. */
+.room-tag {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: baseline;
+ gap: 0 var(--s2);
+ width: fit-content;
+ max-width: 100%;
+ margin: -14px 0 var(--s5) calc(var(--s4) - var(--s6));
+ padding: 2px var(--s2);
+ background: var(--sheet);
+ border: 1px solid var(--wall);
+ font: 600 12px/16px var(--font-lettering);
+ font-stretch: condensed;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: 0.04em;
+}
+.room-tag code {
+ font: 500 11px/16px var(--mono);
+ color: var(--ink-2);
+}
+.room-tag .resolved {
+ color: var(--route);
+}
+
+@keyframes room-in {
+ from {
+ background-color: var(--sheet);
+ }
+}
+
+/* Lists, facts and controls inside rooms */
+
+.rows {
+ margin: 0 0 var(--s4);
+ padding: 0;
+ list-style: none;
+ font-variant-numeric: tabular-nums;
+ border-top: 1px solid color-mix(in srgb, var(--wall) 22%, transparent);
+}
+.rows > li {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: var(--s4);
+ padding: var(--s3) 0;
+ border-bottom: 1px solid color-mix(in srgb, var(--wall) 22%, transparent);
+}
+
+.rows .meta {
+ color: var(--ink-3);
+ font-size: 13px;
+}
+
+.facts {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ align-items: baseline;
+ gap: var(--s2) var(--s6);
+ margin: 0 0 var(--s5);
+ font-variant-numeric: tabular-nums;
+}
+.facts dt {
+ color: var(--ink-3);
+ font-size: 13px;
+}
+.facts dd {
+ margin: 0;
+}
+
+.actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--s3) var(--s5);
+}
+
+.button {
+ display: inline-flex;
+ align-items: center;
+ min-height: 36px;
+ padding: 0 var(--s4);
+ color: var(--sheet);
+ background: var(--wall);
+ border: 0;
+ border-radius: 6px;
+ font-weight: 600;
+ font-size: 14px;
+ cursor: pointer;
+ transition:
+ background-color 160ms var(--ease-out),
+ transform 160ms var(--ease-out);
+}
+.button:hover {
+ background: var(--ink);
+}
+.button:active {
+ transform: translateY(1px);
+}
+.button[aria-busy='true'] {
+ background: var(--ink-3);
+ cursor: progress;
+}
+
+.price {
+ margin: 0 0 var(--s4);
+ font-size: 22px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -0.01em;
+}
+
+.server-state {
+ margin: 0 0 var(--s5);
+ padding: var(--s3) 0;
+ border-block: 1px solid color-mix(in srgb, var(--wall) 22%, transparent);
+ color: var(--ink-2);
+ font-size: 14px;
+}
+.server-state p {
+ margin: 0;
+}
+
+.data {
+ font: 500 13px var(--mono);
+ font-variant-numeric: tabular-nums;
+}
+/* A value the server just sent again: one pass of a highlighter. */
+.fresh {
+ animation: fresh 1600ms var(--ease-out);
+}
+@keyframes fresh {
+ from {
+ background-color: #f7e7a1;
+ }
+}
+
+/* Key plan on the home page: every room where the application mounts it.
+ A host route that is not a module is a plot boundary around its rooms. */
+
+.plan {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ align-items: start;
+ gap: var(--s8) var(--s6);
+ margin-top: var(--s10);
+}
+.plan .room {
+ margin-top: 0;
+}
+.plan .room .room {
+ margin-top: var(--s6);
+}
+.plan .room > p:not(.room-tag) {
+ color: var(--ink-2);
+}
+.plot {
+ grid-column: 1 / -1;
+ padding: 0 var(--s6) var(--s6);
+ border: 1.5px dashed var(--ink-3);
+}
+.plot-rooms {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
+ align-items: start;
+ gap: var(--s8) var(--s6);
+ padding-top: var(--s3);
+}
+.plot > .room-tag {
+ margin-top: -12px;
+ margin-bottom: var(--s4);
+ border-style: dashed;
+ border-color: var(--ink-3);
+ font-weight: 500;
+}
+
+@media (max-width: 720px) {
+ .topbar {
+ position: static;
+ flex-wrap: wrap;
+ gap: 0 var(--s4);
+ padding: var(--s2) var(--s4) 0;
+ }
+ /* One scrolling row below the brand. */
+ .nav {
+ order: 1;
+ flex-basis: 100%;
+ flex-wrap: nowrap;
+ gap: var(--s2);
+ overflow-x: auto;
+ scrollbar-width: none;
+ }
+ .nav a,
+ .nav-group {
+ flex: none;
+ }
+ .nav-group {
+ gap: var(--s2);
+ padding-left: var(--s2);
+ }
+ .page {
+ padding: var(--s6) var(--s4) 120px;
+ }
+ .room {
+ padding: 0 var(--s4) var(--s4);
+ }
+ .room-tag {
+ margin-left: 0;
+ }
+ .plan {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ .plot {
+ padding: 0 var(--s4) var(--s4);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .room,
+ .fresh {
+ animation: none;
+ }
+}
diff --git a/e2e/react-start/route-modules/packages/web/tsconfig.json b/e2e/react-start/route-modules/packages/web/tsconfig.json
new file mode 100644
index 0000000000..30641bffe7
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ES2022",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": ["vite/client"]
+ },
+ "include": ["src", "vite.config.ts", "rsbuild.config.ts", "route-modules.ts"]
+}
diff --git a/e2e/react-start/route-modules/packages/web/vite.config.ts b/e2e/react-start/route-modules/packages/web/vite.config.ts
new file mode 100644
index 0000000000..9c60a3a87c
--- /dev/null
+++ b/e2e/react-start/route-modules/packages/web/vite.config.ts
@@ -0,0 +1,14 @@
+import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
+import { routeModules } from './route-modules'
+
+// The e2e build of each toolchain and mode writes to its own directory.
+const outDir = process.env.E2E_DIST_DIR ?? 'dist'
+
+export default defineConfig({
+ build: {
+ outDir,
+ },
+ plugins: [tanstackStart({ router: { routeModules } }), viteReact()],
+})
diff --git a/e2e/react-start/route-modules/playwright.config.ts b/e2e/react-start/route-modules/playwright.config.ts
new file mode 100644
index 0000000000..dea91cd1a1
--- /dev/null
+++ b/e2e/react-start/route-modules/playwright.config.ts
@@ -0,0 +1,31 @@
+import { defineConfig, devices } from '@playwright/test'
+import { appServerReady } from '@tanstack/router-e2e-utils'
+
+const PORT = Number(process.env.E2E_APP_PORT ?? 0)
+const baseURL = `http://localhost:${PORT}`
+// Nx builds the application with the toolchain of each mode into
+// `E2E_DIST_DIR` (`build::ssr` publishes the route modules first);
+// this serves that build. Module files are compiled from source by the
+// application.
+const command = `cd packages/web && NODE_ENV=production PORT=${PORT} pnpm start`
+
+export default defineConfig({
+ testDir: './e2e',
+ workers: 1,
+ reporter: [['line']],
+ use: {
+ baseURL,
+ },
+ webServer: {
+ command,
+ wait: appServerReady,
+ reuseExistingServer: false,
+ stdout: 'pipe',
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: { ...devices['Desktop Chrome'] },
+ },
+ ],
+})
diff --git a/e2e/react-start/route-modules/playwright.dev.config.ts b/e2e/react-start/route-modules/playwright.dev.config.ts
new file mode 100644
index 0000000000..2c920320a9
--- /dev/null
+++ b/e2e/react-start/route-modules/playwright.dev.config.ts
@@ -0,0 +1,30 @@
+import { defineConfig, devices } from '@playwright/test'
+import { appServerReady } from '@tanstack/router-e2e-utils'
+
+const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite'
+const PORT = Number(process.env.E2E_APP_PORT ?? 0)
+const baseURL = `http://localhost:${PORT}`
+// Development: the Start dev server of the toolchain renders module routes,
+// runs their server functions and hot-updates their files.
+const command = `node scripts/prepare.mjs && pnpm --filter @start-route-modules/web dev:${toolchain} --host 0.0.0.0 --port ${PORT}`
+
+export default defineConfig({
+ testDir: './e2e-dev',
+ workers: 1,
+ reporter: [['line']],
+ use: {
+ baseURL,
+ },
+ webServer: {
+ command,
+ wait: appServerReady,
+ reuseExistingServer: false,
+ stdout: 'pipe',
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: { ...devices['Desktop Chrome'] },
+ },
+ ],
+})
diff --git a/e2e/react-start/route-modules/scripts/prepare.mjs b/e2e/react-start/route-modules/scripts/prepare.mjs
new file mode 100644
index 0000000000..4e4c927b79
--- /dev/null
+++ b/e2e/react-start/route-modules/scripts/prepare.mjs
@@ -0,0 +1,43 @@
+// Generates routes and builds declarations with the packages' TypeScript
+// projects. The application's route tree is generated by the Start plugin.
+//
+// The modules list `@tanstack/router-core` (and the catalog
+// `@tanstack/start-client-core`) as dev dependencies only because the fixture
+// links the framework packages from the workspace: TypeScript names the types
+// of a linked package's dependencies by their own package name. Installed from
+// a registry, the declarations name them through `@tanstack/react-router` and
+// `@tanstack/react-start`, the only packages modules need.
+import { spawnSync } from 'node:child_process'
+import { rmSync } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { Generator, getConfig } from '@tanstack/router-generator'
+
+const packages = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../packages',
+)
+
+const tsc = path.resolve(
+ packages,
+ '../../../../node_modules/.bin',
+ process.platform === 'win32' ? 'tsc.cmd' : 'tsc',
+)
+
+for (const name of ['catalog', 'notes', 'settings', 'team']) {
+ const root = path.join(packages, name)
+ const config = getConfig({ disableLogging: true }, root)
+ await new Generator({ config, root }).run()
+ rmSync(path.join(root, '.tanstack/types'), { recursive: true, force: true })
+ const result = spawnSync(
+ tsc,
+ ['-p', 'tsconfig.route-types.json', '--pretty', 'false'],
+ { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' },
+ )
+ if (result.error) {
+ throw result.error
+ }
+ if (result.status !== 0) {
+ process.exit(result.status ?? 1)
+ }
+}
diff --git a/e2e/react-start/route-modules/tests/start-modules.test.ts b/e2e/react-start/route-modules/tests/start-modules.test.ts
new file mode 100644
index 0000000000..3b816a79ab
--- /dev/null
+++ b/e2e/react-start/route-modules/tests/start-modules.test.ts
@@ -0,0 +1,328 @@
+import path from 'node:path'
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import { Generator, getConfig } from '@tanstack/router-generator'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { Workspace, errorsIn } from './workspace'
+
+let workspace: Workspace
+
+beforeEach(() => {
+ workspace = new Workspace()
+})
+
+afterEach(() => {
+ workspace.dispose()
+})
+
+async function publishModules() {
+ for (const name of ['catalog', 'notes', 'settings', 'team']) {
+ const result = await workspace.publish(name)
+ expect(result.diagnostics, name).toEqual([])
+ }
+}
+
+describe('Start route modules', () => {
+ it.each([
+ {
+ specifier: 'http',
+ importedType: 'IncomingMessage',
+ requiredContext: '{ request: IncomingMessage }',
+ validConsumer:
+ 'export const method: string | undefined = context.request.method',
+ invalidConsumer: 'export const invalid: number = context.request.method',
+ },
+ {
+ specifier: '#request-context',
+ importedType: 'RequestContext',
+ requiredContext: 'RequestContext',
+ validConsumer: 'export const traceId: string = context.traceId',
+ invalidConsumer: 'export const invalid: number = context.traceId',
+ },
+ ])(
+ 'consumes published requirements that import $specifier',
+ async ({
+ specifier,
+ importedType,
+ requiredContext,
+ validConsumer,
+ invalidConsumer,
+ }) => {
+ const catalog = workspace.pkg('catalog')
+ const app = workspace.pkg('web')
+ rmSync(path.join(catalog, 'src'), { recursive: true, force: true })
+ mkdirSync(path.join(catalog, 'src/routes'), { recursive: true })
+ if (specifier === 'http') {
+ const nodeTypes = path.join(catalog, 'node_modules/@types/node')
+ mkdirSync(path.dirname(nodeTypes), { recursive: true })
+ if (!existsSync(nodeTypes)) {
+ symlinkSync(
+ realpathSync(
+ path.resolve(
+ import.meta.dirname,
+ '../../../../node_modules/@types/node',
+ ),
+ ),
+ nodeTypes,
+ 'dir',
+ )
+ }
+ workspace.edit('catalog', 'package.json', (source) => {
+ const pkg = JSON.parse(source)
+ pkg.devDependencies['@types/node'] = '*'
+ return JSON.stringify(pkg)
+ })
+ workspace.edit('catalog', 'tsconfig.json', (source) => {
+ const config = JSON.parse(source)
+ config.compilerOptions.types = ['node']
+ return JSON.stringify(config)
+ })
+ } else {
+ mkdirSync(path.join(catalog, 'types'), { recursive: true })
+ writeFileSync(
+ path.join(catalog, 'types/request-context.d.ts'),
+ 'export interface RequestContext { traceId: string }\n',
+ )
+ workspace.edit('catalog', 'package.json', (source) => {
+ const pkg = JSON.parse(source)
+ pkg.imports = { '#request-context': './types/request-context.d.ts' }
+ return JSON.stringify(pkg)
+ })
+ }
+ writeFileSync(
+ path.join(catalog, 'src/requirements.ts'),
+ `export type { StartModuleRequirements } from '@tanstack/react-start'
+import type { ${importedType} } from '${specifier}'
+declare module '@tanstack/react-start' {
+ interface StartModuleRequirements {
+ '@start-route-modules/catalog': { requestContext: ${requiredContext} }
+ }
+}
+`,
+ )
+ writeFileSync(
+ path.join(catalog, 'src/routes/__root.tsx'),
+ `export type {} from '../requirements'
+import { createModuleRoot } from '../routeScope.gen'
+export const Route = createModuleRoot()({})
+`,
+ )
+ const published = await workspace.publish('catalog')
+ expect(published.diagnostics).toEqual([])
+ expect(
+ readFileSync(
+ path.join(catalog, '.tanstack/types/src/requirements.d.ts'),
+ 'utf8',
+ ),
+ ).toContain(`from '${specifier}'`)
+
+ rmSync(path.join(app, 'src'), { recursive: true, force: true })
+ mkdirSync(path.join(app, 'src/routes'), { recursive: true })
+ writeFileSync(
+ path.join(app, 'src/routes/__root.tsx'),
+ `import { createRootRoute } from '@tanstack/react-router'
+export const Route = createRootRoute()
+`,
+ )
+ writeFileSync(
+ path.join(app, 'src/request-context.ts'),
+ `import type { StartModuleRequirements } from '@tanstack/react-start'
+type RequiredContext = StartModuleRequirements['@start-route-modules/catalog']['requestContext']
+declare module '@tanstack/react-start' {
+ interface Register { server: { requestContext: RequiredContext } }
+}
+declare const context: RequiredContext
+${validConsumer}
+// @ts-expect-error Published requirement imports preserve their field types.
+${invalidConsumer}
+`,
+ )
+ workspace.edit('web', 'tsconfig.json', (source) => {
+ const config = JSON.parse(source)
+ config.compilerOptions.skipLibCheck = false
+ config.compilerOptions.types = ['node']
+ config.include = ['src']
+ return JSON.stringify(config)
+ })
+ await new Generator({
+ root: app,
+ config: getConfig(
+ {
+ disableLogging: true,
+ routeModules: { includes: ['@start-route-modules/catalog'] },
+ },
+ app,
+ ),
+ }).run()
+ rmSync(path.join(catalog, 'src'), { recursive: true, force: true })
+ expect(workspace.checkApp().diagnostics).toEqual([])
+ },
+ )
+
+ it('checks published requirements-only modules against the default Start instance', async () => {
+ const catalog = workspace.pkg('catalog')
+ const app = workspace.pkg('web')
+ rmSync(path.join(catalog, 'src'), { recursive: true, force: true })
+ mkdirSync(path.join(catalog, 'src/routes'), { recursive: true })
+ writeFileSync(
+ path.join(catalog, 'src/requirements.ts'),
+ `export type { StartModuleRequirements } from '@tanstack/react-start'
+declare module '@tanstack/react-start' {
+ interface StartModuleRequirements {
+ '@start-route-modules/catalog': { requestContext: { shopper: string } }
+ }
+}
+`,
+ )
+ writeFileSync(
+ path.join(catalog, 'src/routes/__root.tsx'),
+ `export type {} from '../requirements'
+import { createModuleRoot } from '../routeScope.gen'
+export const Route = createModuleRoot()({})
+`,
+ )
+ writeFileSync(
+ path.join(catalog, 'src/routes/index.tsx'),
+ `import { createFileRoute } from '../routeScope.gen'
+export const Route = createFileRoute('@start-route-modules/catalog:/')({})
+`,
+ )
+ const published = await workspace.publish('catalog')
+ expect(published.diagnostics).toEqual([])
+
+ rmSync(path.join(app, 'src'), { recursive: true, force: true })
+ mkdirSync(path.join(app, 'src/routes'), { recursive: true })
+ writeFileSync(
+ path.join(app, 'src/routes/__root.tsx'),
+ `import { createRootRoute } from '@tanstack/react-router'
+export const Route = createRootRoute()
+`,
+ )
+ workspace.edit('web', 'tsconfig.json', (source) => {
+ const config = JSON.parse(source)
+ config.compilerOptions.skipLibCheck = false
+ config.compilerOptions.types = ['node']
+ config.include = ['src']
+ return JSON.stringify(config)
+ })
+ await new Generator({
+ root: app,
+ config: getConfig(
+ {
+ disableLogging: true,
+ routeModules: {
+ includes: [
+ {
+ module: '@start-route-modules/catalog',
+ as: 'requirementsOnly',
+ at: '/catalog',
+ },
+ ],
+ },
+ },
+ app,
+ ),
+ }).run()
+
+ // Consumer checking must load the augmentation from the published contract.
+ rmSync(path.join(catalog, 'src'), { recursive: true, force: true })
+ const missing = workspace.checkApp()
+ expect(missing.ok).toBe(false)
+ expect(
+ errorsIn(missing.diagnostics, 'startModules.gen.ts').join('\n'),
+ ).toContain(
+ "Route module '@start-route-modules/catalog' requires request context 'shopper' that is not provided from application middleware",
+ )
+
+ // handler.fetch can satisfy requirements without a custom Start instance.
+ writeFileSync(
+ path.join(app, 'src/request-context.ts'),
+ `import '@tanstack/react-start'
+declare module '@tanstack/react-start' {
+ interface Register {
+ server: { requestContext: { shopper: string } }
+ }
+}
+`,
+ )
+ expect(workspace.checkApp().diagnostics).toEqual([])
+ })
+
+ it('the application type-checks against the published modules', async () => {
+ await publishModules()
+ await workspace.generateApp()
+
+ expect((await workspace.checkApp()).diagnostics).toEqual([])
+ })
+
+ it('the application must provide the request context a module requires', async () => {
+ await publishModules()
+ workspace.edit('web', 'src/start.ts', (source) =>
+ source.replace(' requestMiddleware: [shopper],\n', ''),
+ )
+ await workspace.generateApp()
+
+ const result = await workspace.checkApp()
+ expect(result.ok).toBe(false)
+ expect(
+ errorsIn(result.diagnostics, 'startModules.gen.ts').join('\n'),
+ ).toContain(
+ "Route module '@start-route-modules/catalog' requires request context 'shopper' that is not provided from application middleware",
+ )
+ })
+
+ it('the application must install the fragments of its modules', async () => {
+ await publishModules()
+ workspace.edit('web', 'src/start.ts', (source) =>
+ source.replace(' extends: startModules,\n', ''),
+ )
+ await workspace.generateApp()
+
+ const result = await workspace.checkApp()
+ expect(result.ok).toBe(false)
+ expect(
+ errorsIn(result.diagnostics, 'startModules.gen.ts').join('\n'),
+ ).toContain(
+ "Route module '@start-route-modules/catalog' is not installed: add 'extends: startModules' to createStart()",
+ )
+ })
+
+ it("a module's server functions and loaders are validated against its fragment", async () => {
+ workspace.edit('catalog', 'src/start.ts', (source) =>
+ source.replace(' serializationAdapters: [moneyAdapter],\n', ''),
+ )
+
+ const result = await workspace.publish('catalog')
+ expect(result.ok).toBe(false)
+ // `Money` has a method, so it is only serializable with the adapter.
+ const diagnostics = result.diagnostics.join('\n')
+ expect(diagnostics).toMatch(/src\/api\.ts\(\d+,\d+\): error TS2345/)
+ expect(diagnostics).toContain('Function may not be serializable')
+ })
+
+ it("the application serializes a router-only module's results", async () => {
+ workspace.edit('notes', 'src/routes/index.tsx', (source) =>
+ source.replace(
+ "loader: () => ({ notes: ['Compose route modules', 'Ship it'] }),",
+ "loader: () => ({ notes: ['Compose route modules'], open: () => {} }),",
+ ),
+ )
+ await publishModules()
+ await workspace.generateApp()
+
+ const result = await workspace.checkApp()
+ expect(result.ok).toBe(false)
+ expect(
+ errorsIn(result.diagnostics, 'routeTree.gen.ts').join('\n'),
+ ).toContain(
+ "Route module '@start-route-modules/notes' returns loader or beforeLoad results from '@start-route-modules/notes:/' that the application cannot serialize",
+ )
+ })
+})
diff --git a/e2e/react-start/route-modules/tests/workspace.ts b/e2e/react-start/route-modules/tests/workspace.ts
new file mode 100644
index 0000000000..da4a3bf628
--- /dev/null
+++ b/e2e/react-start/route-modules/tests/workspace.ts
@@ -0,0 +1,225 @@
+import path from 'node:path'
+import os from 'node:os'
+import crypto from 'node:crypto'
+import { spawnSync } from 'node:child_process'
+import {
+ cpSync,
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { Generator, getConfig } from '@tanstack/router-generator'
+
+const here = path.dirname(fileURLToPath(import.meta.url))
+const fixtureRoot = path.resolve(here, '../packages')
+const repoRoot = path.resolve(here, '../../../..')
+/** The repository's TypeScript compiler (`tsc` of `@typescript/native`). */
+const tsc = path.join(repoRoot, 'node_modules', '.bin', 'tsc')
+
+const workspaceScope = '@start-route-modules/'
+const generatedFile = /\.gen(?:\.[^.]+)?\.tsx?$/
+
+/** The application's route modules (`vite.config.ts`). */
+const routeModules = {
+ includes: [
+ { module: '@start-route-modules/catalog', at: '/shop' },
+ { module: '@start-route-modules/notes', at: '/notes' },
+ {
+ module: '@start-route-modules/team',
+ parent: '/orgs/$orgId',
+ at: '/team',
+ },
+ {
+ module: '@start-route-modules/settings',
+ parent: '/orgs/$orgId',
+ at: '/settings',
+ as: 'orgSettings',
+ },
+ {
+ module: '@start-route-modules/settings',
+ parent: '/people/$personId',
+ at: '/settings',
+ as: 'personSettings',
+ },
+ ],
+}
+
+/** The route tree footer the TanStack Start plugin generates. */
+const startFooter = [
+ `import type { getRouter } from './router.tsx'
+import type { startInstance } from './start.ts'
+declare module '@tanstack/react-start' {
+ interface Register {
+ ssr: true
+ router: Awaited>
+ config: Awaited>
+ }
+}`,
+]
+
+function listDependencies(nodeModules: string): Array {
+ if (!existsSync(nodeModules)) {
+ return []
+ }
+ const entries: Array = []
+ for (const entry of readdirSync(nodeModules)) {
+ if (entry.startsWith('.')) {
+ continue
+ }
+ if (entry.startsWith('@')) {
+ for (const scoped of readdirSync(path.join(nodeModules, entry))) {
+ entries.push(`${entry}/${scoped}`)
+ }
+ } else {
+ entries.push(entry)
+ }
+ }
+ return entries
+}
+
+/**
+ * A copy of the fixture packages in a temporary directory. Workspace route
+ * modules are linked to their copies; every other dependency is linked to the
+ * package the repository installed. Nothing generated is copied.
+ */
+export class Workspace {
+ readonly root: string
+
+ constructor() {
+ const dir = path.join(
+ os.tmpdir(),
+ `tsr-start-route-modules-${crypto.randomBytes(4).toString('hex')}`,
+ )
+ mkdirSync(dir, { recursive: true })
+ this.root = realpathSync(dir)
+ for (const name of ['catalog', 'notes', 'settings', 'team', 'web']) {
+ this.addPackage(name)
+ }
+ }
+
+ private addPackage(name: string) {
+ const from = path.join(fixtureRoot, name)
+ const to = this.pkg(name)
+ cpSync(from, to, {
+ recursive: true,
+ filter: (file) =>
+ !file.includes(`${path.sep}node_modules`) &&
+ !file.includes(`${path.sep}.tanstack`) &&
+ !file.includes(`${path.sep}dist`) &&
+ !generatedFile.test(file),
+ })
+ for (const dependency of listDependencies(
+ path.join(from, 'node_modules'),
+ )) {
+ const link = path.join(to, 'node_modules', dependency)
+ mkdirSync(path.dirname(link), { recursive: true })
+ const target = dependency.startsWith(workspaceScope)
+ ? this.pkg(dependency.slice(workspaceScope.length))
+ : realpathSync(path.join(from, 'node_modules', dependency))
+ symlinkSync(target, link, 'dir')
+ }
+ }
+
+ pkg(name: string) {
+ return path.join(this.root, name)
+ }
+
+ edit(name: string, file: string, edit: (content: string) => string) {
+ const full = path.join(this.pkg(name), file)
+ const before = readFileSync(full, 'utf8')
+ const after = edit(before)
+ if (after === before) {
+ throw new Error(`The edit of ${name}/${file} changed nothing`)
+ }
+ writeFileSync(full, after)
+ }
+
+ /** Generates and publishes a route module. */
+ async publish(name: string) {
+ const root = this.pkg(name)
+ await new Generator({
+ config: getConfig({ disableLogging: true }, root),
+ root,
+ }).run()
+ const project = JSON.parse(
+ readFileSync(path.join(root, 'tsconfig.route-types.json'), 'utf8'),
+ )
+ rmSync(
+ path.resolve(
+ root,
+ project.compilerOptions.declarationDir ??
+ project.compilerOptions.outDir,
+ ),
+ { recursive: true, force: true },
+ )
+ return this.compile(name, ['-p', 'tsconfig.route-types.json'])
+ }
+
+ /** Generates the application's route tree like the Start plugin does. */
+ async generateApp() {
+ const root = this.pkg('web')
+ const config = getConfig(
+ {
+ disableLogging: true,
+ target: 'react',
+ routeModules,
+ routeTreeFileFooter: startFooter,
+ },
+ root,
+ )
+ await new Generator({ config, root }).run()
+ }
+
+ /** Type-checks the application against the published modules. */
+ checkApp() {
+ return this.compile('web', ['-p', 'tsconfig.json', '--noEmit'])
+ }
+
+ private compile(name: string, args: Array) {
+ const result = spawnSync(tsc, [...args, '--pretty', 'false'], {
+ cwd: this.pkg(name),
+ encoding: 'utf8',
+ })
+ return {
+ ok: result.status === 0,
+ diagnostics: result.error
+ ? [result.error.message]
+ : `${result.stdout ?? ''}${result.stderr ?? ''}`
+ .split(/\r?\n/)
+ .filter((line) => line.trim() !== ''),
+ }
+ }
+
+ dispose() {
+ rmSync(this.root, { recursive: true, force: true })
+ }
+}
+
+/** The diagnostics of a failed check that point into `file`. */
+export function errorsIn(diagnostics: Array, file: string) {
+ const errors: Array = []
+ let current: string | undefined
+ for (const line of diagnostics) {
+ if (/^\s/.test(line)) {
+ if (current !== undefined) {
+ current += `\n${line}`
+ }
+ continue
+ }
+ if (current !== undefined) {
+ errors.push(current)
+ }
+ current =
+ line.startsWith(file) || line.includes(`/${file}(`) ? line : undefined
+ }
+ if (current !== undefined) {
+ errors.push(current)
+ }
+ return errors
+}
diff --git a/e2e/react-start/route-modules/tsconfig.json b/e2e/react-start/route-modules/tsconfig.json
new file mode 100644
index 0000000000..341902faed
--- /dev/null
+++ b/e2e/react-start/route-modules/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": [
+ "tests",
+ "e2e",
+ "e2e-dev",
+ "scripts",
+ "vitest.config.ts",
+ "playwright.config.ts",
+ "playwright.dev.config.ts"
+ ]
+}
diff --git a/e2e/react-start/route-modules/vitest.config.ts b/e2e/react-start/route-modules/vitest.config.ts
new file mode 100644
index 0000000000..a2233ebb31
--- /dev/null
+++ b/e2e/react-start/route-modules/vitest.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.ts'],
+ // Each test runs the generator and the TypeScript compiler on a workspace.
+ testTimeout: 120_000,
+ hookTimeout: 120_000,
+ fileParallelism: false,
+ },
+})
diff --git a/e2e/solid-router/route-modules/.gitignore b/e2e/solid-router/route-modules/.gitignore
new file mode 100644
index 0000000000..18dd57830b
--- /dev/null
+++ b/e2e/solid-router/route-modules/.gitignore
@@ -0,0 +1,2 @@
+# Generated during the e2e preparation/build, never checked in.
+**/route*.gen*.ts
diff --git a/e2e/solid-router/route-modules/e2e/scope-parity.spec.ts b/e2e/solid-router/route-modules/e2e/scope-parity.spec.ts
new file mode 100644
index 0000000000..9df66d1848
--- /dev/null
+++ b/e2e/solid-router/route-modules/e2e/scope-parity.spec.ts
@@ -0,0 +1,177 @@
+import { expect } from '@playwright/test'
+import { test } from '@tanstack/router-e2e-utils'
+
+for (const base of ['/orgs/7/settings', '/users/u1/settings']) {
+ test(`RouteApi and custom links resolve ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await expect(
+ page.getByRole('link', { name: 'API members' }),
+ ).toHaveAttribute('href', `${base}/members`)
+ await expect(
+ page.getByRole('link', { name: 'Custom members' }),
+ ).toHaveAttribute('href', `${base}/members`)
+ expect(
+ await page
+ .getByRole('link', { name: 'API members' })
+ .getAttribute('_module'),
+ ).toBeNull()
+ expect(
+ await page
+ .getByRole('link', { name: 'Custom members' })
+ .getAttribute('_module'),
+ ).toBeNull()
+ const hostId = base.split('/')[2]!
+ const hostParams = base.startsWith('/orgs/')
+ ? { orgId: hostId }
+ : base.startsWith('/people/')
+ ? { personId: hostId }
+ : { userId: hostId }
+ await expect(page.getByTestId('runtime-params')).toHaveText(
+ JSON.stringify(hostParams),
+ )
+ await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible()
+ await expect(page.getByText('MEMBERS_MATCH', { exact: true })).toHaveCount(
+ 0,
+ )
+ await page.getByRole('link', { name: 'API members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test(`useLinkProps navigates within the document under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ await expect(
+ page.getByRole('link', { name: 'Custom members' }),
+ ).toBeVisible()
+ const documentRequests: Array = []
+ page.on('request', (request) => {
+ if (
+ request.isNavigationRequest() &&
+ request.frame() === page.mainFrame()
+ ) {
+ documentRequests.push(request.url())
+ }
+ })
+ await page.getByRole('link', { name: 'Custom members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ expect(documentRequests).toEqual([])
+ })
+
+ test(`RouteApi navigation resolves ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await page.getByRole('button', { name: 'Navigate members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test(`Navigate captures installation under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/forward`)
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test(`component notFound reaches module boundary under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/missing`)
+ await expect(page.getByText('MODULE_NOT_FOUND')).toBeVisible()
+ })
+ for (const button of ['Route up', 'Explicit from home']) {
+ test(`${button} uses the route origin under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await page.getByRole('button', { name: button, exact: true }).click()
+ await expect(page).toHaveURL(base)
+ await expect(
+ page.getByRole('link', { name: 'Profile', exact: true }),
+ ).toHaveAttribute('href', `${base}/profile`)
+ })
+ }
+
+ test(`scoped router view builds and navigates under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ await expect(page.getByTestId('scoped-href')).toHaveText(`${base}/members`)
+ await page.getByRole('button', { name: 'Router members' }).click()
+ await expect(page).toHaveURL(`${base}/members`)
+ const profile = page.getByRole('link', { name: 'Profile', exact: true })
+ await expect(profile).toHaveAttribute('href', `${base}/profile`)
+ await profile.click()
+ await expect(page).toHaveURL(`${base}/profile`)
+ })
+
+ test(`Route.Link keeps the installation under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ const home = page.getByRole('link', { name: 'Route home', exact: true })
+ await expect(home).toHaveAttribute('href', base)
+ await home.click()
+ await expect(page).toHaveURL(base)
+ await expect(
+ page.getByRole('link', { name: 'Profile', exact: true }),
+ ).toHaveAttribute('href', `${base}/profile`)
+ })
+
+ test(`scoped lifecycle redirects retain the installation under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/legacy`)
+ await expect(page).toHaveURL(`${base}/profile`)
+ await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible()
+ })
+
+ test(`framework imports keep application coordinates inside ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ const host = page.getByRole('link', { name: 'Application host' })
+ await expect(host).toHaveAttribute('href', '/orgs/9')
+ await host.click()
+ await expect(page).toHaveURL('/orgs/9')
+ })
+}
+
+test('module observers and router views follow real installation changes', async ({
+ page,
+}) => {
+ await page.goto('/orgs/7/settings/profile')
+ await expect(page.getByTestId('organization-profile')).toHaveText(
+ '@route-modules/solid-settings#orgSettings:/profile',
+ )
+ await expect(page.getByTestId('scoped-href')).toHaveText(
+ '/orgs/7/settings/members',
+ )
+ await page.getByRole('link', { name: 'API members' }).click()
+ await expect(page).toHaveURL('/orgs/7/settings/members')
+ await page.getByRole('link', { name: 'Switch to person' }).click()
+ await expect(page).toHaveURL('/users/u1/settings/profile')
+ await expect(page.getByTestId('organization-profile')).toHaveText('none')
+ await expect(page.getByTestId('scoped-href')).toHaveText(
+ '/users/u1/settings/members',
+ )
+ await page.getByRole('link', { name: 'Switch to organization' }).click()
+ await expect(page).toHaveURL('/orgs/7/settings/profile')
+ await expect(page.getByRole('link', { name: 'API members' })).toHaveAttribute(
+ 'href',
+ '/orgs/7/settings/members',
+ )
+ const readObserved = () =>
+ page.evaluate(
+ () =>
+ (
+ window as Window & {
+ observedModuleMatches: Array
+ }
+ ).observedModuleMatches,
+ )
+ await expect
+ .poll(readObserved)
+ .toContain('@route-modules/solid-settings#userSettings:/profile')
+ const observed = await readObserved()
+ expect(observed).toContain(
+ '@route-modules/solid-settings#orgSettings:/profile',
+ )
+ expect(observed).not.toContain(undefined)
+})
diff --git a/e2e/solid-router/route-modules/index.html b/e2e/solid-router/route-modules/index.html
new file mode 100644
index 0000000000..5a5556330e
--- /dev/null
+++ b/e2e/solid-router/route-modules/index.html
@@ -0,0 +1,11 @@
+
+
+
+
+ Route module contracts
+
+
+
+
+
+
diff --git a/e2e/solid-router/route-modules/package.json b/e2e/solid-router/route-modules/package.json
new file mode 100644
index 0000000000..e04e7428a9
--- /dev/null
+++ b/e2e/solid-router/route-modules/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "tanstack-router-e2e-solid-route-modules",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "generate": "node scripts/prepare.mjs",
+ "build": "node scripts/prepare.mjs && vite build && tsc --noEmit && tsc -p packages/settings/tsconfig.json --noEmit",
+ "preview": "vite preview",
+ "dev:e2e": "node scripts/prepare.mjs && vite",
+ "test:e2e": "playwright test --project=chromium"
+ },
+ "dependencies": {
+ "@route-modules/solid-settings": "workspace:*",
+ "@tanstack/solid-router": "workspace:^",
+ "solid-js": "^1.9.10"
+ },
+ "devDependencies": {
+ "@playwright/test": "^1.61.0",
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@tanstack/router-e2e-utils": "workspace:^",
+ "@tanstack/router-generator": "workspace:^",
+ "@tanstack/router-plugin": "workspace:^",
+ "@types/node": "catalog:",
+ "vite": "^8.0.14",
+ "vitest": "catalog:",
+ "vite-plugin-solid": "^2.11.11"
+ }
+}
diff --git a/e2e/solid-router/route-modules/packages/settings/package.json b/e2e/solid-router/route-modules/packages/settings/package.json
new file mode 100644
index 0000000000..7fbb8ecee5
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/package.json
@@ -0,0 +1,37 @@
+{
+ "name": "@route-modules/solid-settings",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./scope": {
+ "types": "./.tanstack/types/src/routeScope.gen.d.ts",
+ "default": "./src/routeScope.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/solid-router": "workspace:^",
+ "solid-js": "^1.9.10"
+ },
+ "devDependencies": {
+ "@tanstack/router-core": "workspace:^",
+ "@tanstack/router-cli": "workspace:^"
+ }
+}
diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/__root.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/__root.tsx
new file mode 100644
index 0000000000..dd5fc7db8b
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/src/routes/__root.tsx
@@ -0,0 +1,8 @@
+import { Outlet } from '@tanstack/solid-router'
+import { createModuleRoot } from '../routeScope.gen'
+export const Route = createModuleRoot<{
+ onProfileMatch?: (routeId: string | undefined) => void
+}>()({
+ component: () => ,
+ notFoundComponent: () => MODULE_NOT_FOUND
,
+})
diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/forward.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/forward.tsx
new file mode 100644
index 0000000000..dfeb7629ae
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/src/routes/forward.tsx
@@ -0,0 +1,4 @@
+import { createFileRoute, Navigate } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/solid-settings:/forward')({
+ component: () => ,
+})
diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/index.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/index.tsx
new file mode 100644
index 0000000000..49521d0f90
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/src/routes/index.tsx
@@ -0,0 +1,4 @@
+import { createFileRoute, Link } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/solid-settings:/')({
+ component: () => Profile,
+})
diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/legacy.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/legacy.tsx
new file mode 100644
index 0000000000..03de793835
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/src/routes/legacy.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute, redirect } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/solid-settings:/legacy')({
+ beforeLoad: () => {
+ throw redirect({ to: '/profile' })
+ },
+})
diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/members.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/members.tsx
new file mode 100644
index 0000000000..7675c942c8
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/src/routes/members.tsx
@@ -0,0 +1,11 @@
+import { createFileRoute, getRouteApi } from '../routeScope.gen'
+const ProfileLink = getRouteApi('@route-modules/solid-settings:/profile').Link
+export const Route = createFileRoute('@route-modules/solid-settings:/members')({
+ loader: () => ({ label: 'members' as const }),
+ component: () => (
+ <>
+ MEMBERS_PAGE
+ Profile
+ >
+ ),
+})
diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/missing.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/missing.tsx
new file mode 100644
index 0000000000..cc90818852
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/src/routes/missing.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute, notFound } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/solid-settings:/missing')({
+ component: () => {
+ throw notFound({ routeId: '@route-modules/solid-settings:' })
+ },
+})
diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/profile.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/profile.tsx
new file mode 100644
index 0000000000..352cf6b63f
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/src/routes/profile.tsx
@@ -0,0 +1,56 @@
+import { createRenderEffect } from 'solid-js'
+import { Link as ApplicationLink } from '@tanstack/solid-router'
+import {
+ createFileRoute,
+ getRouteApi,
+ MatchRoute,
+ useLinkProps,
+ useNavigate,
+ useRouter,
+} from '../routeScope.gen'
+const api = getRouteApi('@route-modules/solid-settings:/profile')
+export const Route = createFileRoute('@route-modules/solid-settings:/profile')({
+ component: () => {
+ const navigate = api.useNavigate()
+ const routeNavigate = Route.useNavigate()
+ const relativeNavigate = useNavigate({ from: '/profile' })
+ const anchor = useLinkProps({ to: '/members' })
+ const match = Route.useMatch({ shouldThrow: false })
+ const scopedRouter = useRouter()
+ const observe = scopedRouter.options.context?.onProfileMatch
+ createRenderEffect(() => observe?.(match()?.routeId))
+ return (
+ <>
+ {match()?.routeId}
+
+ {JSON.stringify(match()?.params)}
+
+ API members
+ navigate({ to: '/members' })}>
+ Navigate members
+
+ Custom members
+
+ PROFILE_MATCH
+
+
+ MEMBERS_MATCH
+
+
+ {scopedRouter.buildLocation({ to: '/members' }).href}
+
+ scopedRouter.navigate({ to: '/members' })}>
+ Router members
+
+ routeNavigate({ to: '..' })}>Route up
+ relativeNavigate({ to: '..' })}>
+ Explicit from home
+
+ Route home
+
+ Application host
+
+ >
+ )
+ },
+})
diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/search.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/search.tsx
new file mode 100644
index 0000000000..4b7cf73052
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/src/routes/search.tsx
@@ -0,0 +1,4 @@
+import { createFileRoute } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/solid-settings:/search')({
+ validateSearch: (search: { query: string }) => search,
+})
diff --git a/e2e/solid-router/route-modules/packages/settings/tsconfig.json b/e2e/solid-router/route-modules/packages/settings/tsconfig.json
new file mode 100644
index 0000000000..c77693ae51
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/solid-router/route-modules/packages/settings/tsconfig.route-types.json b/e2e/solid-router/route-modules/packages/settings/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/solid-router/route-modules/packages/settings/tsr.config.json b/e2e/solid-router/route-modules/packages/settings/tsr.config.json
new file mode 100644
index 0000000000..078264aa1f
--- /dev/null
+++ b/e2e/solid-router/route-modules/packages/settings/tsr.config.json
@@ -0,0 +1,3 @@
+{
+ "target": "solid"
+}
diff --git a/e2e/solid-router/route-modules/playwright.config.ts b/e2e/solid-router/route-modules/playwright.config.ts
new file mode 100644
index 0000000000..56f2d789b1
--- /dev/null
+++ b/e2e/solid-router/route-modules/playwright.config.ts
@@ -0,0 +1,17 @@
+import { defineConfig, devices } from '@playwright/test'
+import { appServerReady } from '@tanstack/router-e2e-utils'
+
+const PORT = Number(process.env.E2E_APP_PORT ?? 0)
+export default defineConfig({
+ testDir: './e2e',
+ workers: 1,
+ reporter: [['line']],
+ use: { baseURL: `http://localhost:${PORT}` },
+ webServer: {
+ command: `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}`,
+ wait: appServerReady,
+ reuseExistingServer: false,
+ stdout: 'pipe',
+ },
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+})
diff --git a/e2e/solid-router/route-modules/scripts/prepare.mjs b/e2e/solid-router/route-modules/scripts/prepare.mjs
new file mode 100644
index 0000000000..c7bad5c894
--- /dev/null
+++ b/e2e/solid-router/route-modules/scripts/prepare.mjs
@@ -0,0 +1,28 @@
+import { spawnSync } from 'node:child_process'
+import { rmSync } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { Generator, getConfig } from '@tanstack/router-generator'
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const provider = path.join(root, 'packages/settings')
+await new Generator({
+ config: getConfig({ disableLogging: true }, provider),
+ root: provider,
+}).run()
+rmSync(path.join(provider, '.tanstack/types'), { recursive: true, force: true })
+const result = spawnSync(
+ 'pnpm',
+ ['exec', 'tsc', '-p', 'tsconfig.route-types.json', '--pretty', 'false'],
+ { cwd: provider, stdio: 'inherit', shell: process.platform === 'win32' },
+)
+if (result.error) {
+ throw result.error
+}
+if (result.status !== 0) {
+ process.exit(result.status ?? 1)
+}
+await new Generator({
+ config: getConfig({ disableLogging: true }, root),
+ root,
+}).run()
diff --git a/e2e/solid-router/route-modules/src/main.tsx b/e2e/solid-router/route-modules/src/main.tsx
new file mode 100644
index 0000000000..9f01709fdb
--- /dev/null
+++ b/e2e/solid-router/route-modules/src/main.tsx
@@ -0,0 +1,19 @@
+import { render } from 'solid-js/web'
+import { RouterProvider, createRouter } from '@tanstack/solid-router'
+import { routeTree } from './routeTree.gen'
+
+const observedModuleMatches: Array = []
+Object.assign(window, { observedModuleMatches })
+const router = createRouter({
+ routeTree,
+ context: { onProfileMatch: (routeId) => observedModuleMatches.push(routeId) },
+})
+declare module '@tanstack/solid-router' {
+ interface Register {
+ router: typeof router
+ }
+}
+render(
+ () => ,
+ document.getElementById('app')!,
+)
diff --git a/e2e/solid-router/route-modules/src/routes/__root.tsx b/e2e/solid-router/route-modules/src/routes/__root.tsx
new file mode 100644
index 0000000000..fbc4f195e7
--- /dev/null
+++ b/e2e/solid-router/route-modules/src/routes/__root.tsx
@@ -0,0 +1,29 @@
+import { createRootRouteWithContext, Outlet } from '@tanstack/solid-router'
+import { orgSettings, userSettings } from '../routeScope.gen'
+export const Route = createRootRouteWithContext<{
+ onProfileMatch?: (routeId: string | undefined) => void
+}>()({
+ component: () => {
+ const organizationProfile = orgSettings.useMatch({
+ from: '@route-modules/solid-settings:/profile',
+ shouldThrow: false,
+ })
+ return (
+ <>
+
+
+ Switch to organization
+
+
+ Switch to person
+
+
+ {organizationProfile()?.routeId ?? 'none'}
+
+
+
+ >
+ )
+ },
+ notFoundComponent: () => APP_NOT_FOUND
,
+})
diff --git a/e2e/solid-router/route-modules/src/routes/orgs.$orgId.tsx b/e2e/solid-router/route-modules/src/routes/orgs.$orgId.tsx
new file mode 100644
index 0000000000..8a19e7b731
--- /dev/null
+++ b/e2e/solid-router/route-modules/src/routes/orgs.$orgId.tsx
@@ -0,0 +1,2 @@
+import { createFileRoute } from '@tanstack/solid-router'
+export const Route = createFileRoute('/orgs/$orgId')({})
diff --git a/e2e/solid-router/route-modules/src/routes/users.$userId.tsx b/e2e/solid-router/route-modules/src/routes/users.$userId.tsx
new file mode 100644
index 0000000000..d7bcb5d927
--- /dev/null
+++ b/e2e/solid-router/route-modules/src/routes/users.$userId.tsx
@@ -0,0 +1,2 @@
+import { createFileRoute } from '@tanstack/solid-router'
+export const Route = createFileRoute('/users/$userId')({})
diff --git a/e2e/solid-router/route-modules/tsconfig.json b/e2e/solid-router/route-modules/tsconfig.json
new file mode 100644
index 0000000000..8d28f99d15
--- /dev/null
+++ b/e2e/solid-router/route-modules/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": false,
+ "noEmit": true,
+ "types": ["vite/client"]
+ },
+ "include": ["src", "type-tests"]
+}
diff --git a/e2e/solid-router/route-modules/tsr.config.json b/e2e/solid-router/route-modules/tsr.config.json
new file mode 100644
index 0000000000..99b9443380
--- /dev/null
+++ b/e2e/solid-router/route-modules/tsr.config.json
@@ -0,0 +1,19 @@
+{
+ "target": "solid",
+ "routeModules": {
+ "includes": [
+ {
+ "module": "@route-modules/solid-settings",
+ "parent": "/orgs/$orgId",
+ "at": "/settings",
+ "as": "orgSettings"
+ },
+ {
+ "module": "@route-modules/solid-settings",
+ "parent": "/users/$userId",
+ "at": "/settings",
+ "as": "userSettings"
+ }
+ ]
+ }
+}
diff --git a/e2e/solid-router/route-modules/type-tests/scope-contracts.tsx b/e2e/solid-router/route-modules/type-tests/scope-contracts.tsx
new file mode 100644
index 0000000000..bae1999534
--- /dev/null
+++ b/e2e/solid-router/route-modules/type-tests/scope-contracts.tsx
@@ -0,0 +1,95 @@
+import { expectTypeOf, test } from 'vitest'
+import { orgSettings, userSettings } from '../src/routeScope.gen'
+import * as settings from '@route-modules/solid-settings/scope'
+
+test('reusable options preserve their installation through spreads and arrays', () => {
+ const user = userSettings.linkOptions({
+ to: '/members',
+ params: () => ({ userId: 'u1', orgId: '7' }),
+ })
+ expectTypeOf(
+ user._module,
+ ).toEqualTypeOf<'@route-modules/solid-settings#userSettings'>()
+ const same =
+ const { _module, ...neutral } = user
+ const compatiblePathsAndParams =
+ void compatiblePathsAndParams
+ void _module
+ // @ts-expect-error An explicit sibling installation is a conflicting scope.
+ const different =
+ // @ts-expect-error Rewrapping must not erase the conflicting scope.
+ orgSettings.linkOptions({ ...user })
+ // @ts-expect-error Arrays preserve each entry's destination scope.
+ orgSettings.linkOptions([user])
+ // @ts-expect-error Redirects enforce the same receiving-scope contract.
+ orgSettings.redirect(user)
+ orgSettings.linkOptions({
+ to: '/members',
+ params: { orgId: '7' },
+ // @ts-expect-error A mask cannot silently retarget another installation's options.
+ mask: user,
+ })
+ // @ts-expect-error Hook defaults must retain and check a reusable scope stamp.
+ orgSettings.useNavigate({ ...user, from: '/profile' })
+ // @ts-expect-error The callback checks the same destination stamp.
+ orgSettings.useNavigate()(user)
+ void same
+ void different
+})
+
+test('module-typed helper targets only known route IDs', () => {
+ settings.notFound({ routeId: '@route-modules/solid-settings:' })
+ settings.notFound()
+ // @ts-expect-error This route is not declared by the module.
+ settings.notFound({ routeId: '@route-modules/solid-settings:/absent' })
+})
+
+test('blocker locations describe the entire application and raw URL values', () => {
+ settings.useBlocker({
+ shouldBlockFn: ({ current, next }) => {
+ expectTypeOf(current.routeId).toEqualTypeOf()
+ expectTypeOf(next.fullPath).toEqualTypeOf()
+ expectTypeOf(next.params).toEqualTypeOf<
+ Record
+ >()
+ expectTypeOf(next.search).toEqualTypeOf>()
+ return false
+ },
+ })
+})
+
+test('match selectors expose foreign data and the generated guard restores known data', () => {
+ settings.useMatch({
+ strict: false,
+ select: (match) => {
+ expectTypeOf(match.context).toBeUnknown()
+ expectTypeOf(match.loaderData).toBeUnknown()
+ return match.routeId
+ },
+ })
+ settings.useMatches({
+ select: (matches) => {
+ expectTypeOf(matches[0]!.context).toBeUnknown()
+ for (const match of matches) {
+ if (
+ settings.isScopedMatch(match) &&
+ match.localRouteId === '@route-modules/solid-settings:/members'
+ ) {
+ expectTypeOf(match.loaderData).toEqualTypeOf<
+ { label: 'members' } | undefined
+ >()
+ expectTypeOf(match.fullPath).toEqualTypeOf()
+ }
+ }
+ return matches.length
+ },
+ })
+})
+
+test('MatchRoute accepts only the scope paths in JSX', () => {
+ const own =
+ // @ts-expect-error This path is not a module route.
+ const foreign =
+ void own
+ void foreign
+})
diff --git a/e2e/solid-router/route-modules/type-tests/validation-aliases.tsx b/e2e/solid-router/route-modules/type-tests/validation-aliases.tsx
new file mode 100644
index 0000000000..db957af10e
--- /dev/null
+++ b/e2e/solid-router/route-modules/type-tests/validation-aliases.tsx
@@ -0,0 +1,110 @@
+import { expectTypeOf, test } from 'vitest'
+import type { orgSettings } from '../src/routeScope.gen'
+
+test('every generated validation alias preserves its namespace contract', () => {
+ type Options = { to: '/profile'; params: { orgId: '7' } }
+ const options: Options = { to: '/profile', params: { orgId: '7' } }
+ const link: orgSettings.ValidateLinkOptions = options
+ const links: orgSettings.ValidateLinkOptionsArray = [
+ options,
+ ]
+ const navigate: orgSettings.ValidateNavigateOptions = options
+ const navigations: orgSettings.ValidateNavigateOptionsArray<
+ readonly [Options]
+ > = [options]
+ const redirect: orgSettings.ValidateRedirectOptions = options
+ const redirects: orgSettings.ValidateRedirectOptionsArray<
+ readonly [Options]
+ > = [options]
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+
+ const from: orgSettings.ValidateFromPath<'/profile'> = '/profile'
+ const to: orgSettings.ValidateToPath<'/profile'> = '/profile'
+ const search: orgSettings.ValidateSearch<'/search'> = {
+ search: { query: 'hello' },
+ }
+ const params: orgSettings.ValidateParams<'/profile'> = {
+ params: { orgId: '7' },
+ }
+ const id: orgSettings.ValidateId<'@route-modules/solid-settings:/profile'> =
+ '@route-modules/solid-settings:/profile'
+ const useSearch: orgSettings.ValidateUseSearchOptions<{
+ from: '@route-modules/solid-settings:/profile'
+ }> = { from: '@route-modules/solid-settings:/profile' }
+ const useParams: orgSettings.ValidateUseParamsOptions<{
+ from: '@route-modules/solid-settings:/profile'
+ }> = { from: '@route-modules/solid-settings:/profile' }
+ void [from, to, search, params, id, useSearch, useParams]
+
+ const foreignPath = {
+ to: '/orgs/$orgId',
+ params: { orgId: '7' },
+ } as const
+ const foreignPaths = [foreignPath] as const
+ const foreignOrigin = { from: '/orgs/$orgId' } as const
+ const wrongSearch = { search: { query: 42 } }
+ const wrongParams = { params: { userId: 'u1' } }
+
+ // @ts-expect-error The validation alias is bound to this module's paths.
+ const invalidLink: orgSettings.ValidateLinkOptions =
+ foreignPath
+ // @ts-expect-error Tuple entries retain the generated scope.
+ const invalidLinks: orgSettings.ValidateLinkOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error Navigation wrappers cannot escape the module paths.
+ const invalidNavigate: orgSettings.ValidateNavigateOptions<
+ typeof foreignPath
+ > = foreignPath
+ // @ts-expect-error Every navigation array entry is checked.
+ const invalidNavigations: orgSettings.ValidateNavigateOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error Redirect wrappers retain module path validation.
+ const invalidRedirect: orgSettings.ValidateRedirectOptions<
+ typeof foreignPath
+ > = foreignPath
+ // @ts-expect-error Every redirect array entry is checked.
+ const invalidRedirects: orgSettings.ValidateRedirectOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error A route origin must be a path in the module.
+ const invalidFrom: orgSettings.ValidateFromPath<'/profile'> = '/orgs/$orgId'
+ // @ts-expect-error A destination must be a path in the module.
+ const invalidTo: orgSettings.ValidateToPath<'/profile'> = '/orgs/$orgId'
+ // @ts-expect-error Search validation follows the generated route schema.
+ const invalidSearch: orgSettings.ValidateSearch<'/search'> = wrongSearch
+ // @ts-expect-error The named installation requires its own host parameter.
+ const invalidParams: orgSettings.ValidateParams<'/profile'> = wrongParams
+ // @ts-expect-error A foreign route ID is not a module route.
+ const invalidId: orgSettings.ValidateId<'@route-modules/solid-settings:/profile'> =
+ '/orgs/$orgId'
+ // @ts-expect-error Search selectors must name a route in this module.
+ const invalidUseSearch: orgSettings.ValidateUseSearchOptions<
+ typeof foreignOrigin
+ > = foreignOrigin
+ // @ts-expect-error Parameter selectors must name a route in this module.
+ const invalidUseParams: orgSettings.ValidateUseParamsOptions<
+ typeof foreignOrigin
+ > = foreignOrigin
+ void [
+ invalidLink,
+ invalidLinks,
+ invalidNavigate,
+ invalidNavigations,
+ invalidRedirect,
+ invalidRedirects,
+ invalidFrom,
+ invalidTo,
+ invalidSearch,
+ invalidParams,
+ invalidId,
+ invalidUseSearch,
+ invalidUseParams,
+ ]
+})
diff --git a/e2e/solid-router/route-modules/vite.config.ts b/e2e/solid-router/route-modules/vite.config.ts
new file mode 100644
index 0000000000..f966227153
--- /dev/null
+++ b/e2e/solid-router/route-modules/vite.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vite'
+import solid from 'vite-plugin-solid'
+import { tanstackRouter } from '@tanstack/router-plugin/vite'
+
+export default defineConfig({
+ plugins: [
+ tanstackRouter({ target: 'solid', autoCodeSplitting: true }),
+ solid(),
+ ],
+})
diff --git a/e2e/vue-router/route-modules/.gitignore b/e2e/vue-router/route-modules/.gitignore
new file mode 100644
index 0000000000..18dd57830b
--- /dev/null
+++ b/e2e/vue-router/route-modules/.gitignore
@@ -0,0 +1,2 @@
+# Generated during the e2e preparation/build, never checked in.
+**/route*.gen*.ts
diff --git a/e2e/vue-router/route-modules/e2e/scope-parity.spec.ts b/e2e/vue-router/route-modules/e2e/scope-parity.spec.ts
new file mode 100644
index 0000000000..2690e77001
--- /dev/null
+++ b/e2e/vue-router/route-modules/e2e/scope-parity.spec.ts
@@ -0,0 +1,175 @@
+import { expect } from '@playwright/test'
+import { test } from '@tanstack/router-e2e-utils'
+
+for (const base of ['/orgs/7/settings', '/users/u1/settings']) {
+ test(`RouteApi and custom links resolve ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await expect(
+ page.getByRole('link', { name: 'API members' }),
+ ).toHaveAttribute('href', `${base}/members`)
+ await expect(
+ page.getByRole('link', { name: 'Custom members' }),
+ ).toHaveAttribute('href', `${base}/members`)
+ expect(
+ await page
+ .getByRole('link', { name: 'API members' })
+ .getAttribute('_module'),
+ ).toBeNull()
+ expect(
+ await page
+ .getByRole('link', { name: 'Custom members' })
+ .getAttribute('_module'),
+ ).toBeNull()
+ const hostId = base.split('/')[2]!
+ const hostParams = base.startsWith('/orgs/')
+ ? { orgId: hostId }
+ : base.startsWith('/people/')
+ ? { personId: hostId }
+ : { userId: hostId }
+ await expect(page.getByTestId('runtime-params')).toHaveText(
+ JSON.stringify(hostParams),
+ )
+ await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible()
+ await expect(page.getByText('MEMBERS_MATCH', { exact: true })).toHaveCount(
+ 0,
+ )
+ await page.getByRole('link', { name: 'API members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test(`useLinkProps navigates within the document under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ await expect(
+ page.getByRole('link', { name: 'Custom members' }),
+ ).toBeVisible()
+ const documentRequests: Array = []
+ page.on('request', (request) => {
+ if (
+ request.isNavigationRequest() &&
+ request.frame() === page.mainFrame()
+ ) {
+ documentRequests.push(request.url())
+ }
+ })
+ await page.getByRole('link', { name: 'Custom members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ expect(documentRequests).toEqual([])
+ })
+
+ test(`RouteApi navigation resolves ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await page.getByRole('button', { name: 'Navigate members' }).click()
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test(`Navigate captures installation under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/forward`)
+ await expect(page.getByText('MEMBERS_PAGE')).toBeVisible()
+ await expect(page).toHaveURL(`${base}/members`)
+ })
+
+ test(`component notFound reaches module boundary under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/missing`)
+ await expect(page.getByText('MODULE_NOT_FOUND')).toBeVisible()
+ })
+ for (const button of ['Route up', 'Explicit from home']) {
+ test(`${button} uses the route origin under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ await page.getByRole('button', { name: button, exact: true }).click()
+ await expect(page).toHaveURL(base)
+ await expect(
+ page.getByRole('link', { name: 'Profile', exact: true }),
+ ).toHaveAttribute('href', `${base}/profile`)
+ })
+ }
+
+ test(`scoped router view builds and navigates under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ await expect(page.getByTestId('scoped-href')).toHaveText(`${base}/members`)
+ await page.getByRole('button', { name: 'Router members' }).click()
+ await expect(page).toHaveURL(`${base}/members`)
+ const profile = page.getByRole('link', { name: 'Profile', exact: true })
+ await expect(profile).toHaveAttribute('href', `${base}/profile`)
+ await profile.click()
+ await expect(page).toHaveURL(`${base}/profile`)
+ })
+
+ test(`Route.Link keeps the installation under ${base}`, async ({ page }) => {
+ await page.goto(`${base}/profile`)
+ const home = page.getByRole('link', { name: 'Route home', exact: true })
+ await expect(home).toHaveAttribute('href', base)
+ await home.click()
+ await expect(page).toHaveURL(base)
+ await expect(
+ page.getByRole('link', { name: 'Profile', exact: true }),
+ ).toHaveAttribute('href', `${base}/profile`)
+ })
+
+ test(`scoped lifecycle redirects retain the installation under ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/legacy`)
+ await expect(page).toHaveURL(`${base}/profile`)
+ await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible()
+ })
+
+ test(`framework imports keep application coordinates inside ${base}`, async ({
+ page,
+ }) => {
+ await page.goto(`${base}/profile`)
+ const host = page.getByRole('link', { name: 'Application host' })
+ await expect(host).toHaveAttribute('href', '/orgs/9')
+ await host.click()
+ await expect(page).toHaveURL('/orgs/9')
+ })
+}
+
+test('module observers and router views follow real installation changes', async ({
+ page,
+}) => {
+ await page.goto('/orgs/7/settings/profile')
+ await expect(page.getByTestId('organization-profile')).toHaveText(
+ '@route-modules/vue-settings#orgSettings:/profile',
+ )
+ await expect(page.getByTestId('scoped-href')).toHaveText(
+ '/orgs/7/settings/members',
+ )
+ await page.getByRole('link', { name: 'API members' }).click()
+ await expect(page).toHaveURL('/orgs/7/settings/members')
+ await page.getByRole('link', { name: 'Switch to person' }).click()
+ await expect(page).toHaveURL('/users/u1/settings/profile')
+ await expect(page.getByTestId('organization-profile')).toHaveText('none')
+ await expect(page.getByTestId('scoped-href')).toHaveText(
+ '/users/u1/settings/members',
+ )
+ await page.getByRole('link', { name: 'Switch to organization' }).click()
+ await expect(page).toHaveURL('/orgs/7/settings/profile')
+ await expect(page.getByRole('link', { name: 'API members' })).toHaveAttribute(
+ 'href',
+ '/orgs/7/settings/members',
+ )
+ const readObserved = () =>
+ page.evaluate(
+ () =>
+ (
+ window as Window & {
+ observedModuleMatches: Array
+ }
+ ).observedModuleMatches,
+ )
+ await expect
+ .poll(readObserved)
+ .toContain('@route-modules/vue-settings#userSettings:/profile')
+ const observed = await readObserved()
+ expect(observed).toContain('@route-modules/vue-settings#orgSettings:/profile')
+ expect(observed).not.toContain(undefined)
+})
diff --git a/e2e/vue-router/route-modules/index.html b/e2e/vue-router/route-modules/index.html
new file mode 100644
index 0000000000..5a5556330e
--- /dev/null
+++ b/e2e/vue-router/route-modules/index.html
@@ -0,0 +1,11 @@
+
+
+
+
+ Route module contracts
+
+
+
+
+
+
diff --git a/e2e/vue-router/route-modules/package.json b/e2e/vue-router/route-modules/package.json
new file mode 100644
index 0000000000..ad2a94a537
--- /dev/null
+++ b/e2e/vue-router/route-modules/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "tanstack-router-e2e-vue-route-modules",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "generate": "node scripts/prepare.mjs",
+ "build": "node scripts/prepare.mjs && vite build && tsc --noEmit && tsc -p packages/settings/tsconfig.json --noEmit",
+ "preview": "vite preview",
+ "dev:e2e": "node scripts/prepare.mjs && vite",
+ "test:e2e": "playwright test --project=chromium"
+ },
+ "dependencies": {
+ "@route-modules/vue-settings": "workspace:*",
+ "@tanstack/vue-router": "workspace:^",
+ "vue": "^3.5.16"
+ },
+ "devDependencies": {
+ "@playwright/test": "^1.61.0",
+ "@tanstack/router-cli": "workspace:^",
+ "@tanstack/router-core": "workspace:^",
+ "@tanstack/router-e2e-utils": "workspace:^",
+ "@tanstack/router-generator": "workspace:^",
+ "@tanstack/router-plugin": "workspace:^",
+ "@types/node": "catalog:",
+ "vite": "^8.0.14",
+ "vitest": "catalog:",
+ "@vitejs/plugin-vue-jsx": "^5.1.5"
+ }
+}
diff --git a/e2e/vue-router/route-modules/packages/settings/package.json b/e2e/vue-router/route-modules/packages/settings/package.json
new file mode 100644
index 0000000000..10eaf438b0
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/package.json
@@ -0,0 +1,37 @@
+{
+ "name": "@route-modules/vue-settings",
+ "private": true,
+ "type": "module",
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ },
+ "exports": {
+ "./route-types": {
+ "types": "./.tanstack/types/src/routeContract.gen.d.ts"
+ },
+ "./route-module": {
+ "types": "./.tanstack/types/src/routeModule.gen.d.ts",
+ "default": "./src/routeModule.gen.ts"
+ },
+ "./scope": {
+ "types": "./.tanstack/types/src/routeScope.gen.d.ts",
+ "default": "./src/routeScope.gen.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "generate": "tsr generate",
+ "emit-types": "tsc -p tsconfig.route-types.json",
+ "check": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@tanstack/vue-router": "workspace:^",
+ "vue": "^3.5.16"
+ },
+ "devDependencies": {
+ "@tanstack/router-core": "workspace:^",
+ "@tanstack/router-cli": "workspace:^"
+ }
+}
diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/__root.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/__root.tsx
new file mode 100644
index 0000000000..818a747831
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/src/routes/__root.tsx
@@ -0,0 +1,9 @@
+import * as Vue from 'vue'
+import { Outlet } from '@tanstack/vue-router'
+import { createModuleRoot } from '../routeScope.gen'
+export const Route = createModuleRoot<{
+ onProfileMatch?: (routeId: string | undefined) => void
+}>()({
+ component: () => ,
+ notFoundComponent: () => MODULE_NOT_FOUND
,
+})
diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/forward.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/forward.tsx
new file mode 100644
index 0000000000..a01bf2b8b6
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/src/routes/forward.tsx
@@ -0,0 +1,5 @@
+import * as Vue from 'vue'
+import { createFileRoute, Navigate } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/vue-settings:/forward')({
+ component: () => ,
+})
diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/index.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/index.tsx
new file mode 100644
index 0000000000..55697a39de
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/src/routes/index.tsx
@@ -0,0 +1,4 @@
+import { createFileRoute, Link } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/vue-settings:/')({
+ component: () => Profile,
+})
diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/legacy.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/legacy.tsx
new file mode 100644
index 0000000000..a83a5cd897
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/src/routes/legacy.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute, redirect } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/vue-settings:/legacy')({
+ beforeLoad: () => {
+ throw redirect({ to: '/profile' })
+ },
+})
diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/members.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/members.tsx
new file mode 100644
index 0000000000..a71c4fb4bf
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/src/routes/members.tsx
@@ -0,0 +1,12 @@
+import * as Vue from 'vue'
+import { createFileRoute, getRouteApi } from '../routeScope.gen'
+const ProfileLink = getRouteApi('@route-modules/vue-settings:/profile').Link
+export const Route = createFileRoute('@route-modules/vue-settings:/members')({
+ loader: () => ({ label: 'members' as const }),
+ component: () => (
+ <>
+ MEMBERS_PAGE
+ Profile
+ >
+ ),
+})
diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/missing.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/missing.tsx
new file mode 100644
index 0000000000..eb114f3dc1
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/src/routes/missing.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute, notFound } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/vue-settings:/missing')({
+ component: () => {
+ throw notFound({ routeId: '@route-modules/vue-settings:' })
+ },
+})
diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/profile.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/profile.tsx
new file mode 100644
index 0000000000..b3cb158126
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/src/routes/profile.tsx
@@ -0,0 +1,58 @@
+import * as Vue from 'vue'
+import { Link as ApplicationLink } from '@tanstack/vue-router'
+import {
+ createFileRoute,
+ getRouteApi,
+ MatchRoute,
+ useLinkProps,
+ useNavigate,
+ useRouter,
+} from '../routeScope.gen'
+const api = getRouteApi('@route-modules/vue-settings:/profile')
+export const Route = createFileRoute('@route-modules/vue-settings:/profile')({
+ component: Vue.defineComponent({
+ setup() {
+ const navigate = api.useNavigate()
+ const routeNavigate = Route.useNavigate()
+ const relativeNavigate = useNavigate({ from: '/profile' })
+ const anchor = useLinkProps({ to: '/members' })
+ const match = Route.useMatch({ shouldThrow: false })
+ const scopedRouter = useRouter()
+ const observe = scopedRouter.options.context?.onProfileMatch
+ Vue.watchEffect(() => observe?.(match.value?.routeId), { flush: 'sync' })
+ return () => (
+ <>
+ {match.value?.routeId}
+
+ {JSON.stringify(match.value?.params)}
+
+ API members
+ navigate({ to: '/members' })}>
+ Navigate members
+
+ Custom members
+
+ PROFILE_MATCH
+
+
+ MEMBERS_MATCH
+
+
+ {scopedRouter.buildLocation({ to: '/members' }).href}
+
+ scopedRouter.navigate({ to: '/members' })}>
+ Router members
+
+ routeNavigate({ to: '..' })}>Route up
+ relativeNavigate({ to: '..' })}>
+ Explicit from home
+
+ Route home
+
+ Application host
+
+ >
+ )
+ },
+ }),
+})
diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/search.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/search.tsx
new file mode 100644
index 0000000000..ce7240ca62
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/src/routes/search.tsx
@@ -0,0 +1,4 @@
+import { createFileRoute } from '../routeScope.gen'
+export const Route = createFileRoute('@route-modules/vue-settings:/search')({
+ validateSearch: (search: { query: string }) => search,
+})
diff --git a/e2e/vue-router/route-modules/packages/settings/tsconfig.json b/e2e/vue-router/route-modules/packages/settings/tsconfig.json
new file mode 100644
index 0000000000..03e4f22814
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "preserve",
+ "jsxImportSource": "vue",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/e2e/vue-router/route-modules/packages/settings/tsconfig.route-types.json b/e2e/vue-router/route-modules/packages/settings/tsconfig.route-types.json
new file mode 100644
index 0000000000..0c9aec3caf
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/tsconfig.route-types.json
@@ -0,0 +1,13 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "declarationMap": true,
+ "rootDir": ".",
+ "outDir": ".tanstack/types"
+ },
+ "include": ["src"]
+}
diff --git a/e2e/vue-router/route-modules/packages/settings/tsr.config.json b/e2e/vue-router/route-modules/packages/settings/tsr.config.json
new file mode 100644
index 0000000000..e026c80dc2
--- /dev/null
+++ b/e2e/vue-router/route-modules/packages/settings/tsr.config.json
@@ -0,0 +1,3 @@
+{
+ "target": "vue"
+}
diff --git a/e2e/vue-router/route-modules/playwright.config.ts b/e2e/vue-router/route-modules/playwright.config.ts
new file mode 100644
index 0000000000..56f2d789b1
--- /dev/null
+++ b/e2e/vue-router/route-modules/playwright.config.ts
@@ -0,0 +1,17 @@
+import { defineConfig, devices } from '@playwright/test'
+import { appServerReady } from '@tanstack/router-e2e-utils'
+
+const PORT = Number(process.env.E2E_APP_PORT ?? 0)
+export default defineConfig({
+ testDir: './e2e',
+ workers: 1,
+ reporter: [['line']],
+ use: { baseURL: `http://localhost:${PORT}` },
+ webServer: {
+ command: `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}`,
+ wait: appServerReady,
+ reuseExistingServer: false,
+ stdout: 'pipe',
+ },
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+})
diff --git a/e2e/vue-router/route-modules/scripts/prepare.mjs b/e2e/vue-router/route-modules/scripts/prepare.mjs
new file mode 100644
index 0000000000..c7bad5c894
--- /dev/null
+++ b/e2e/vue-router/route-modules/scripts/prepare.mjs
@@ -0,0 +1,28 @@
+import { spawnSync } from 'node:child_process'
+import { rmSync } from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { Generator, getConfig } from '@tanstack/router-generator'
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const provider = path.join(root, 'packages/settings')
+await new Generator({
+ config: getConfig({ disableLogging: true }, provider),
+ root: provider,
+}).run()
+rmSync(path.join(provider, '.tanstack/types'), { recursive: true, force: true })
+const result = spawnSync(
+ 'pnpm',
+ ['exec', 'tsc', '-p', 'tsconfig.route-types.json', '--pretty', 'false'],
+ { cwd: provider, stdio: 'inherit', shell: process.platform === 'win32' },
+)
+if (result.error) {
+ throw result.error
+}
+if (result.status !== 0) {
+ process.exit(result.status ?? 1)
+}
+await new Generator({
+ config: getConfig({ disableLogging: true }, root),
+ root,
+}).run()
diff --git a/e2e/vue-router/route-modules/src/main.tsx b/e2e/vue-router/route-modules/src/main.tsx
new file mode 100644
index 0000000000..239fc24f38
--- /dev/null
+++ b/e2e/vue-router/route-modules/src/main.tsx
@@ -0,0 +1,16 @@
+import { createApp, h } from 'vue'
+import { RouterProvider, createRouter } from '@tanstack/vue-router'
+import { routeTree } from './routeTree.gen'
+
+const observedModuleMatches: Array = []
+Object.assign(window, { observedModuleMatches })
+const router = createRouter({
+ routeTree,
+ context: { onProfileMatch: (routeId) => observedModuleMatches.push(routeId) },
+})
+declare module '@tanstack/vue-router' {
+ interface Register {
+ router: typeof router
+ }
+}
+createApp({ setup: () => () => h(RouterProvider, { router }) }).mount('#app')
diff --git a/e2e/vue-router/route-modules/src/routes/__root.tsx b/e2e/vue-router/route-modules/src/routes/__root.tsx
new file mode 100644
index 0000000000..567c442bb3
--- /dev/null
+++ b/e2e/vue-router/route-modules/src/routes/__root.tsx
@@ -0,0 +1,32 @@
+import * as Vue from 'vue'
+import { createRootRouteWithContext, Outlet } from '@tanstack/vue-router'
+import { orgSettings, userSettings } from '../routeScope.gen'
+export const Route = createRootRouteWithContext<{
+ onProfileMatch?: (routeId: string | undefined) => void
+}>()({
+ component: Vue.defineComponent({
+ setup() {
+ const organizationProfile = orgSettings.useMatch({
+ from: '@route-modules/vue-settings:/profile',
+ shouldThrow: false,
+ })
+ return () => (
+ <>
+
+
+ Switch to organization
+
+
+ Switch to person
+
+
+ {organizationProfile.value?.routeId ?? 'none'}
+
+
+
+ >
+ )
+ },
+ }),
+ notFoundComponent: () => APP_NOT_FOUND
,
+})
diff --git a/e2e/vue-router/route-modules/src/routes/orgs.$orgId.tsx b/e2e/vue-router/route-modules/src/routes/orgs.$orgId.tsx
new file mode 100644
index 0000000000..8612ff63dc
--- /dev/null
+++ b/e2e/vue-router/route-modules/src/routes/orgs.$orgId.tsx
@@ -0,0 +1,2 @@
+import { createFileRoute } from '@tanstack/vue-router'
+export const Route = createFileRoute('/orgs/$orgId')({})
diff --git a/e2e/vue-router/route-modules/src/routes/users.$userId.tsx b/e2e/vue-router/route-modules/src/routes/users.$userId.tsx
new file mode 100644
index 0000000000..591ed91014
--- /dev/null
+++ b/e2e/vue-router/route-modules/src/routes/users.$userId.tsx
@@ -0,0 +1,2 @@
+import { createFileRoute } from '@tanstack/vue-router'
+export const Route = createFileRoute('/users/$userId')({})
diff --git a/e2e/vue-router/route-modules/tsconfig.json b/e2e/vue-router/route-modules/tsconfig.json
new file mode 100644
index 0000000000..9e43460be8
--- /dev/null
+++ b/e2e/vue-router/route-modules/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "preserve",
+ "jsxImportSource": "vue",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": false,
+ "noEmit": true,
+ "types": ["vite/client"]
+ },
+ "include": ["src", "type-tests"]
+}
diff --git a/e2e/vue-router/route-modules/tsr.config.json b/e2e/vue-router/route-modules/tsr.config.json
new file mode 100644
index 0000000000..4c17a3b082
--- /dev/null
+++ b/e2e/vue-router/route-modules/tsr.config.json
@@ -0,0 +1,19 @@
+{
+ "target": "vue",
+ "routeModules": {
+ "includes": [
+ {
+ "module": "@route-modules/vue-settings",
+ "parent": "/orgs/$orgId",
+ "at": "/settings",
+ "as": "orgSettings"
+ },
+ {
+ "module": "@route-modules/vue-settings",
+ "parent": "/users/$userId",
+ "at": "/settings",
+ "as": "userSettings"
+ }
+ ]
+ }
+}
diff --git a/e2e/vue-router/route-modules/type-tests/scope-contracts.tsx b/e2e/vue-router/route-modules/type-tests/scope-contracts.tsx
new file mode 100644
index 0000000000..a32b8448a8
--- /dev/null
+++ b/e2e/vue-router/route-modules/type-tests/scope-contracts.tsx
@@ -0,0 +1,95 @@
+import { expectTypeOf, test } from 'vitest'
+import { orgSettings, userSettings } from '../src/routeScope.gen'
+import * as settings from '@route-modules/vue-settings/scope'
+
+test('reusable options preserve their installation through spreads and arrays', () => {
+ const user = userSettings.linkOptions({
+ to: '/members',
+ params: () => ({ userId: 'u1', orgId: '7' }),
+ })
+ expectTypeOf(
+ user._module,
+ ).toEqualTypeOf<'@route-modules/vue-settings#userSettings'>()
+ const same =
+ const { _module, ...neutral } = user
+ const compatiblePathsAndParams =
+ void compatiblePathsAndParams
+ void _module
+ // @ts-expect-error An explicit sibling installation is a conflicting scope.
+ const different =
+ // @ts-expect-error Rewrapping must not erase the conflicting scope.
+ orgSettings.linkOptions({ ...user })
+ // @ts-expect-error Arrays preserve each entry's destination scope.
+ orgSettings.linkOptions([user])
+ // @ts-expect-error Redirects enforce the same receiving-scope contract.
+ orgSettings.redirect(user)
+ orgSettings.linkOptions({
+ to: '/members',
+ params: { orgId: '7' },
+ // @ts-expect-error A mask cannot silently retarget another installation's options.
+ mask: user,
+ })
+ // @ts-expect-error Hook defaults must retain and check a reusable scope stamp.
+ orgSettings.useNavigate({ ...user, from: '/profile' })
+ // @ts-expect-error The callback checks the same destination stamp.
+ orgSettings.useNavigate()(user)
+ void same
+ void different
+})
+
+test('module-typed helper targets only known route IDs', () => {
+ settings.notFound({ routeId: '@route-modules/vue-settings:' })
+ settings.notFound()
+ // @ts-expect-error This route is not declared by the module.
+ settings.notFound({ routeId: '@route-modules/vue-settings:/absent' })
+})
+
+test('blocker locations describe the entire application and raw URL values', () => {
+ settings.useBlocker({
+ shouldBlockFn: ({ current, next }) => {
+ expectTypeOf(current.routeId).toEqualTypeOf()
+ expectTypeOf(next.fullPath).toEqualTypeOf()
+ expectTypeOf(next.params).toEqualTypeOf<
+ Record
+ >()
+ expectTypeOf(next.search).toEqualTypeOf>()
+ return false
+ },
+ })
+})
+
+test('match selectors expose foreign data and the generated guard restores known data', () => {
+ settings.useMatch({
+ strict: false,
+ select: (match) => {
+ expectTypeOf(match.context).toBeUnknown()
+ expectTypeOf(match.loaderData).toBeUnknown()
+ return match.routeId
+ },
+ })
+ settings.useMatches({
+ select: (matches) => {
+ expectTypeOf(matches[0]!.context).toBeUnknown()
+ for (const match of matches) {
+ if (
+ settings.isScopedMatch(match) &&
+ match.localRouteId === '@route-modules/vue-settings:/members'
+ ) {
+ expectTypeOf(match.loaderData).toEqualTypeOf<
+ { label: 'members' } | undefined
+ >()
+ expectTypeOf(match.fullPath).toEqualTypeOf()
+ }
+ }
+ return matches.length
+ },
+ })
+})
+
+test('MatchRoute accepts only the scope paths in JSX', () => {
+ const own =
+ // @ts-expect-error This path is not a module route.
+ const foreign =
+ void own
+ void foreign
+})
diff --git a/e2e/vue-router/route-modules/type-tests/validation-aliases.tsx b/e2e/vue-router/route-modules/type-tests/validation-aliases.tsx
new file mode 100644
index 0000000000..3952934073
--- /dev/null
+++ b/e2e/vue-router/route-modules/type-tests/validation-aliases.tsx
@@ -0,0 +1,110 @@
+import { expectTypeOf, test } from 'vitest'
+import type { orgSettings } from '../src/routeScope.gen'
+
+test('every generated validation alias preserves its namespace contract', () => {
+ type Options = { to: '/profile'; params: { orgId: '7' } }
+ const options: Options = { to: '/profile', params: { orgId: '7' } }
+ const link: orgSettings.ValidateLinkOptions = options
+ const links: orgSettings.ValidateLinkOptionsArray = [
+ options,
+ ]
+ const navigate: orgSettings.ValidateNavigateOptions = options
+ const navigations: orgSettings.ValidateNavigateOptionsArray<
+ readonly [Options]
+ > = [options]
+ const redirect: orgSettings.ValidateRedirectOptions = options
+ const redirects: orgSettings.ValidateRedirectOptionsArray<
+ readonly [Options]
+ > = [options]
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().toMatchTypeOf()
+
+ const from: orgSettings.ValidateFromPath<'/profile'> = '/profile'
+ const to: orgSettings.ValidateToPath<'/profile'> = '/profile'
+ const search: orgSettings.ValidateSearch<'/search'> = {
+ search: { query: 'hello' },
+ }
+ const params: orgSettings.ValidateParams<'/profile'> = {
+ params: { orgId: '7' },
+ }
+ const id: orgSettings.ValidateId<'@route-modules/vue-settings:/profile'> =
+ '@route-modules/vue-settings:/profile'
+ const useSearch: orgSettings.ValidateUseSearchOptions<{
+ from: '@route-modules/vue-settings:/profile'
+ }> = { from: '@route-modules/vue-settings:/profile' }
+ const useParams: orgSettings.ValidateUseParamsOptions<{
+ from: '@route-modules/vue-settings:/profile'
+ }> = { from: '@route-modules/vue-settings:/profile' }
+ void [from, to, search, params, id, useSearch, useParams]
+
+ const foreignPath = {
+ to: '/orgs/$orgId',
+ params: { orgId: '7' },
+ } as const
+ const foreignPaths = [foreignPath] as const
+ const foreignOrigin = { from: '/orgs/$orgId' } as const
+ const wrongSearch = { search: { query: 42 } }
+ const wrongParams = { params: { userId: 'u1' } }
+
+ // @ts-expect-error The validation alias is bound to this module's paths.
+ const invalidLink: orgSettings.ValidateLinkOptions =
+ foreignPath
+ // @ts-expect-error Tuple entries retain the generated scope.
+ const invalidLinks: orgSettings.ValidateLinkOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error Navigation wrappers cannot escape the module paths.
+ const invalidNavigate: orgSettings.ValidateNavigateOptions<
+ typeof foreignPath
+ > = foreignPath
+ // @ts-expect-error Every navigation array entry is checked.
+ const invalidNavigations: orgSettings.ValidateNavigateOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error Redirect wrappers retain module path validation.
+ const invalidRedirect: orgSettings.ValidateRedirectOptions<
+ typeof foreignPath
+ > = foreignPath
+ // @ts-expect-error Every redirect array entry is checked.
+ const invalidRedirects: orgSettings.ValidateRedirectOptionsArray<
+ typeof foreignPaths
+ > = foreignPaths
+ // @ts-expect-error A route origin must be a path in the module.
+ const invalidFrom: orgSettings.ValidateFromPath<'/profile'> = '/orgs/$orgId'
+ // @ts-expect-error A destination must be a path in the module.
+ const invalidTo: orgSettings.ValidateToPath<'/profile'> = '/orgs/$orgId'
+ // @ts-expect-error Search validation follows the generated route schema.
+ const invalidSearch: orgSettings.ValidateSearch<'/search'> = wrongSearch
+ // @ts-expect-error The named installation requires its own host parameter.
+ const invalidParams: orgSettings.ValidateParams<'/profile'> = wrongParams
+ // @ts-expect-error A foreign route ID is not a module route.
+ const invalidId: orgSettings.ValidateId<'@route-modules/vue-settings:/profile'> =
+ '/orgs/$orgId'
+ // @ts-expect-error Search selectors must name a route in this module.
+ const invalidUseSearch: orgSettings.ValidateUseSearchOptions<
+ typeof foreignOrigin
+ > = foreignOrigin
+ // @ts-expect-error Parameter selectors must name a route in this module.
+ const invalidUseParams: orgSettings.ValidateUseParamsOptions<
+ typeof foreignOrigin
+ > = foreignOrigin
+ void [
+ invalidLink,
+ invalidLinks,
+ invalidNavigate,
+ invalidNavigations,
+ invalidRedirect,
+ invalidRedirects,
+ invalidFrom,
+ invalidTo,
+ invalidSearch,
+ invalidParams,
+ invalidId,
+ invalidUseSearch,
+ invalidUseParams,
+ ]
+})
diff --git a/e2e/vue-router/route-modules/vite.config.ts b/e2e/vue-router/route-modules/vite.config.ts
new file mode 100644
index 0000000000..51084a35b1
--- /dev/null
+++ b/e2e/vue-router/route-modules/vite.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vite'
+import vueJsx from '@vitejs/plugin-vue-jsx'
+import { tanstackRouter } from '@tanstack/router-plugin/vite'
+
+export default defineConfig({
+ plugins: [
+ tanstackRouter({ target: 'vue', autoCodeSplitting: true }),
+ vueJsx(),
+ ],
+})
diff --git a/eslint.config.js b/eslint.config.js
index f58cc3fd10..f3a0c389ca 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -4,9 +4,23 @@ import { tanstackConfig } from '@tanstack/eslint-config'
import unusedImports from 'eslint-plugin-unused-imports'
+// Packages that set their own `no-restricted-syntax` must include this entry.
+export const routerCoreAugmentation = {
+ selector: "TSModuleDeclaration[id.value='@tanstack/router-core']",
+ message:
+ "Augment '@tanstack/router-core/extensions' instead. Augmenting the main entry makes emitted declarations import router types from '@tanstack/router-core' (see packages/router-core/src/extensions.ts).",
+}
+
/** @type {import('eslint').Linter.Config[]} */
export default [
...tanstackConfig,
+ {
+ name: 'tanstack/router-core-augmentation',
+ files: ['src/**/*.{ts,tsx}'],
+ rules: {
+ 'no-restricted-syntax': ['error', routerCoreAugmentation],
+ },
+ },
{
name: 'tanstack/temp',
rules: {
diff --git a/examples/react/start-large-route-modules/.gitignore b/examples/react/start-large-route-modules/.gitignore
new file mode 100644
index 0000000000..f9cade74f3
--- /dev/null
+++ b/examples/react/start-large-route-modules/.gitignore
@@ -0,0 +1,21 @@
+node_modules
+.DS_Store
+dist
+dist-ssr
+*.local
+
+# Written by `pnpm gen`: the route modules, the application's package.json
+# (it depends on every generated module) and the files listing the modules.
+/modules
+/app/package.json
+/app/node_modules
+/app/route-modules.gen.ts
+/app/src/moduleIndex.gen.tsx
+/measurements
+
+# Generated by the route generator.
+**/routeTree.gen.ts
+**/routeScope.gen.ts
+**/routeContract.gen.ts
+**/routeModule.gen.ts
+**/startModules.gen.ts
diff --git a/examples/react/start-large-route-modules/.prettierignore b/examples/react/start-large-route-modules/.prettierignore
new file mode 100644
index 0000000000..2be5eaa6ec
--- /dev/null
+++ b/examples/react/start-large-route-modules/.prettierignore
@@ -0,0 +1,4 @@
+**/build
+**/public
+pnpm-lock.yaml
+routeTree.gen.ts
\ No newline at end of file
diff --git a/examples/react/start-large-route-modules/README.md b/examples/react/start-large-route-modules/README.md
new file mode 100644
index 0000000000..51596a70f7
--- /dev/null
+++ b/examples/react/start-large-route-modules/README.md
@@ -0,0 +1,80 @@
+# TanStack Start - Large Route Modules Example
+
+A TanStack Start application that installs many generated route modules, to
+measure how builds and type checks scale with the number of modules.
+
+- [Route modules guide](https://tanstack.com/start/latest/docs/framework/react/guide/route-modules)
+
+## Layout
+
+- `app/`: the application. It installs every module and provides the request
+ context the modules require.
+- `template/`: the module templates. `account` is a small module every feature
+ module links to. `feature` is copied once per feature module. Its layout,
+ item list, item and search routes load data through the module's own server
+ functions and middleware, and `pages/page.tsx` is copied to fill up the route
+ count.
+- `modules/`: the generated module packages (not committed). They are linked
+ like workspace packages and resolve their dependencies from this example.
+
+## Getting Started
+
+```sh
+pnpm install
+pnpm gen
+pnpm dev
+```
+
+`pnpm gen` generates routes and builds each package's declarations with
+`tsc -p tsconfig.route-types.json`, the account module first. The script cleans
+each declaration output before compiling. Router handles route generation;
+the package build handles declaration output, and a task runner such as Nx can
+schedule these steps in dependency order. It also writes the application files that list the
+modules: `app/package.json`, `app/route-modules.gen.ts` and
+`app/src/moduleIndex.gen.tsx`. Options:
+
+- `--modules `: number of feature modules (default 50).
+- `--routes `: routes per feature module, at least 5 (default 10).
+- `--transpiled`: ships the modules as JavaScript, the way a module prebuilt to
+ transpiled ESM would. The application still code-splits and compiles them.
+
+`pnpm dev` and `pnpm build` generate the default modules if none exist yet.
+Run `pnpm gen` again to change their number.
+
+Each feature declares its cross-module references in `tanstack.router.module.uses`.
+The application selects each module's mount path explicitly in `includes[].at`.
+The feature's viewer requirement is a type-only `StartModuleRequirements`
+augmentation; the application supplies that context through request middleware.
+
+## Build
+
+```sh
+pnpm build # Vite
+pnpm build:rsbuild # Rsbuild
+pnpm start
+```
+
+The Nx build targets are uncached because these commands preserve the selected
+workload in ignored generated directories. Their output must be built for the
+current workload instead of restored from a cache that omits those inputs.
+
+## Measure
+
+```sh
+pnpm gen --modules 100
+pnpm measure --runs 3 --profile
+pnpm gen --modules 100 --transpiled
+pnpm measure --runs 3 --profile
+```
+
+`pnpm measure` builds the application with Vite and with Rsbuild (one of them
+with `--toolchain vite` or `--toolchain rsbuild`) and prints the median and
+fastest build time. `--profile` adds one build under the V8 CPU profiler. It
+lists where the JavaScript threads spent their time, by package. Time spent
+inside a TanStack plugin, including the Babel passes it runs, counts for that
+plugin. The results are saved to `measurements/` (not committed).
+
+The example lists `@tanstack/router-core` and `@tanstack/start-client-core`
+because it links the framework packages from this repository: the modules'
+declarations name the types of a linked package's dependencies by their own
+package name.
diff --git a/examples/react/start-large-route-modules/app/rsbuild.config.ts b/examples/react/start-large-route-modules/app/rsbuild.config.ts
new file mode 100644
index 0000000000..bbb8ab7955
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/rsbuild.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from '@rsbuild/core'
+import { pluginReact } from '@rsbuild/plugin-react'
+import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
+import { routeModules } from './route-modules.gen'
+
+export default defineConfig({
+ server: {
+ port: 3000,
+ },
+ plugins: [pluginReact(), tanstackStart({ router: { routeModules } })],
+})
diff --git a/examples/react/start-large-route-modules/app/server.js b/examples/react/start-large-route-modules/app/server.js
new file mode 100644
index 0000000000..36d7e661c3
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/server.js
@@ -0,0 +1,18 @@
+// Serves a production build of either toolchain: Vite writes the server
+// entry to `server/server.js`, Rsbuild to `server/index.js`.
+import { spawn } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import path from 'node:path'
+
+const serverEntry =
+ ['server.js', 'index.js']
+ .map((file) => path.resolve('dist', 'server', file))
+ .find((file) => existsSync(file)) ??
+ path.resolve('dist', 'server', 'server.js')
+
+const child = spawn(
+ 'srvx',
+ ['--prod', '-s', path.resolve('dist', 'client'), serverEntry],
+ { stdio: 'inherit', shell: process.platform === 'win32' },
+)
+child.on('exit', (code) => process.exit(code ?? 0))
diff --git a/examples/react/start-large-route-modules/app/src/router.tsx b/examples/react/start-large-route-modules/app/src/router.tsx
new file mode 100644
index 0000000000..a00a209fc4
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/src/router.tsx
@@ -0,0 +1,10 @@
+import { createRouter } from '@tanstack/react-router'
+import { routeTree } from './routeTree.gen'
+
+export function getRouter() {
+ return createRouter({
+ routeTree,
+ defaultPreload: 'intent',
+ scrollRestoration: true,
+ })
+}
diff --git a/examples/react/start-large-route-modules/app/src/routes/__root.tsx b/examples/react/start-large-route-modules/app/src/routes/__root.tsx
new file mode 100644
index 0000000000..2f0f71764e
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/src/routes/__root.tsx
@@ -0,0 +1,44 @@
+///
+import type { ReactNode } from 'react'
+import {
+ HeadContent,
+ Link,
+ Scripts,
+ createRootRoute,
+} from '@tanstack/react-router'
+import { account } from '../routeScope.gen'
+import '../styles.css'
+
+export const Route = createRootRoute({
+ head: () => ({
+ meta: [
+ { charSet: 'utf-8' },
+ { name: 'viewport', content: 'width=device-width, initial-scale=1' },
+ { title: 'Large route modules' },
+ ],
+ }),
+ shellComponent: RootDocument,
+})
+
+function RootDocument({ children }: { children: ReactNode }) {
+ return (
+
+
+
+
+
+
+
+ Large route modules
+
+
+ Modules
+ Account
+
+
+ {children}
+
+
+
+ )
+}
diff --git a/examples/react/start-large-route-modules/app/src/routes/index.tsx b/examples/react/start-large-route-modules/app/src/routes/index.tsx
new file mode 100644
index 0000000000..1f710d26aa
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/src/routes/index.tsx
@@ -0,0 +1,23 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { moduleIndex } from '../moduleIndex.gen'
+
+export const Route = createFileRoute('/')({
+ component: Home,
+})
+
+function Home() {
+ return (
+ <>
+ Modules
+
+ {moduleIndex.length} generated feature modules, each its own package
+ with its own routes, server functions and middleware.
+
+
+ {moduleIndex.map(({ name, link }) => (
+ {link}
+ ))}
+
+ >
+ )
+}
diff --git a/examples/react/start-large-route-modules/app/src/start.ts b/examples/react/start-large-route-modules/app/src/start.ts
new file mode 100644
index 0000000000..1205da611b
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/src/start.ts
@@ -0,0 +1,10 @@
+import { createMiddleware, createStart } from '@tanstack/react-start'
+
+// Provides the request context every feature module requires.
+const viewer = createMiddleware().server(({ next }) =>
+ next({ context: { viewer: 'ada' } }),
+)
+
+export const startInstance = createStart(() => ({
+ requestMiddleware: [viewer],
+}))
diff --git a/examples/react/start-large-route-modules/app/src/styles.css b/examples/react/start-large-route-modules/app/src/styles.css
new file mode 100644
index 0000000000..46046be435
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/src/styles.css
@@ -0,0 +1,114 @@
+:root {
+ color-scheme: light;
+ --ground: #f5f6f8;
+ --sheet: #ffffff;
+ --ink: #1f2328;
+ --ink-2: #565e67;
+ --line: #d6dadf;
+ --accent: #3d5bd9;
+ --font:
+ ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto,
+ 'Helvetica Neue', Arial, sans-serif;
+ --mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ margin: 0;
+ background: var(--ground);
+ color: var(--ink);
+ font: 15px/1.5 var(--font);
+}
+
+a {
+ color: inherit;
+ text-underline-offset: 3px;
+}
+
+a.active {
+ color: var(--accent);
+ font-weight: 600;
+}
+
+.topbar {
+ display: flex;
+ align-items: center;
+ gap: 24px;
+ padding: 12px 24px;
+ background: var(--sheet);
+ border-bottom: 1px solid var(--line);
+}
+
+.brand {
+ font-weight: 700;
+ text-decoration: none;
+}
+
+.nav,
+.module-nav {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+}
+
+.page {
+ max-width: 960px;
+ margin: 0 auto;
+ padding: 32px 24px 64px;
+}
+
+.lead {
+ color: var(--ink-2);
+ max-width: 60ch;
+}
+
+.grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
+ gap: 8px;
+ padding: 0;
+ list-style: none;
+}
+
+.grid a {
+ display: block;
+ padding: 8px 12px;
+ background: var(--sheet);
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ text-decoration: none;
+}
+
+.module {
+ padding: 20px 24px;
+ background: var(--sheet);
+ border: 1px solid var(--line);
+ border-radius: 8px;
+}
+
+.module-tag {
+ margin: 0 0 4px;
+ color: var(--ink-2);
+ font: 12px/1.4 var(--mono);
+}
+
+.rows {
+ padding-left: 20px;
+}
+
+.facts {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ gap: 4px 16px;
+}
+
+.facts dt {
+ color: var(--ink-2);
+}
+
+.facts dd {
+ margin: 0;
+}
diff --git a/examples/react/start-large-route-modules/app/tsconfig.json b/examples/react/start-large-route-modules/app/tsconfig.json
new file mode 100644
index 0000000000..60398c44b4
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ES2022",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": ["vite/client"]
+ },
+ "include": [
+ "src",
+ "vite.config.ts",
+ "rsbuild.config.ts",
+ "route-modules.gen.ts"
+ ]
+}
diff --git a/examples/react/start-large-route-modules/app/vite.config.ts b/examples/react/start-large-route-modules/app/vite.config.ts
new file mode 100644
index 0000000000..f211ef9e0b
--- /dev/null
+++ b/examples/react/start-large-route-modules/app/vite.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
+import { routeModules } from './route-modules.gen'
+
+export default defineConfig({
+ server: {
+ port: 3000,
+ },
+ plugins: [tanstackStart({ router: { routeModules } }), viteReact()],
+})
diff --git a/examples/react/start-large-route-modules/package.json b/examples/react/start-large-route-modules/package.json
new file mode 100644
index 0000000000..acffbe1479
--- /dev/null
+++ b/examples/react/start-large-route-modules/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "tanstack-start-example-large-route-modules",
+ "private": true,
+ "sideEffects": false,
+ "type": "module",
+ "nx": {
+ "targets": {
+ "build": {
+ "cache": false
+ },
+ "build:rsbuild": {
+ "cache": false
+ }
+ }
+ },
+ "scripts": {
+ "gen": "node scripts/gen.mjs",
+ "dev": "node scripts/gen.mjs --if-missing && cd app && vite dev",
+ "dev:rsbuild": "node scripts/gen.mjs --if-missing && cd app && rsbuild dev",
+ "build": "node scripts/gen.mjs --if-missing && cd app && vite build && tsc --noEmit",
+ "build:rsbuild": "node scripts/gen.mjs --if-missing && cd app && rsbuild build && tsc --noEmit",
+ "start": "cd app && node server.js",
+ "measure": "node scripts/measure.mjs"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "^1.170.46",
+ "@tanstack/react-start": "^1.169.4",
+ "react": "^19.0.0",
+ "react-dom": "^19.0.0"
+ },
+ "devDependencies": {
+ "@rsbuild/core": "^2.1.0",
+ "@rsbuild/plugin-react": "^2.0.0",
+ "@tanstack/router-core": "^1.171.39",
+ "@tanstack/router-generator": "^1.167.46",
+ "@tanstack/start-client-core": "^1.170.39",
+ "@types/node": "^22.5.4",
+ "@types/react": "^19.0.8",
+ "@types/react-dom": "^19.0.3",
+ "@typescript/native": "npm:typescript@^7.0.2",
+ "@vitejs/plugin-react": "^6.0.1",
+ "srvx": "^1.0.0",
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
+ "vite": "^8.0.14"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC"
+}
diff --git a/examples/react/start-large-route-modules/scripts/gen.mjs b/examples/react/start-large-route-modules/scripts/gen.mjs
new file mode 100644
index 0000000000..c7107aa461
--- /dev/null
+++ b/examples/react/start-large-route-modules/scripts/gen.mjs
@@ -0,0 +1,384 @@
+// Generates the route modules of the example from `template/` and the
+// application files that list them, then generates and publishes every module
+// in dependency order, with ordinary TypeScript declaration builds.
+//
+// pnpm gen [--modules ] [--routes ]
+// [--transpiled] [--if-missing]
+//
+// `--if-missing` keeps the modules of an earlier run: `dev` and `build`
+// generate the default modules only in a fresh checkout.
+//
+// `--transpiled` ships every module as JavaScript, the way a module built to
+// transpiled ESM would: after publishing its types, each module's TypeScript
+// sources are replaced with their oxc output and its manifest lists the
+// JavaScript route files. The application still code-splits and compiles
+// them. Comparing builds with and without it measures what prebuilding the
+// modules that way saves.
+//
+// The modules are packages in `modules/`, linked like workspace packages:
+// `modules/node_modules/` for the modules that use each other and
+// `app/node_modules` for the application. They resolve everything else from
+// the example's own dependencies.
+import { spawn } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import {
+ mkdir,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parseArgs } from 'node:util'
+import { Generator, getConfig } from '@tanstack/router-generator'
+import { transformWithOxc } from 'vite'
+
+const { values } = parseArgs({
+ options: {
+ modules: { type: 'string', default: '50' },
+ routes: { type: 'string', default: '10' },
+ transpiled: { type: 'boolean', default: false },
+ 'if-missing': { type: 'boolean', default: false },
+ },
+})
+const featureCount = Number(values.modules)
+const routeCount = Number(values.routes)
+// Every feature has a layout, an item list, an item and a search route, and
+// fills the rest with pages.
+const pageCount = routeCount - 4
+if (!Number.isInteger(featureCount) || featureCount < 1) {
+ throw new Error('--modules must be a positive integer')
+}
+if (!Number.isInteger(routeCount) || pageCount < 1) {
+ throw new Error('--routes must be an integer of at least 5')
+}
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const templateDir = path.join(root, 'template')
+const modulesDir = path.join(root, 'modules')
+const appDir = path.join(root, 'app')
+const scope = '@large-route-modules'
+
+if (
+ values['if-missing'] &&
+ existsSync(path.join(appDir, 'route-modules.gen.ts'))
+) {
+ process.exit(0)
+}
+
+const features = Array.from({ length: featureCount }, (_, index) => ({
+ name: `feature-${index}`,
+ title: `Feature ${index}`,
+}))
+
+async function listFiles(dir, base = dir) {
+ const files = []
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name)
+ if (entry.isDirectory()) {
+ files.push(...(await listFiles(full, base)))
+ } else {
+ files.push(path.relative(base, full))
+ }
+ }
+ return files
+}
+
+async function write(file, content) {
+ await mkdir(path.dirname(file), { recursive: true })
+ await writeFile(file, content)
+}
+
+function replaceAll(content, replacements) {
+ let result = content
+ for (const [placeholder, value] of Object.entries(replacements)) {
+ result = result.replaceAll(placeholder, value)
+ }
+ return result
+}
+
+function modulePackageJson({ name, dependencies = {} }) {
+ return {
+ name: `${scope}/${name}`,
+ private: true,
+ type: 'module',
+ tanstack: { router: { module: { uses: Object.keys(dependencies) } } },
+ exports: {
+ './route-types': {
+ types: './.tanstack/types/src/routeContract.gen.d.ts',
+ },
+ './route-module': {
+ types: './.tanstack/types/src/routeModule.gen.d.ts',
+ default: './src/routeModule.gen.ts',
+ },
+ './package.json': './package.json',
+ },
+ dependencies: {
+ ...dependencies,
+ '@tanstack/react-router': '*',
+ '@tanstack/react-start': '*',
+ react: '*',
+ },
+ }
+}
+
+const moduleTsconfig = {
+ compilerOptions: {
+ strict: true,
+ esModuleInterop: true,
+ jsx: 'react-jsx',
+ target: 'ESNext',
+ moduleResolution: 'Bundler',
+ module: 'ESNext',
+ lib: ['DOM', 'DOM.Iterable', 'ES2022'],
+ skipLibCheck: true,
+ noEmit: true,
+ types: [],
+ },
+ include: ['src'],
+}
+
+const json = (value) => `${JSON.stringify(value, null, 2)}\n`
+
+async function writeModule(name, templateName, packageJson, replacements) {
+ const dir = path.join(modulesDir, name)
+ const template = path.join(templateDir, templateName)
+ for (const file of await listFiles(template)) {
+ const content = await readFile(path.join(template, file), 'utf8')
+ if (file === path.join('src', 'routes', 'pages', 'page.tsx')) {
+ for (let page = 0; page < pageCount; page++) {
+ await write(
+ path.join(dir, 'src', 'routes', 'pages', `page-${page}.tsx`),
+ replaceAll(content, {
+ ...replacements,
+ __NEXT_PAGE__: String((page + 1) % pageCount),
+ __PAGE__: String(page),
+ }),
+ )
+ }
+ } else {
+ await write(path.join(dir, file), replaceAll(content, replacements))
+ }
+ }
+ await write(path.join(dir, 'package.json'), json(packageJson))
+ await write(path.join(dir, 'tsconfig.json'), json(moduleTsconfig))
+ await write(
+ path.join(dir, 'tsconfig.route-types.json'),
+ json({
+ extends: './tsconfig.json',
+ compilerOptions: {
+ noEmit: false,
+ declaration: true,
+ emitDeclarationOnly: true,
+ noEmitOnError: true,
+ declarationMap: true,
+ rootDir: '.',
+ outDir: '.tanstack/types',
+ },
+ }),
+ )
+ await symlink(
+ path.join('..', '..', name),
+ path.join(modulesDir, 'node_modules', scope, name),
+ 'dir',
+ )
+}
+
+async function runPool(items, concurrency, task) {
+ const queue = [...items]
+ await Promise.all(
+ Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
+ while (queue.length) {
+ await task(queue.shift())
+ }
+ }),
+ )
+}
+
+async function generate(name) {
+ const dir = path.join(modulesDir, name)
+ const config = getConfig({ disableLogging: true }, dir)
+ await new Generator({ config, root: dir }).run()
+}
+
+async function emitTypes(name) {
+ const packageRoot = path.join(modulesDir, name)
+ await rm(path.join(packageRoot, '.tanstack/types'), {
+ recursive: true,
+ force: true,
+ })
+ await new Promise((resolve, reject) => {
+ const child = spawn(
+ path.join(
+ root,
+ 'node_modules/.bin',
+ process.platform === 'win32' ? 'tsc.cmd' : 'tsc',
+ ),
+ ['-p', 'tsconfig.route-types.json', '--pretty', 'false'],
+ {
+ cwd: packageRoot,
+ stdio: 'inherit',
+ shell: process.platform === 'win32',
+ },
+ )
+ child.once('error', reject)
+ child.once('close', (code) => {
+ if (code === 0) {
+ resolve()
+ } else {
+ reject(new Error(`Declaration build of ${name} exited with ${code}`))
+ }
+ })
+ })
+}
+
+const started = performance.now()
+
+await rm(modulesDir, { recursive: true, force: true })
+await rm(path.join(appDir, 'node_modules'), { recursive: true, force: true })
+await mkdir(path.join(modulesDir, 'node_modules', scope), { recursive: true })
+await mkdir(path.join(appDir, 'node_modules'), { recursive: true })
+await symlink(
+ path.join('..', '..', 'modules', 'node_modules', scope),
+ path.join(appDir, 'node_modules', scope),
+ 'dir',
+)
+
+await writeModule(
+ 'account',
+ 'account',
+ modulePackageJson({ name: 'account' }),
+ {},
+)
+for (const feature of features) {
+ await writeModule(
+ feature.name,
+ 'feature',
+ modulePackageJson({
+ name: feature.name,
+ dependencies: { [`${scope}/account`]: 'link:../account' },
+ }),
+ { __MODULE_ID__: `${scope}/${feature.name}`, __TITLE__: feature.title },
+ )
+}
+
+// The application depends on every module it installs.
+const moduleIds = ['account', ...features.map((feature) => feature.name)].map(
+ (name) => `${scope}/${name}`,
+)
+await write(
+ path.join(appDir, 'package.json'),
+ json({
+ name: `${scope}/app`,
+ private: true,
+ type: 'module',
+ dependencies: {
+ ...Object.fromEntries(
+ moduleIds.map((id) => [
+ id,
+ `link:../modules/${id.slice(scope.length + 1)}`,
+ ]),
+ ),
+ '@tanstack/react-router': '*',
+ '@tanstack/react-start': '*',
+ react: '*',
+ 'react-dom': '*',
+ },
+ }),
+)
+await write(
+ path.join(appDir, 'route-modules.gen.ts'),
+ `// Written by \`pnpm gen\`: the modules the application installs.
+export const routeModules = {
+ includes: ${JSON.stringify(
+ moduleIds.map((module) => ({
+ module,
+ at: `/${module.slice(scope.length + 1)}`,
+ })),
+ null,
+ 2,
+ ).replaceAll('\n', '\n ')},
+}
+`,
+)
+const namespace = (name) => name.replace(/-(\w)/g, (_, c) => c.toUpperCase())
+await write(
+ path.join(appDir, 'src', 'moduleIndex.gen.tsx'),
+ `// Written by \`pnpm gen\`: a link to every feature module.
+import { ${features.map((feature) => namespace(feature.name)).join(', ')} } from './routeScope.gen'
+
+export const moduleIndex = [
+${features
+ .map(
+ (feature) =>
+ ` { name: '${feature.name}', link: <${namespace(feature.name)}.Link to="/">${feature.title}${namespace(feature.name)}.Link> },`,
+ )
+ .join('\n')}
+]
+`,
+)
+
+// The features use the account module: it is published first.
+await generate('account')
+await emitTypes('account')
+for (const feature of features) {
+ await generate(feature.name)
+}
+await runPool(
+ features.map((feature) => feature.name),
+ os.availableParallelism(),
+ emitTypes,
+)
+
+async function transpile(name) {
+ const dir = path.join(modulesDir, name)
+ const src = path.join(dir, 'src')
+ for (const file of await listFiles(src)) {
+ if (!/\.tsx?$/.test(file)) {
+ continue
+ }
+ const source = path.join(src, file)
+ const result = await transformWithOxc(
+ await readFile(source, 'utf8'),
+ source,
+ { jsx: { runtime: 'automatic' } },
+ )
+ await writeFile(source.replace(/\.tsx?$/, '.js'), result.code)
+ await rm(source)
+ }
+ const manifestPath = path.join(dir, '.tanstack', 'route-module.json')
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
+ for (const routeFile of manifest.routeFiles) {
+ routeFile.file = routeFile.file.replace(/\.tsx?$/, '.js')
+ }
+ for (const tree of manifest.clientTrees) {
+ tree.file = tree.file.replace(/\.tsx?$/, '.js')
+ tree.clientFile = tree.clientFile.replace(/\.tsx?$/, '.js')
+ }
+ await writeFile(manifestPath, json(manifest))
+ const packageJsonPath = path.join(dir, 'package.json')
+ const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf8'))
+ packageJson.exports['./route-module'].default = './src/routeModule.gen.js'
+ await writeFile(packageJsonPath, json(packageJson))
+}
+
+if (values.transpiled) {
+ await runPool(
+ ['account', ...features.map((feature) => feature.name)],
+ os.availableParallelism(),
+ transpile,
+ )
+}
+
+const seconds = ((performance.now() - started) / 1000).toFixed(1)
+console.log(
+ `Generated ${featureCount} feature modules with ${routeCount} routes each, plus the account module${values.transpiled ? ', as transpiled JavaScript,' : ''} in ${seconds}s.`,
+)
+if (!existsSync(path.join(appDir, 'src', 'routeTree.gen.ts'))) {
+ console.log(
+ 'The application generates its route tree on `pnpm dev` or `pnpm build`.',
+ )
+}
diff --git a/examples/react/start-large-route-modules/scripts/measure.mjs b/examples/react/start-large-route-modules/scripts/measure.mjs
new file mode 100644
index 0000000000..0c130f5a76
--- /dev/null
+++ b/examples/react/start-large-route-modules/scripts/measure.mjs
@@ -0,0 +1,242 @@
+// Measures production builds of the application with the modules `pnpm gen`
+// generated last.
+//
+// pnpm measure [--toolchain vite|rsbuild] [--runs ] [--profile]
+//
+// Each run is a fresh build process without the type check. `--profile` adds
+// one run under the V8 CPU profiler and lists where the JavaScript thread
+// spent its time, grouped by package. Work in native threads (Rolldown, Oxc,
+// Rspack, SWC) shows up only as the JavaScript thread waiting for it.
+import { spawn } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { parseArgs } from 'node:util'
+
+const { values } = parseArgs({
+ options: {
+ toolchain: { type: 'string', multiple: true },
+ runs: { type: 'string', default: '3' },
+ profile: { type: 'boolean', default: false },
+ },
+})
+const toolchains = values.toolchain ?? ['vite', 'rsbuild']
+const runs = Number(values.runs)
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
+const appDir = path.join(root, 'app')
+const modulesDir = path.join(root, 'modules')
+const require = createRequire(path.join(root, 'package.json'))
+
+const bins = {
+ vite: path.join(
+ path.dirname(require.resolve('vite/package.json')),
+ 'bin',
+ 'vite.js',
+ ),
+ rsbuild: path.join(
+ path.dirname(require.resolve('@rsbuild/core/package.json')),
+ 'bin',
+ 'rsbuild.js',
+ ),
+}
+
+if (!existsSync(path.join(appDir, 'route-modules.gen.ts'))) {
+ throw new Error('Generate the modules first: pnpm gen')
+}
+
+async function listFiles(dir) {
+ const files = []
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name)
+ if (entry.isDirectory()) {
+ files.push(...(await listFiles(full)))
+ } else {
+ files.push(full)
+ }
+ }
+ return files
+}
+
+function build(toolchain, nodeArgs = []) {
+ return new Promise((resolve, reject) => {
+ const started = performance.now()
+ const child = spawn(
+ process.execPath,
+ [...nodeArgs, bins[toolchain], 'build'],
+ {
+ cwd: appDir,
+ env: { ...process.env, NODE_ENV: 'production' },
+ stdio: ['ignore', 'ignore', 'pipe'],
+ },
+ )
+ let stderr = ''
+ child.stderr.on('data', (chunk) => (stderr += chunk))
+ child.on('error', reject)
+ child.on('close', (code) => {
+ if (code !== 0) {
+ reject(new Error(`${toolchain} build failed:\n${stderr}`))
+ } else {
+ resolve(performance.now() - started)
+ }
+ })
+ })
+}
+
+const workspacePackages = path.resolve(root, '..', '..', '..', 'packages')
+
+/** The package a profiled function belongs to, or a V8 category. */
+function categorize(callFrame) {
+ const url = callFrame.url
+ if (!url) {
+ return callFrame.functionName.startsWith('(')
+ ? callFrame.functionName
+ : '(native)'
+ }
+ if (url.startsWith('node:')) {
+ return 'node'
+ }
+ const file = url.startsWith('file://') ? fileURLToPath(url) : url
+ const nodeModules = file.lastIndexOf(`${path.sep}node_modules${path.sep}`)
+ if (nodeModules !== -1) {
+ const [first, second] = file
+ .slice(nodeModules + '/node_modules/'.length)
+ .split(path.sep)
+ return first.startsWith('@') ? `${first}/${second}` : first
+ }
+ if (file.startsWith(workspacePackages + path.sep)) {
+ return `@tanstack/${file.slice(workspacePackages.length + 1).split(path.sep)[0]}`
+ }
+ return path.relative(root, file).split(path.sep)[0]
+}
+
+/**
+ * Sums the sampled time of the profiles by the package of the sampled
+ * function, except that time spent inside a TanStack package's call (its
+ * Babel passes, for example) counts for the outermost TanStack package on the
+ * stack: the plugin that ran.
+ */
+async function summarizeProfiles(dir) {
+ const times = new Map()
+ let total = 0
+ for (const file of await readdir(dir)) {
+ const profile = JSON.parse(await readFile(path.join(dir, file), 'utf8'))
+ const nodes = new Map(profile.nodes.map((node) => [node.id, node]))
+ const parents = new Map()
+ for (const node of profile.nodes) {
+ for (const child of node.children ?? []) {
+ parents.set(child, node.id)
+ }
+ }
+ const owners = new Map()
+ const ownerOf = (id) => {
+ if (!owners.has(id)) {
+ const parent = parents.get(id)
+ const outer = parent === undefined ? undefined : ownerOf(parent)
+ const category = categorize(nodes.get(id).callFrame)
+ owners.set(
+ id,
+ outer ?? (category.startsWith('@tanstack/') ? category : undefined),
+ )
+ }
+ return owners.get(id)
+ }
+ for (let index = 0; index < profile.samples.length; index++) {
+ const id = profile.samples[index]
+ const delta = profile.timeDeltas[index] / 1000
+ const owner = ownerOf(id)
+ const category = owner
+ ? `${owner} (with callees)`
+ : categorize(nodes.get(id).callFrame)
+ times.set(category, (times.get(category) ?? 0) + delta)
+ total += delta
+ }
+ }
+ return {
+ total,
+ categories: [...times]
+ .sort((a, b) => b[1] - a[1])
+ .map(([category, ms]) => ({ category, ms })),
+ }
+}
+
+const median = (numbers) => {
+ const sorted = [...numbers].sort((a, b) => a - b)
+ const middle = Math.floor(sorted.length / 2)
+ return sorted.length % 2
+ ? sorted[middle]
+ : (sorted[middle - 1] + sorted[middle]) / 2
+}
+const ms = (value) => `${Math.round(value).toLocaleString('en-US')} ms`
+
+const moduleNames = (await readdir(modulesDir)).filter(
+ (name) => name !== 'node_modules',
+)
+const moduleFiles = (
+ await Promise.all(
+ moduleNames.map((name) => listFiles(path.join(modulesDir, name, 'src'))),
+ )
+).flat()
+const moduleCount = moduleNames.length
+const transpiled = !moduleFiles.some((file) => /\.tsx?$/.test(file))
+console.log(
+ `${moduleCount} modules, ${moduleFiles.length} module source files (${transpiled ? 'transpiled JavaScript' : 'TypeScript'})`,
+)
+
+const results = {
+ date: new Date().toISOString(),
+ modules: moduleCount,
+ moduleFiles: moduleFiles.length,
+ transpiled,
+ toolchains: {},
+}
+
+for (const toolchain of toolchains) {
+ if (!bins[toolchain]) {
+ throw new Error(`Unknown toolchain "${toolchain}": use vite or rsbuild`)
+ }
+ const times = []
+ for (let run = 0; run < runs; run++) {
+ await rm(path.join(appDir, 'dist'), { recursive: true, force: true })
+ times.push(await build(toolchain))
+ }
+ const clientChunks = (
+ await listFiles(path.join(appDir, 'dist', 'client'))
+ ).filter((file) => file.endsWith('.js')).length
+ console.log(
+ `${toolchain}: median ${ms(median(times))}, min ${ms(Math.min(...times))} over ${runs} runs (${clientChunks} client chunks)`,
+ )
+ const result = { times, clientChunks }
+
+ if (values.profile) {
+ const profileDir = path.join(
+ root,
+ 'measurements',
+ `${toolchain}-cpuprofile`,
+ )
+ await rm(profileDir, { recursive: true, force: true })
+ await mkdir(profileDir, { recursive: true })
+ await rm(path.join(appDir, 'dist'), { recursive: true, force: true })
+ await build(toolchain, ['--cpu-prof', `--cpu-prof-dir=${profileDir}`])
+ const summary = await summarizeProfiles(profileDir)
+ console.log(` JavaScript threads, ${ms(summary.total)} sampled:`)
+ for (const { category, ms: time } of summary.categories.slice(0, 15)) {
+ console.log(
+ ` ${category.padEnd(44)} ${ms(time).padStart(10)} ${((time / summary.total) * 100).toFixed(1).padStart(5)}%`,
+ )
+ }
+ result.profile = summary
+ }
+ results.toolchains[toolchain] = result
+}
+
+await mkdir(path.join(root, 'measurements'), { recursive: true })
+const resultFile = path.join(
+ root,
+ 'measurements',
+ `${results.date.replace(/[:.]/g, '-')}.json`,
+)
+await writeFile(resultFile, `${JSON.stringify(results, null, 2)}\n`)
+console.log(`Saved ${path.relative(root, resultFile)}`)
diff --git a/examples/react/start-large-route-modules/template/account/src/api.ts b/examples/react/start-large-route-modules/template/account/src/api.ts
new file mode 100644
index 0000000000..c94341627d
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/account/src/api.ts
@@ -0,0 +1,8 @@
+import { createServerFn } from './routeScope.gen'
+
+/** The signed-in account, loaded on the server. */
+export const getAccount = createServerFn().handler(() => ({
+ name: 'Ada Lovelace',
+ plan: 'Team',
+ seats: 12,
+}))
diff --git a/examples/react/start-large-route-modules/template/account/src/routes/__root.tsx b/examples/react/start-large-route-modules/template/account/src/routes/__root.tsx
new file mode 100644
index 0000000000..244e474f54
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/account/src/routes/__root.tsx
@@ -0,0 +1,18 @@
+import { Outlet } from '@tanstack/react-router'
+import { createModuleRoot } from '../routeScope.gen'
+
+export const Route = createModuleRoot()({
+ component: AccountLayout,
+})
+
+function AccountLayout() {
+ return (
+
+
+ @large-route-modules/account {Route.fullPath}
+
+ Account
+
+
+ )
+}
diff --git a/examples/react/start-large-route-modules/template/account/src/routes/index.tsx b/examples/react/start-large-route-modules/template/account/src/routes/index.tsx
new file mode 100644
index 0000000000..01480ab45a
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/account/src/routes/index.tsx
@@ -0,0 +1,21 @@
+import { createFileRoute } from '../routeScope.gen'
+import { getAccount } from '../api'
+
+export const Route = createFileRoute('@large-route-modules/account:/')({
+ loader: () => getAccount(),
+ component: Account,
+})
+
+function Account() {
+ const account = Route.useLoaderData()
+ return (
+
+ Name
+ {account.name}
+ Plan
+ {account.plan}
+ Seats
+ {account.seats}
+
+ )
+}
diff --git a/examples/react/start-large-route-modules/template/feature/src/api.ts b/examples/react/start-large-route-modules/template/feature/src/api.ts
new file mode 100644
index 0000000000..4cf635cb26
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/feature/src/api.ts
@@ -0,0 +1,45 @@
+import { notFound } from '@tanstack/react-router'
+import { createMiddleware, createServerFn } from './routeScope.gen'
+
+// Module-local: only this module's server functions run it.
+const audience = createMiddleware({ type: 'function' }).server(
+ ({ context, next }) =>
+ next({ context: { audience: `${context.viewer} in __MODULE_ID__` } }),
+)
+
+const items = Array.from({ length: 24 }, (_, index) => ({
+ id: `item-${index + 1}`,
+ name: `__TITLE__ item ${index + 1}`,
+ quantity: (index * 7) % 13,
+}))
+
+export const listItems = createServerFn()
+ .middleware([audience])
+ .handler(({ context }) => ({
+ audience: context.audience,
+ items: items.slice(0, 8).map(({ id, name }) => ({ id, name })),
+ }))
+
+export const getItem = createServerFn()
+ .middleware([audience])
+ .validator((id: string) => id)
+ .handler(({ data, context }) => {
+ const item = items.find((candidate) => candidate.id === data)
+ if (!item) {
+ throw notFound()
+ }
+ return { ...item, viewedBy: context.audience }
+ })
+
+const pageSize = 6
+
+/** Filters the items on whichever side runs the loader. */
+export function searchItems(query: string, page: number) {
+ const matches = items.filter((item) =>
+ item.name.toLowerCase().includes(query.toLowerCase()),
+ )
+ return {
+ items: matches.slice((page - 1) * pageSize, page * pageSize),
+ hasMore: matches.length > page * pageSize,
+ }
+}
diff --git a/examples/react/start-large-route-modules/template/feature/src/requirements.ts b/examples/react/start-large-route-modules/template/feature/src/requirements.ts
new file mode 100644
index 0000000000..4f1f611458
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/feature/src/requirements.ts
@@ -0,0 +1,10 @@
+export type { StartModuleRequirements } from '@tanstack/react-start'
+
+// The application says who is viewing; the module does not authenticate.
+declare module '@tanstack/react-start' {
+ interface StartModuleRequirements {
+ ['__MODULE_ID__']: {
+ requestContext: { viewer: string }
+ }
+ }
+}
diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/$itemId.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/$itemId.tsx
new file mode 100644
index 0000000000..3619e92ef4
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/feature/src/routes/$itemId.tsx
@@ -0,0 +1,28 @@
+import { Link, account, createFileRoute } from '../routeScope.gen'
+import { getItem } from '../api'
+
+export const Route = createFileRoute('__MODULE_ID__:/$itemId')({
+ loader: ({ params }) => getItem({ data: params.itemId }),
+ component: Item,
+})
+
+function Item() {
+ const item = Route.useLoaderData()
+ return (
+
+ {item.name}
+
+ Quantity
+ {item.quantity}
+ Viewed by
+
+ {item.viewedBy}
+
+
+
+ All items ·{' '}
+ Your account
+
+
+ )
+}
diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/__root.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/__root.tsx
new file mode 100644
index 0000000000..2c74ff494e
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/feature/src/routes/__root.tsx
@@ -0,0 +1,28 @@
+import { Outlet } from '@tanstack/react-router'
+import { Link, createModuleRoot } from '../routeScope.gen'
+export type {} from '../requirements'
+
+export const Route = createModuleRoot()({
+ component: FeatureLayout,
+})
+
+function FeatureLayout() {
+ return (
+
+
+ __MODULE_ID__ {Route.fullPath}
+
+ __TITLE__
+
+
+ Items
+
+
+ Search
+
+ Pages
+
+
+
+ )
+}
diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/index.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/index.tsx
new file mode 100644
index 0000000000..0bb446ebda
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/feature/src/routes/index.tsx
@@ -0,0 +1,25 @@
+import { Link, createFileRoute } from '../routeScope.gen'
+import { listItems } from '../api'
+
+export const Route = createFileRoute('__MODULE_ID__:/')({
+ loader: () => listItems(),
+ component: Items,
+})
+
+function Items() {
+ const { audience, items } = Route.useLoaderData()
+ return (
+ <>
+ Loaded on the server for {audience}.
+
+ {items.map((item) => (
+
+
+ {item.name}
+
+
+ ))}
+
+ >
+ )
+}
diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/pages/page.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/pages/page.tsx
new file mode 100644
index 0000000000..e4e2b1a42c
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/feature/src/routes/pages/page.tsx
@@ -0,0 +1,30 @@
+import { Fragment } from 'react'
+import { Link, createFileRoute } from '../../routeScope.gen'
+
+export const Route = createFileRoute('__MODULE_ID__:/pages/page-__PAGE__')({
+ loader: () => ({
+ rows: Array.from({ length: 8 }, (_, index) => ({
+ label: `Row ${index + 1}`,
+ value: (index + 1) * (__PAGE__ + 1),
+ })),
+ }),
+ component: Page,
+})
+
+function Page() {
+ const { rows } = Route.useLoaderData()
+ return (
+
+ Page __PAGE__ of __TITLE__
+
+ {rows.map((row) => (
+
+ {row.label}
+ {row.value}
+
+ ))}
+
+ Next page
+
+ )
+}
diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/search.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/search.tsx
new file mode 100644
index 0000000000..a6316c2946
--- /dev/null
+++ b/examples/react/start-large-route-modules/template/feature/src/routes/search.tsx
@@ -0,0 +1,44 @@
+import { Link, createFileRoute } from '../routeScope.gen'
+import { searchItems } from '../api'
+
+export const Route = createFileRoute('__MODULE_ID__:/search')({
+ validateSearch: (search: Record) => ({
+ q: typeof search.q === 'string' ? search.q : '',
+ page: Math.max(1, Number(search.page) || 1),
+ }),
+ loaderDeps: ({ search }) => search,
+ loader: ({ deps }) => searchItems(deps.q, deps.page),
+ component: Search,
+})
+
+function Search() {
+ const { q, page } = Route.useSearch()
+ const results = Route.useLoaderData()
+ const navigate = Route.useNavigate()
+ return (
+ <>
+
+ navigate({ search: { q: event.target.value, page: 1 } })
+ }
+ />
+
+ {results.items.map((item) => (
+
+
+ {item.name}
+
+
+ ))}
+
+ {results.hasMore ? (
+
+ Next results
+
+ ) : null}
+ >
+ )
+}
diff --git a/packages/eslint-plugin-router/src/__tests__/fixtures/app/package.json b/packages/eslint-plugin-router/src/__tests__/fixtures/app/package.json
new file mode 100644
index 0000000000..87b8a0c318
--- /dev/null
+++ b/packages/eslint-plugin-router/src/__tests__/fixtures/app/package.json
@@ -0,0 +1,4 @@
+{
+ "name": "@fixture/app",
+ "private": true
+}
diff --git a/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json b/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json
new file mode 100644
index 0000000000..346800ea14
--- /dev/null
+++ b/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "@fixture/route-module",
+ "private": true,
+ "tanstack": {
+ "router": {
+ "module": true
+ }
+ }
+}
diff --git a/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts b/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts
new file mode 100644
index 0000000000..8cf1df7ca9
--- /dev/null
+++ b/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts
@@ -0,0 +1,101 @@
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { RuleTester } from '@typescript-eslint/rule-tester'
+
+import {
+ name,
+ rule,
+} from '../rules/route-module-imports/route-module-imports.rule'
+
+const fixtures = path.join(
+ path.dirname(fileURLToPath(import.meta.url)),
+ 'fixtures',
+)
+const moduleFile = path.join(fixtures, 'route-module/src/routes/index.tsx')
+const appFile = path.join(fixtures, 'app/src/routes/index.tsx')
+const generatedFile = path.join(fixtures, 'route-module/src/routeScope.gen.ts')
+
+const ruleTester = new RuleTester()
+
+ruleTester.run(name, rule, {
+ valid: [
+ {
+ name: 'scope imports in a route module',
+ filename: moduleFile,
+ code: `
+ import { createFileRoute, Link } from '../routeScope.gen'
+ export const Route = createFileRoute('@fixture/route-module:/')({})
+ `,
+ },
+ {
+ name: 'APIs the scope does not provide',
+ filename: moduleFile,
+ code: `
+ import { Outlet, notFound, createSerializationAdapter } from '@tanstack/react-router'
+ import { createMiddleware, useServerFn } from '@tanstack/react-start'
+ `,
+ },
+ {
+ name: 'type-only imports',
+ filename: moduleFile,
+ code: `
+ import type { Link } from '@tanstack/react-router'
+ import { type useNavigate } from '@tanstack/solid-router'
+ `,
+ },
+ {
+ name: 'applications are not route modules',
+ filename: appFile,
+ code: `
+ import { createFileRoute, Link, createRootRoute } from '@tanstack/react-router'
+ import { createServerFn } from '@tanstack/react-start'
+ `,
+ },
+ {
+ name: 'generated files',
+ filename: generatedFile,
+ code: `
+ import { createServerFn as createStartServerFn } from '@tanstack/react-start'
+ `,
+ },
+ ],
+ invalid: [
+ {
+ name: 'routing APIs from the framework package',
+ filename: moduleFile,
+ code: `
+ import { createFileRoute, Link as RouterLink, Outlet } from '@tanstack/react-router'
+ import { useNavigate } from '@tanstack/vue-router'
+ `,
+ errors: [
+ { messageId: 'useRouteScope', data: { name: 'createFileRoute' } },
+ { messageId: 'useRouteScope', data: { name: 'Link' } },
+ { messageId: 'useRouteScope', data: { name: 'useNavigate' } },
+ ],
+ },
+ {
+ name: 'root route constructors',
+ filename: moduleFile,
+ code: `
+ import { createRootRouteWithContext } from '@tanstack/solid-router'
+ `,
+ errors: [
+ {
+ messageId: 'useModuleRoot',
+ data: { name: 'createRootRouteWithContext' },
+ },
+ ],
+ },
+ {
+ name: 'Start APIs from the framework package',
+ filename: moduleFile,
+ code: `
+ import { createServerFn, createStartModule } from '@tanstack/react-start'
+ `,
+ errors: [
+ { messageId: 'useRouteScope', data: { name: 'createServerFn' } },
+ { messageId: 'useRouteScope', data: { name: 'createStartModule' } },
+ ],
+ },
+ ],
+})
diff --git a/packages/eslint-plugin-router/src/index.ts b/packages/eslint-plugin-router/src/index.ts
index 7b8855cdf2..5bbc48de1e 100644
--- a/packages/eslint-plugin-router/src/index.ts
+++ b/packages/eslint-plugin-router/src/index.ts
@@ -27,6 +27,7 @@ Object.assign(plugin.configs, {
rules: {
'@tanstack/router/create-route-property-order': 'warn',
'@tanstack/router/route-param-names': 'error',
+ '@tanstack/router/route-module-imports': 'error',
},
},
'flat/recommended': [
@@ -37,6 +38,7 @@ Object.assign(plugin.configs, {
rules: {
'@tanstack/router/create-route-property-order': 'warn',
'@tanstack/router/route-param-names': 'error',
+ '@tanstack/router/route-module-imports': 'error',
},
},
],
diff --git a/packages/eslint-plugin-router/src/rules.ts b/packages/eslint-plugin-router/src/rules.ts
index 1042929a45..ebe904d098 100644
--- a/packages/eslint-plugin-router/src/rules.ts
+++ b/packages/eslint-plugin-router/src/rules.ts
@@ -1,5 +1,6 @@
import * as createRoutePropertyOrder from './rules/create-route-property-order/create-route-property-order.rule'
import * as routeParamNames from './rules/route-param-names/route-param-names.rule'
+import * as routeModuleImports from './rules/route-module-imports/route-module-imports.rule'
import type { ESLintUtils } from '@typescript-eslint/utils'
import type { ExtraRuleDocs } from './types'
@@ -14,4 +15,5 @@ export const rules: Record<
> = {
[createRoutePropertyOrder.name]: createRoutePropertyOrder.rule,
[routeParamNames.name]: routeParamNames.rule,
+ [routeModuleImports.name]: routeModuleImports.rule,
}
diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts
new file mode 100644
index 0000000000..3381caad47
--- /dev/null
+++ b/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts
@@ -0,0 +1,37 @@
+/**
+ * Routing APIs a route module's generated scope (`routeScope.gen.ts`) exports
+ * typed against the module's own routes.
+ */
+export const scopedRouterApis = [
+ 'createFileRoute',
+ 'Link',
+ 'createLink',
+ 'linkOptions',
+ 'Navigate',
+ 'useNavigate',
+ 'redirect',
+ 'MatchRoute',
+ 'useMatchRoute',
+ 'useRouter',
+ 'getRouteApi',
+ 'useMatch',
+ 'useMatches',
+ 'useParentMatches',
+ 'useChildMatches',
+ 'useLoaderData',
+ 'useLoaderDeps',
+ 'useSearch',
+ 'useParams',
+ 'useRouteContext',
+ 'useLocation',
+ 'useRouterState',
+] as const
+
+/** Root route constructors; a route module's root is `createModuleRoot`. */
+export const rootRouteConstructors = [
+ 'createRootRoute',
+ 'createRootRouteWithContext',
+] as const
+
+/** Start APIs a Start route module's scope exports. */
+export const scopedStartApis = ['createServerFn', 'createStartModule'] as const
diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts
new file mode 100644
index 0000000000..ab20f09c87
--- /dev/null
+++ b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts
@@ -0,0 +1,90 @@
+import path from 'node:path'
+import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils'
+
+import { getDocsUrl } from '../../utils/get-docs-url'
+import {
+ rootRouteConstructors,
+ scopedRouterApis,
+ scopedStartApis,
+} from './constants'
+import { isGeneratedFile, isInRouteModule } from './route-module-imports.utils'
+import type { ExtraRuleDocs } from '../../types'
+
+const createRule = ESLintUtils.RuleCreator(getDocsUrl)
+
+const routerPackage = /^@tanstack\/(react|solid|vue)-router$/
+const startPackage = /^@tanstack\/(react|solid|vue)-start$/
+const scopedRouterApiSet = new Set(scopedRouterApis)
+const rootRouteConstructorSet = new Set(rootRouteConstructors)
+const scopedStartApiSet = new Set(scopedStartApis)
+
+export const name = 'route-module-imports'
+
+export const rule = createRule({
+ name,
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Ensure route modules import routing and Start APIs from their generated route scope',
+ recommended: 'error',
+ },
+ messages: {
+ useRouteScope:
+ '"{{name}}" in a route module must be imported from its generated route scope (routeScope.gen), which types it against the module\'s own routes.',
+ useModuleRoot:
+ 'The root route of a route module is created with "createModuleRoot" from its generated route scope (routeScope.gen), not with "{{name}}".',
+ },
+ schema: [],
+ },
+ defaultOptions: [],
+
+ create(context) {
+ const filename = context.filename
+ if (isGeneratedFile(filename) || !isInRouteModule(path.dirname(filename))) {
+ return {}
+ }
+
+ return {
+ ImportDeclaration(node) {
+ if (node.importKind === 'type') {
+ return
+ }
+ const source = node.source.value
+ const fromRouter = routerPackage.test(source)
+ const fromStart = startPackage.test(source)
+ if (!fromRouter && !fromStart) {
+ return
+ }
+ for (const specifier of node.specifiers) {
+ if (
+ specifier.type !== AST_NODE_TYPES.ImportSpecifier ||
+ specifier.importKind === 'type'
+ ) {
+ continue
+ }
+ const imported =
+ specifier.imported.type === AST_NODE_TYPES.Identifier
+ ? specifier.imported.name
+ : specifier.imported.value
+ if (fromRouter && rootRouteConstructorSet.has(imported)) {
+ context.report({
+ node: specifier,
+ messageId: 'useModuleRoot',
+ data: { name: imported },
+ })
+ } else if (
+ (fromRouter && scopedRouterApiSet.has(imported)) ||
+ (fromStart && scopedStartApiSet.has(imported))
+ ) {
+ context.report({
+ node: specifier,
+ messageId: 'useRouteScope',
+ data: { name: imported },
+ })
+ }
+ }
+ },
+ }
+ },
+})
diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts
new file mode 100644
index 0000000000..c72e6df0a8
--- /dev/null
+++ b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts
@@ -0,0 +1,50 @@
+import fs from 'node:fs'
+import path from 'node:path'
+
+const routeModuleByDirectory = new Map()
+
+function readsAsRouteModule(packageJsonPath: string): boolean {
+ try {
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
+ return packageJson?.tanstack?.router?.module !== undefined
+ } catch {
+ return false
+ }
+}
+
+/**
+ * Whether `directory` belongs to a route module: its nearest `package.json`
+ * declares `tanstack.router.module`. Results are cached per directory.
+ */
+export function isInRouteModule(directory: string): boolean {
+ const visited: Array = []
+ let current = path.resolve(directory)
+ let result = false
+ for (;;) {
+ const cached = routeModuleByDirectory.get(current)
+ if (cached !== undefined) {
+ result = cached
+ break
+ }
+ visited.push(current)
+ const packageJsonPath = path.join(current, 'package.json')
+ if (fs.existsSync(packageJsonPath)) {
+ result = readsAsRouteModule(packageJsonPath)
+ break
+ }
+ const parent = path.dirname(current)
+ if (parent === current) {
+ break
+ }
+ current = parent
+ }
+ for (const dir of visited) {
+ routeModuleByDirectory.set(dir, result)
+ }
+ return result
+}
+
+/** Generated files (`routeScope.gen.ts` imports the framework itself). */
+export function isGeneratedFile(filename: string): boolean {
+ return /\.gen\.[cm]?[jt]sx?$/.test(filename)
+}
diff --git a/packages/eslint-plugin-router/tsconfig.json b/packages/eslint-plugin-router/tsconfig.json
index cbceff3f8b..1715152a91 100644
--- a/packages/eslint-plugin-router/tsconfig.json
+++ b/packages/eslint-plugin-router/tsconfig.json
@@ -1,7 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
- "moduleResolution": "Bundler"
+ "moduleResolution": "Bundler",
+ "types": ["node"]
},
"include": ["src", "eslint.config.js", "vite.config.ts"]
}
diff --git a/packages/react-router/package.json b/packages/react-router/package.json
index 9a61d5af25..94ce82d1ac 100644
--- a/packages/react-router/package.json
+++ b/packages/react-router/package.json
@@ -27,12 +27,12 @@
"clean": "rimraf ./dist && rimraf ./coverage",
"test:eslint": "eslint",
"test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"",
- "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js -p tsconfig.legacy.json",
- "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js -p tsconfig.legacy.json",
- "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js -p tsconfig.legacy.json",
- "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json",
- "test:types:ts60": "tsc6 -p tsconfig.legacy.json",
- "test:types:ts70": "tsc -p tsconfig.legacy.json",
+ "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js -p tsconfig.legacy.json && node ../../node_modules/typescript56/lib/tsc.js -p tests/registered-router-cycle/tsconfig.json",
+ "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js -p tsconfig.legacy.json && node ../../node_modules/typescript57/lib/tsc.js -p tests/registered-router-cycle/tsconfig.json",
+ "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js -p tsconfig.legacy.json && node ../../node_modules/typescript58/lib/tsc.js -p tests/registered-router-cycle/tsconfig.json",
+ "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json && node ../../node_modules/typescript59/lib/tsc.js -p tests/registered-router-cycle/tsconfig.json",
+ "test:types:ts60": "tsc6 -p tsconfig.legacy.json && tsc6 -p tests/registered-router-cycle/tsconfig.json",
+ "test:types:ts70": "tsc -p tsconfig.legacy.json && tsc -p tests/registered-router-cycle/tsconfig.json",
"test:unit": "vitest",
"test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests",
"test:perf": "vitest bench",
@@ -81,7 +81,17 @@
"default": "./dist/cjs/ssr/client.cjs"
}
},
- "./package.json": "./package.json"
+ "./package.json": "./package.json",
+ "./_internal/route-module": {
+ "import": {
+ "types": "./dist/esm/route-module-internal.d.ts",
+ "default": "./dist/esm/route-module-internal.js"
+ },
+ "require": {
+ "types": "./dist/cjs/route-module-internal.d.cts",
+ "default": "./dist/cjs/route-module-internal.cjs"
+ }
+ }
},
"sideEffects": false,
"files": [
diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx
index db1d341ec4..8e84163119 100644
--- a/packages/react-router/src/Match.tsx
+++ b/packages/react-router/src/Match.tsx
@@ -1,5 +1,6 @@
'use client'
+import { resolveRouteId } from '@tanstack/router-core/_internal/route-module'
import * as React from 'react'
import { useSelector } from '@tanstack/react-store'
import { isNotFound, rootRouteId } from '@tanstack/router-core'
@@ -111,7 +112,10 @@ function matchView(router: ReturnType, match: AnyRouteMatch) {
{
error.routeId ??= match.routeId
- if (error.routeId !== match.routeId) {
+ if (
+ (resolveRouteId?.(router, error.routeId, match.routeId) ??
+ error.routeId) !== match.routeId
+ ) {
throw error
}
const notFoundElement = React.createElement(
diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx
index a20c862b23..50c118769a 100644
--- a/packages/react-router/src/Matches.tsx
+++ b/packages/react-router/src/Matches.tsx
@@ -25,12 +25,14 @@ import type {
MakeRouteMatchUnion,
MaskOptions,
MatchRouteOptions,
+ Register,
RegisteredRouter,
+ RegisteredRouterOf,
ResolveRoute,
ToSubOptionsProps,
} from '@tanstack/router-core'
-declare module '@tanstack/router-core' {
+declare module '@tanstack/router-core/extensions' {
export interface RouteMatchExtensions {
meta?: Array
links?: Array
@@ -134,6 +136,21 @@ export type UseMatchRouteOptions<
MaskOptions &
MatchRouteOptions
+/**
+ * The signature of `useMatchRoute`, typed against the router of `TDefaultRegister` unless a router
+ * type is passed explicitly. Route modules export a `useMatchRoute` of this type.
+ */
+export type UseMatchRouteFn = <
+ TRouter extends AnyRouter = RegisteredRouterOf,
+>() => <
+ const TFrom extends string = string,
+ const TTo extends string | undefined = undefined,
+ const TMaskFrom extends string = TFrom,
+ const TMaskTo extends string = '',
+>(
+ opts: UseMatchRouteOptions,
+) => false | Expand['types']['allParams']>
+
/**
* Create a matcher function for testing locations against route definitions.
*
@@ -213,6 +230,20 @@ export type MakeMatchRouteOptions<
| React.ReactNode
}
+/**
+ * The signature of `MatchRoute`, typed against the router of `TDefaultRegister` unless a router
+ * type is passed explicitly. Route modules export a `MatchRoute` of this type.
+ */
+export type MatchRouteFn = <
+ TRouter extends AnyRouter = RegisteredRouterOf,
+ const TFrom extends string = string,
+ const TTo extends string | undefined = undefined,
+ const TMaskFrom extends string = TFrom,
+ const TMaskTo extends string = '',
+>(
+ props: MakeMatchRouteOptions,
+) => any
+
/**
* Component that conditionally renders its children based on whether a route
* matches the provided `from`/`to` options. If `children` is a function, it
@@ -252,6 +283,19 @@ export type UseMatchesResult<
TSelected,
> = unknown extends TSelected ? Array> : TSelected
+/**
+ * The signature of `useMatches`, typed against the router of `TDefaultRegister` unless a router
+ * type is passed explicitly. Route modules export a `useMatches` of this type.
+ */
+export type UseMatchesFn = <
+ TRouter extends AnyRouter = RegisteredRouterOf,
+ TSelected = unknown,
+ TStructuralSharing extends boolean = boolean,
+>(
+ opts?: UseMatchesBaseOptions &
+ StructuralSharingOption,
+) => UseMatchesResult
+
export function useMatches<
TRouter extends AnyRouter = RegisteredRouter,
TSelected = unknown,
@@ -280,6 +324,19 @@ export function useMatches<
) as UseMatchesResult
}
+/**
+ * The signature of `useParentMatches`, typed against the router of `TDefaultRegister` unless a router
+ * type is passed explicitly. Route modules export a `useParentMatches` of this type.
+ */
+export type UseParentMatchesFn = <
+ TRouter extends AnyRouter = RegisteredRouterOf,
+ TSelected = unknown,
+ TStructuralSharing extends boolean = boolean,
+>(
+ opts?: UseMatchesBaseOptions &
+ StructuralSharingOption,
+) => UseMatchesResult
+
/**
* Read the presented route matches above the current match, or select a
* derived value from them.
@@ -306,6 +363,19 @@ export function useParentMatches<
} as any)
}
+/**
+ * The signature of `useChildMatches`, typed against the router of `TDefaultRegister` unless a router
+ * type is passed explicitly. Route modules export a `useChildMatches` of this type.
+ */
+export type UseChildMatchesFn = <
+ TRouter extends AnyRouter = RegisteredRouterOf,
+ TSelected = unknown,
+ TStructuralSharing extends boolean = boolean,
+>(
+ opts?: UseMatchesBaseOptions &
+ StructuralSharingOption,
+) => UseMatchesResult
+
/**
* Read the presented route matches below the current match, or select a
* derived value from them.
diff --git a/packages/react-router/src/fileRoute.ts b/packages/react-router/src/fileRoute.ts
index f4d8c9b967..154422460c 100644
--- a/packages/react-router/src/fileRoute.ts
+++ b/packages/react-router/src/fileRoute.ts
@@ -64,6 +64,81 @@ export function createFileRoute<
}
}
+/**
+ * The route factory returned by `createFileRoute(path)`. `TDefaultRegister`
+ * is the scope of the created route: the application's `Register`, or the
+ * scope register of a route module.
+ */
+export type FileRouteFactory<
+ TFilePath extends string,
+ TParentRoute extends AnyRoute,
+ TId extends RouteConstraints['TId'],
+ TPath extends RouteConstraints['TPath'],
+ TFullPath extends RouteConstraints['TFullPath'],
+ TDefaultRegister = Register,
+> = <
+ TRegister = TDefaultRegister,
+ TSearchValidator = undefined,
+ TParams = ResolveParams,
+ TRouteContextFn = AnyContext,
+ TBeforeLoadFn = AnyContext,
+ TLoaderDeps extends Record = {},
+ TLoaderFn = undefined,
+ TChildren = unknown,
+ TSSR = unknown,
+ const TMiddlewares = unknown,
+ THandlers = undefined,
+>(
+ options?: FileBaseRouteOptions<
+ TRegister,
+ TParentRoute,
+ TId,
+ TPath,
+ TSearchValidator,
+ TParams,
+ TLoaderDeps,
+ TLoaderFn,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ AnyContext,
+ TSSR,
+ TMiddlewares,
+ THandlers
+ > &
+ UpdatableRouteOptions<
+ TParentRoute,
+ TId,
+ TFullPath,
+ TParams,
+ TSearchValidator,
+ TLoaderFn,
+ TLoaderDeps,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn
+ >,
+) => Route<
+ TRegister,
+ TParentRoute,
+ TPath,
+ TFullPath,
+ TFilePath,
+ TId,
+ TSearchValidator,
+ TParams,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TChildren,
+ unknown,
+ TSSR,
+ TMiddlewares,
+ THandlers
+>
+
/**
@deprecated It's no longer recommended to use the `FileRoute` class directly.
Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.
@@ -85,68 +160,13 @@ export class FileRoute<
this.silent = _opts?.silent
}
- createRoute = <
- TRegister = Register,
- TSearchValidator = undefined,
- TParams = ResolveParams,
- TRouteContextFn = AnyContext,
- TBeforeLoadFn = AnyContext,
- TLoaderDeps extends Record = {},
- TLoaderFn = undefined,
- TChildren = unknown,
- TSSR = unknown,
- const TMiddlewares = unknown,
- THandlers = undefined,
- >(
- options?: FileBaseRouteOptions<
- TRegister,
- TParentRoute,
- TId,
- TPath,
- TSearchValidator,
- TParams,
- TLoaderDeps,
- TLoaderFn,
- AnyContext,
- TRouteContextFn,
- TBeforeLoadFn,
- AnyContext,
- TSSR,
- TMiddlewares,
- THandlers
- > &
- UpdatableRouteOptions<
- TParentRoute,
- TId,
- TFullPath,
- TParams,
- TSearchValidator,
- TLoaderFn,
- TLoaderDeps,
- AnyContext,
- TRouteContextFn,
- TBeforeLoadFn
- >,
- ): Route<
- TRegister,
- TParentRoute,
- TPath,
- TFullPath,
+ createRoute: FileRouteFactory<
TFilePath,
+ TParentRoute,
TId,
- TSearchValidator,
- TParams,
- AnyContext,
- TRouteContextFn,
- TBeforeLoadFn,
- TLoaderDeps,
- TLoaderFn,
- TChildren,
- unknown,
- TSSR,
- TMiddlewares,
- THandlers
- > => {
+ TPath,
+ TFullPath
+ > = (options) => {
if (process.env.NODE_ENV !== 'production') {
if (!this.silent) {
console.warn(
@@ -192,7 +212,7 @@ export function FileRouteLoader<
return (loaderFn) => loaderFn as any
}
-declare module '@tanstack/router-core' {
+declare module '@tanstack/router-core/extensions' {
export interface LazyRoute {
useMatch: UseMatchRoute
useRouteContext: UseRouteContextRoute
diff --git a/packages/react-router/src/index.tsx b/packages/react-router/src/index.tsx
index 23ebf57938..96d6bbbcb8 100644
--- a/packages/react-router/src/index.tsx
+++ b/packages/react-router/src/index.tsx
@@ -185,6 +185,8 @@ export type {
ResolvedRedirect,
MakeRouteMatch,
MakeRouteMatchUnion,
+ KnownRouteMatchUnion,
+ ForeignRouteMatch,
RouteMatch,
AnyRouteMatch,
RouteContextFn,
@@ -269,9 +271,54 @@ export type {
DefaultRouteTypes,
RouteTypes,
} from './route'
+// `createFileRoute` returns router-core's `Route`, and `Route` above is this
+// package's class: declarations name the type of file routes through this
+// export, so they need no import of `@tanstack/router-core`.
+export type { Route as RouteCore } from '@tanstack/router-core'
export { createRouter, Router } from './router'
+export type {
+ FileRoutesByPathEntry,
+ FileRouteScope,
+ RouteScope,
+} from './routeModule'
+export type { FileRouteFactory } from './fileRoute'
+export type {
+ HostedRouter,
+ InstallationRoutesById,
+ MountedRoutesById,
+ ModuleRootRoute,
+ ModuleRootRouteOptions,
+ MountRouteModuleOptions,
+ RedirectFn,
+ RegisteredRouterOf,
+ ScopeRouter,
+ ScopedRouter,
+ ScopedRouterView,
+ ValidateRouteModuleMount,
+ ValidateRouteModuleMountPath,
+} from '@tanstack/router-core'
+export type { GetRouteApiFn } from './route'
+export type { CreateLinkFn, LinkOptionsFn } from './link'
+export type { NavigateComponentFn, UseNavigateFn } from './useNavigate'
+export type {
+ MatchRouteFn,
+ UseChildMatchesFn,
+ UseMatchRouteFn,
+ UseMatchesFn,
+ UseParentMatchesFn,
+} from './Matches'
+export type { UseRouterFn } from './useRouter'
+export type { UseMatchFn } from './useMatch'
+export type { UseLoaderDataFn } from './useLoaderData'
+export type { UseLoaderDepsFn } from './useLoaderDeps'
+export type { UseSearchFn } from './useSearch'
+export type { UseParamsFn } from './useParams'
+export type { UseRouteContextFn } from './useRouteContext'
+export type { UseLocationFn } from './useLocation'
+export type { UseRouterStateFn } from './useRouterState'
+
export { lazyFn, SearchParamError } from '@tanstack/router-core'
export { RouterProvider, RouterContextProvider } from './RouterProvider'
diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx
index ce6a7ed9d1..0087ef991d 100644
--- a/packages/react-router/src/link.tsx
+++ b/packages/react-router/src/link.tsx
@@ -12,16 +12,20 @@ import {
import { isServer } from '@tanstack/router-core/isServer'
import { useRouter } from './useRouter'
import { createLinkScope, matchContext } from './matchContext'
-
import type {
ActiveOptions,
AnyRouter,
Constrain,
LinkOptions,
ParsedLocation,
+ Register,
RegisteredRouter,
+ RegisteredRouterOf,
+ RouteModuleScope,
RoutePaths,
+ ScopedRouteOptions,
} from '@tanstack/router-core'
+
import type { ReactNode } from 'react'
import type {
ValidateLinkOptions,
@@ -131,6 +135,17 @@ function resolveIsActive(
* @returns React anchor props suitable for `` or custom components.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook
*/
+export type UseLinkPropsFn = <
+ TRouter extends AnyRouter = RegisteredRouterOf,
+ TFrom extends string = string,
+ TTo extends string = '',
+ TMaskFrom extends string = TFrom,
+ TMaskTo extends string = '',
+>(
+ options: UseLinkPropsOptions,
+ forwardedRef?: React.ForwardedRef,
+) => React.ComponentPropsWithRef<'a'>
+
export function useLinkProps<
TRouter extends AnyRouter = RegisteredRouter,
const TFrom extends string = string,
@@ -172,6 +187,9 @@ export function useLinkProps<
host?: 'a' | React.ElementType,
): React.ComponentPropsWithRef<'a'> {
const router = useRouter()
+ // The route of the nearest match: it scopes the links of a route, and
+ // module destinations resolve to the installation it belongs to.
+ const routeId = React.useContext(matchContext)
// ==========================================================================
// SERVER EARLY RETURN
@@ -188,7 +206,7 @@ export function useLinkProps<
// browser-build constant `isServer = false` and drop this server block,
// together with `getServerLinkProps` and the key sets only it references.
if (isServer ?? router.isServer) {
- return getServerLinkProps(router, options, forwardedRef, host)
+ return getServerLinkProps(router, options, forwardedRef, host, routeId)
}
// ==========================================================================
@@ -239,7 +257,14 @@ export function useLinkProps<
onMouseEnter,
onMouseLeave,
onTouchStart,
- } = options as typeof options & { to?: string }
+ // Route-module scope; constant for a given scoped component.
+ _module,
+ _fromRoute,
+ } = options as typeof options & {
+ to?: string
+ _module?: RouteModuleScope
+ _fromRoute?: string
+ }
// eslint-disable-next-line react-hooks/rules-of-hooks
const [stableSearch, stableParams, stableActiveOptions] = useStableValues(
@@ -249,8 +274,6 @@ export function useLinkProps<
)
// The links of a route share its location source. Links outside every
// match share one that never departs.
- // eslint-disable-next-line react-hooks/rules-of-hooks
- const routeId = React.useContext(matchContext)
const scope = ((router.stores._linkScopes ??= {})[routeId!] ??=
createLinkScope(router, routeId))
@@ -270,7 +293,9 @@ export function useLinkProps<
return [options, () => state] as const
}
- const dest = { ...options } as any
+ // The nearest route resolves module destinations to the installation
+ // the link renders under; other destinations ignore it.
+ const dest = { ...options, _nearestRoute: routeId } as any
let source: ParsedLocation | undefined
let state: LinkState
let hydrationState: LinkState | undefined
@@ -335,6 +360,8 @@ export function useLinkProps<
options.state,
options.mask,
options.unsafeRelative,
+ _module,
+ _fromRoute,
stableActiveOptions,
disabled,
])
@@ -450,9 +477,14 @@ export function useLinkProps<
cancelPreload(innerRef)
// The current options carry the navigation controls; `dest` only
- // contributes the location the link displays. Navigation builds again
- // to run `validateSearch` before committing.
- router.navigate({ ...options, _fromLocation: dest._fromLocation })
+ // contributes the location the link displays and the installation of a
+ // module destination. Navigation builds again to run `validateSearch`
+ // before committing.
+ router.navigate({
+ ...options,
+ _fromLocation: dest._fromLocation,
+ _nearestRoute: routeId,
+ })
}
}
@@ -504,6 +536,8 @@ const ROUTER_OPTION_KEYS = /* @__PURE__ */ new Set([
'inactiveProps',
'activeOptions',
'_asChild',
+ '_module',
+ '_fromRoute',
])
// Copies the element props. An object rest would test every key against the
@@ -588,6 +622,7 @@ function getServerLinkProps(
options: any,
forwardedRef: React.ForwardedRef | undefined,
host: 'a' | React.ElementType | undefined,
+ routeId: string | undefined,
): React.ComponentPropsWithRef<'a'> {
const { to, disabled, activeOptions } = options as {
to: string | undefined
@@ -600,7 +635,13 @@ function getServerLinkProps(
// Direct-scheme links need no route resolution. Blocked links still use
// the shared inactive-prop merge so their server and client markup agree.
const next =
- directExternalLink === undefined ? router.buildLocation(options) : undefined
+ directExternalLink === undefined
+ ? router.buildLocation(
+ options._module === undefined
+ ? options
+ : { ...options, _nearestRoute: routeId },
+ )
+ : undefined
const hrefOption = next
? getHrefOption(next, router, disabled)
@@ -778,8 +819,9 @@ export type CreateLinkProps = LinkProps<
export type LinkComponent<
in out TComp,
in out TDefaultFrom extends string = string,
+ in out TDefaultRegister = Register,
> = <
- TRouter extends AnyRouter = RegisteredRouter,
+ TRouter extends AnyRouter = RegisteredRouterOf,
const TFrom extends string = TDefaultFrom,
const TTo extends string | undefined = undefined,
const TMaskFrom extends string = TFrom,
@@ -790,10 +832,11 @@ export type LinkComponent<
export interface LinkComponentRoute<
in out TDefaultFrom extends string = string,
+ in out TDefaultRegister = Register,
> {
defaultFrom: TDefaultFrom;
<
- TRouter extends AnyRouter = RegisteredRouter,
+ TRouter extends AnyRouter = RegisteredRouterOf,
const TTo extends string | undefined = undefined,
const TMaskTo extends string = '',
>(
@@ -808,6 +851,14 @@ export interface LinkComponentRoute<
): React.ReactElement
}
+/**
+ * The signature of `createLink`, creating links typed against the router of `TDefaultRegister`.
+ * Route modules export a `createLink` of this type.
+ */
+export type CreateLinkFn = (
+ Comp: Constrain ReactNode>,
+) => LinkComponent
+
/**
* Creates a typed Link-like component that preserves TanStack Router's
* navigation semantics and type-safety while delegating rendering to the
@@ -899,12 +950,12 @@ export type LinkOptionsFnOptions<
? ValidateLinkOptionsArray
: ValidateLinkOptions
-export type LinkOptionsFn = <
+export type LinkOptionsFn = <
const TOptions,
- TRouter extends AnyRouter = RegisteredRouter,
+ TRouter extends AnyRouter = RegisteredRouterOf,
>(
options: LinkOptionsFnOptions,
-) => TOptions
+) => ScopedRouteOptions
/**
* Validate and reuse navigation options for `Link`, `navigate` or `redirect`.
diff --git a/packages/react-router/src/matchContext.tsx b/packages/react-router/src/matchContext.tsx
index 12db4dbada..0948eb8048 100644
--- a/packages/react-router/src/matchContext.tsx
+++ b/packages/react-router/src/matchContext.tsx
@@ -4,7 +4,7 @@ import * as React from 'react'
import { _isRouteDeparting } from '@tanstack/router-core'
import type { AnyRoute, AnyRouter, ParsedLocation } from '@tanstack/router-core'
-declare module '@tanstack/router-core' {
+declare module '@tanstack/router-core/extensions' {
// Declaration merging requires the original type parameters.
// eslint-disable-next-line unused-imports/no-unused-vars
interface RouterStores {
diff --git a/packages/react-router/src/route-module-internal.ts b/packages/react-router/src/route-module-internal.ts
new file mode 100644
index 0000000000..3ac86d6306
--- /dev/null
+++ b/packages/react-router/src/route-module-internal.ts
@@ -0,0 +1,6 @@
+// Internal generated/framework wiring; use generated scopes to author modules.
+export * from './routeModule'
+export {
+ mountRouteModule,
+ getRouteModuleId,
+} from '@tanstack/router-core/_internal/route-module'
diff --git a/packages/react-router/src/route.tsx b/packages/react-router/src/route.tsx
index 57dca9ef02..ad7e403db9 100644
--- a/packages/react-router/src/route.tsx
+++ b/packages/react-router/src/route.tsx
@@ -4,6 +4,7 @@ import {
BaseRouteApi,
notFound,
} from '@tanstack/router-core'
+import { getRouteNavigationScope } from '@tanstack/router-core/_internal/route-module'
import React from 'react'
import { useLoaderData } from './useLoaderData'
import { useLoaderDeps } from './useLoaderDeps'
@@ -24,6 +25,7 @@ import type {
NotFoundRouteProps,
Register,
RegisteredRouter,
+ RegisteredRouterOf,
ResolveFullPath,
ResolveId,
ResolveParams,
@@ -48,7 +50,7 @@ import type { UseSearchRoute } from './useSearch'
import type { UseRouteContextRoute } from './useRouteContext'
import type { LinkComponentRoute } from './link'
-declare module '@tanstack/router-core' {
+declare module '@tanstack/router-core/extensions' {
export interface UpdatableRouteOptionsExtensions {
component?: RouteComponent
errorComponent?: false | null | undefined | ErrorRouteComponent
@@ -67,18 +69,31 @@ declare module '@tanstack/router-core' {
export interface RouteExtensions<
in out TId extends string,
in out TFullPath extends string,
+ in out TRegister,
> {
- useMatch: UseMatchRoute
- useRouteContext: UseRouteContextRoute
- useSearch: UseSearchRoute
- useParams: UseParamsRoute
- useLoaderDeps: UseLoaderDepsRoute
- useLoaderData: UseLoaderDataRoute
- useNavigate: () => UseNavigateResult
- Link: LinkComponentRoute
+ useMatch: UseMatchRoute
+ useRouteContext: UseRouteContextRoute
+ useSearch: UseSearchRoute
+ useParams: UseParamsRoute
+ useLoaderDeps: UseLoaderDepsRoute
+ useLoaderData: UseLoaderDataRoute
+ useNavigate: () => UseNavigateResult
+ Link: LinkComponentRoute
}
}
+/**
+ * The signature of `getRouteApi`, typed against the router of `TDefaultRegister` unless a
+ * router type is passed explicitly. Route modules export a `getRouteApi` of
+ * this type.
+ */
+export type GetRouteApiFn = <
+ const TId,
+ TRouter extends AnyRouter = RegisteredRouterOf,
+>(
+ id: ConstrainLiteral>,
+) => RouteApi
+
/**
* Returns a route-specific API that exposes type-safe hooks pre-bound
* to a single route ID. Useful for consuming a route's APIs from files
@@ -106,49 +121,64 @@ export class RouteApi<
super({ id })
}
- useMatch: UseMatchRoute = (opts) => {
+ useMatch: UseMatchRoute = (opts) => {
return useMatch({ ...opts, from: this.id } as any) as any
}
- useRouteContext: UseRouteContextRoute = (opts) => {
+ useRouteContext: UseRouteContextRoute = (opts) => {
return useRouteContext({ ...(opts as any), from: this.id })
}
- useSearch: UseSearchRoute = (opts) => {
+ useSearch: UseSearchRoute = (opts) => {
return useSearch({ ...opts, from: this.id } as any)
}
- useParams: UseParamsRoute = (opts) => {
+ useParams: UseParamsRoute = (opts) => {
return useParams({ ...opts, from: this.id } as any)
}
- useLoaderDeps: UseLoaderDepsRoute = (opts) => {
+ useLoaderDeps: UseLoaderDepsRoute = (opts) => {
return useLoaderDeps({ ...opts, from: this.id, strict: false } as any)
}
- useLoaderData: UseLoaderDataRoute = (opts) => {
+ useLoaderData: UseLoaderDataRoute = (opts) => {
return useLoaderData({ ...opts, from: this.id, strict: false } as any)
}
useNavigate = (): UseNavigateResult<
- RouteTypesById['fullPath']
+ RouteTypesById['fullPath'],
+ { router: TRouter }
> => {
const router = useRouter()
- return useNavigate({ from: router.routesById[this.id as string].fullPath })
+ return useNavigate(
+ getRouteNavigationScope(
+ this.id as string,
+ router.routesById[this.id as string]?.fullPath,
+ ) as any,
+ ) as any
}
notFound = (opts?: NotFoundError) => {
return notFound({ routeId: this.id as string, ...opts })
}
- Link: LinkComponentRoute['fullPath']> =
- React.forwardRef((props, ref: React.ForwardedRef) => {
- const router = useRouter()
- const fullPath = router.routesById[this.id as string].fullPath
- return
- }) as unknown as LinkComponentRoute<
- RouteTypesById['fullPath']
- >
+ Link: LinkComponentRoute<
+ RouteTypesById['fullPath'],
+ { router: TRouter }
+ > = React.forwardRef((props, ref: React.ForwardedRef) => {
+ const router = useRouter()
+ const fullPath = router.routesById[this.id as string]?.fullPath
+ return (
+
+ )
+ }) as unknown as LinkComponentRoute<
+ RouteTypesById['fullPath'],
+ { router: TRouter }
+ >
}
export class Route<
@@ -246,39 +276,47 @@ export class Route<
super(options)
}
- useMatch: UseMatchRoute = (opts) => {
+ useMatch: UseMatchRoute = (opts) => {
return useMatch({ ...opts, from: this.id } as any) as any
}
- useRouteContext: UseRouteContextRoute = (opts?) => {
+ useRouteContext: UseRouteContextRoute = (opts?) => {
return useRouteContext({ ...(opts as any), from: this.id })
}
- useSearch: UseSearchRoute = (opts) => {
+ useSearch: UseSearchRoute = (opts) => {
return useSearch({ ...opts, from: this.id } as any)
}
- useParams: UseParamsRoute = (opts) => {
+ useParams: UseParamsRoute = (opts) => {
return useParams({ ...opts, from: this.id } as any)
}
- useLoaderDeps: UseLoaderDepsRoute = (opts) => {
+ useLoaderDeps: UseLoaderDepsRoute = (opts) => {
return useLoaderDeps({ ...opts, from: this.id } as any)
}
- useLoaderData: UseLoaderDataRoute = (opts) => {
+ useLoaderData: UseLoaderDataRoute = (opts) => {
return useLoaderData({ ...opts, from: this.id } as any)
}
- useNavigate = (): UseNavigateResult => {
- return useNavigate({ from: this.fullPath })
+ useNavigate = (): UseNavigateResult => {
+ return useNavigate(
+ getRouteNavigationScope(this.id, this.fullPath) as any,
+ ) as any
}
- Link: LinkComponentRoute = React.forwardRef(
+ Link: LinkComponentRoute = React.forwardRef(
(props, ref: React.ForwardedRef) => {
- return
+ return (
+
+ )
},
- ) as unknown as LinkComponentRoute
+ ) as unknown as LinkComponentRoute
}
/**
@@ -503,39 +541,39 @@ export class RootRoute<
super(options)
}
- useMatch: UseMatchRoute = (opts) => {
+ useMatch: UseMatchRoute = (opts) => {
return useMatch({ ...opts, from: this.id } as any) as any
}
- useRouteContext: UseRouteContextRoute = (opts) => {
+ useRouteContext: UseRouteContextRoute = (opts) => {
return useRouteContext({ ...(opts as any), from: this.id })
}
- useSearch: UseSearchRoute = (opts) => {
+ useSearch: UseSearchRoute = (opts) => {
return useSearch({ ...opts, from: this.id } as any)
}
- useParams: UseParamsRoute = (opts) => {
+ useParams: UseParamsRoute = (opts) => {
return useParams({ ...opts, from: this.id } as any)
}
- useLoaderDeps: UseLoaderDepsRoute = (opts) => {
+ useLoaderDeps: UseLoaderDepsRoute = (opts) => {
return useLoaderDeps({ ...opts, from: this.id } as any)
}
- useLoaderData: UseLoaderDataRoute = (opts) => {
+ useLoaderData: UseLoaderDataRoute = (opts) => {
return useLoaderData({ ...opts, from: this.id } as any)
}
- useNavigate = (): UseNavigateResult<'/'> => {
- return useNavigate({ from: this.fullPath })
+ useNavigate = (): UseNavigateResult<'/', TRegister> => {
+ return useNavigate({ from: this.fullPath }) as any
}
- Link: LinkComponentRoute<'/'> = React.forwardRef(
+ Link: LinkComponentRoute<'/', TRegister> = React.forwardRef(
(props, ref: React.ForwardedRef) => {
return
},
- ) as unknown as LinkComponentRoute<'/'>
+ ) as unknown as LinkComponentRoute<'/', TRegister>
}
/**
diff --git a/packages/react-router/src/routeModule.tsx b/packages/react-router/src/routeModule.tsx
new file mode 100644
index 0000000000..c5bca7aa76
--- /dev/null
+++ b/packages/react-router/src/routeModule.tsx
@@ -0,0 +1,441 @@
+import * as React from 'react'
+import { notFound } from '@tanstack/router-core'
+import {
+ bindRouteScopeOptions,
+ createScopedRedirect,
+ getInstallationRouteIdMapper,
+ getScopedRouterView,
+} from '@tanstack/router-core/_internal/route-module'
+import { Route, getRouteApi } from './route'
+import { Link, useLinkProps } from './link'
+import { useBlocker } from './useBlocker'
+import { Navigate, useNavigate } from './useNavigate'
+import {
+ MatchRoute,
+ useChildMatches,
+ useMatchRoute,
+ useMatches,
+ useParentMatches,
+} from './Matches'
+import { useRouter } from './useRouter'
+import { matchContext } from './matchContext'
+import { useMatch } from './useMatch'
+import { useLoaderData } from './useLoaderData'
+import { useLoaderDeps } from './useLoaderDeps'
+import { useSearch } from './useSearch'
+import { useParams } from './useParams'
+import { useRouteContext } from './useRouteContext'
+import { useLocation } from './useLocation'
+import { useRouterState } from './useRouterState'
+import type { UseBlockerFn } from './useBlocker'
+import type {
+ AnyContext,
+ AnyRoute,
+ AnyRouter,
+ ModuleRootRoute,
+ ModuleRootRouteOptions,
+ NotFoundError,
+ RedirectFn,
+ RouteIds,
+ ScopedRouterView,
+} from '@tanstack/router-core'
+import type { FileRouteFactory } from './fileRoute'
+import type { GetRouteApiFn } from './route'
+import type {
+ CreateLinkFn,
+ LinkComponent,
+ LinkOptionsFn,
+ UseLinkPropsFn,
+} from './link'
+import type { NavigateComponentFn, UseNavigateFn } from './useNavigate'
+import type {
+ MatchRouteFn,
+ UseChildMatchesFn,
+ UseMatchRouteFn,
+ UseMatchesFn,
+ UseParentMatchesFn,
+} from './Matches'
+import type { UseMatchFn } from './useMatch'
+import type { UseLoaderDataFn } from './useLoaderData'
+import type { UseLoaderDepsFn } from './useLoaderDeps'
+import type { UseSearchFn } from './useSearch'
+import type { UseParamsFn } from './useParams'
+import type { UseRouteContextFn } from './useRouteContext'
+import type { UseLocationFn } from './useLocation'
+import type { UseRouterStateFn } from './useRouterState'
+
+/** An entry of a generated module-local `FileRoutesByPath` interface. */
+export interface FileRoutesByPathEntry {
+ id: string
+ path: string
+ fullPath: string
+ parentRoute: AnyRoute
+}
+
+// Entries reference the route files, whose types depend on these factories:
+// read one property at a time and never constrain or check whole entries.
+type FileRouteEntry =
+ TFileRoutesByPath[TFilePath & keyof TFileRoutesByPath]
+type FileRouteParent =
+ FileRouteEntry extends {
+ parentRoute: infer TParentRoute extends AnyRoute
+ }
+ ? TParentRoute
+ : never
+type FileRouteId =
+ FileRouteEntry extends {
+ id: infer TId extends string
+ }
+ ? TId
+ : never
+type FileRoutePath =
+ FileRouteEntry extends {
+ path: infer TPath extends string
+ }
+ ? TPath
+ : never
+type FileRouteFullPath =
+ FileRouteEntry extends {
+ fullPath: infer TFullPath extends string
+ }
+ ? TFullPath
+ : never
+
+/**
+ * Route factories of a route module, typed against the module's generated
+ * `FileRoutesByPath` and its scope register instead of the application's
+ * global registrations.
+ */
+export interface FileRouteScope<
+ TFileRoutesByPath,
+ TRegister,
+ TModuleId extends string,
+> {
+ /** `createFileRoute`, typed against the module's own route files. */
+ createFileRoute: (
+ path?: TFilePath,
+ ) => FileRouteFactory<
+ FileRouteId,
+ FileRouteParent,
+ FileRouteId,
+ FileRoutePath,
+ FileRouteFullPath,
+ TRegister
+ >
+ /**
+ * Creates the module root. `TRouterContext` is the router context the module
+ * requires from the route it is mounted under.
+ */
+ createModuleRoot: () => <
+ TRouteContextFn = AnyContext,
+ TBeforeLoadFn = AnyContext,
+ TSearchValidator = undefined,
+ TLoaderDeps extends Record = {},
+ TLoaderFn = undefined,
+ TSSR = unknown,
+ const TServerMiddlewares = unknown,
+ THandlers = undefined,
+ >(
+ options?: ModuleRootRouteOptions<
+ TModuleId,
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TSSR,
+ TServerMiddlewares,
+ THandlers
+ >,
+ ) => ModuleRootRoute<
+ TModuleId,
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ unknown,
+ unknown,
+ TSSR,
+ TServerMiddlewares,
+ THandlers
+ >
+}
+
+/** Binds only the module-root factory used by generated route scopes. */
+export function bindCreateModuleRoot(
+ moduleId: TModuleId,
+): FileRouteScope['createModuleRoot'] {
+ return () => (options) =>
+ new Route({ ...(options as any), _module: moduleId }) as any
+}
+
+/**
+ * The routing APIs of a route scope, typed against `TRouter`.
+ *
+ * Path-based APIs (`Link`, `useNavigate`, `redirect`, ...) address routes by
+ * the module-local paths of the module: they work wherever the module is
+ * mounted. Id-based APIs (`useMatch`, `getRouteApi`, ...) take qualified route
+ * ids such as `@acme/products:/$productId`.
+ */
+export interface RouteScope {
+ Link: LinkComponent<'a', string, { router: TRouter }>
+ createLink: CreateLinkFn<{ router: TRouter }>
+ linkOptions: LinkOptionsFn<'a', { router: TRouter }>
+ Navigate: NavigateComponentFn<{ router: TRouter }>
+ useNavigate: UseNavigateFn<{ router: TRouter }>
+ useLinkProps: UseLinkPropsFn<{ router: TRouter }>
+ useBlocker: UseBlockerFn<{ router: TRouter }>
+ notFound: (
+ options?: Omit & {
+ routeId?: RouteIds
+ },
+ ) => NotFoundError
+ redirect: RedirectFn<{ router: TRouter }>
+ MatchRoute: MatchRouteFn<{ router: TRouter }>
+ useMatchRoute: UseMatchRouteFn<{ router: TRouter }>
+ /**
+ * The router, viewed from the module: its `navigate`, `buildLocation`,
+ * `preloadRoute` and `matchRoute` take module-local paths.
+ */
+ useRouter: (opts?: { warn?: boolean }) => ScopedRouterView
+ getRouteApi: GetRouteApiFn<{ router: TRouter }>
+ useMatch: UseMatchFn<{ router: TRouter }>
+ useMatches: UseMatchesFn<{ router: TRouter }>
+ useParentMatches: UseParentMatchesFn<{ router: TRouter }>
+ useChildMatches: UseChildMatchesFn<{ router: TRouter }>
+ useLoaderData: UseLoaderDataFn<{ router: TRouter }>
+ useLoaderDeps: UseLoaderDepsFn<{ router: TRouter }>
+ useSearch: UseSearchFn<{ router: TRouter }>
+ useParams: UseParamsFn<{ router: TRouter }>
+ useRouteContext: UseRouteContextFn<{ router: TRouter }>
+ useLocation: UseLocationFn<{ router: TRouter }>
+ useRouterState: UseRouterStateFn<{ router: TRouter }>
+}
+
+// Each generated ESM export binds only its own API. These functions allocate
+// closures/components; they never access a router or register runtime state.
+function useBoundOptions(moduleId: string): (options: any) => any {
+ const router = useRouter()
+ const routeId = React.useContext(matchContext)
+ return React.useCallback(
+ (options: any) =>
+ bindRouteScopeOptions(moduleId, options ?? {}, router, routeId),
+ [moduleId, router, routeId],
+ )
+}
+
+function bindIdHook(moduleId: string, hook: (options: any) => any) {
+ const toInstallation = getInstallationRouteIdMapper(moduleId)
+ return toInstallation
+ ? (options?: { from?: string }) =>
+ hook({ ...options, from: toInstallation(options?.from) })
+ : hook
+}
+
+export function bindRouteScopeLink(
+ moduleId: string,
+): RouteScope['Link'] {
+ const AnyLink = Link as React.ComponentType
+ return React.forwardRef((props, ref) => {
+ const bind = useBoundOptions(moduleId)
+ return
+ }) as any
+}
+
+export function bindRouteScopeCreateLink(
+ moduleId: string,
+): RouteScope['createLink'] {
+ const AnyLink = Link as React.ComponentType
+ return ((Comp: unknown) =>
+ React.forwardRef((props, ref) => {
+ const bind = useBoundOptions(moduleId)
+ return
+ })) as any
+}
+
+export function bindRouteScopeNavigate(
+ moduleId: string,
+): RouteScope['Navigate'] {
+ const AnyNavigate = Navigate as React.ComponentType
+ return function ScopedNavigate(props: object) {
+ const bind = useBoundOptions(moduleId)
+ return
+ } as any
+}
+
+export function bindRouteScopeMatchRoute(
+ moduleId: string,
+): RouteScope['MatchRoute'] {
+ const AnyMatchRoute = MatchRoute as React.ComponentType
+ return function ScopedMatchRoute(props: object) {
+ const bind = useBoundOptions(moduleId)
+ const routeId = React.useContext(matchContext)
+ return
+ } as any
+}
+
+export function bindRouteScopeUseLinkProps(
+ moduleId: string,
+): RouteScope['useLinkProps'] {
+ return function useScopedLinkProps(
+ options: any,
+ ref: React.ForwardedRef,
+ ) {
+ return useLinkProps(useBoundOptions(moduleId)(options), ref)
+ } as any
+}
+
+export function bindRouteScopeLinkOptions(
+ moduleId: string,
+): RouteScope['linkOptions'] {
+ return ((options: any) =>
+ Array.isArray(options)
+ ? options.map((option) => bindRouteScopeOptions(moduleId, option))
+ : bindRouteScopeOptions(moduleId, options)) as any
+}
+
+export function bindRouteScopeUseNavigate(
+ moduleId: string,
+): RouteScope['useNavigate'] {
+ return function useScopedNavigate(options?: any) {
+ const bind = useBoundOptions(moduleId)
+ const navigate = useNavigate(bind(options))
+ return React.useCallback(
+ (next: any) => navigate(bind(next)),
+ [navigate, bind],
+ )
+ } as any
+}
+
+export function bindRouteScopeRedirect(
+ moduleId: string,
+): RouteScope['redirect'] {
+ return createScopedRedirect(moduleId)
+}
+
+export function bindRouteScopeUseMatchRoute(
+ moduleId: string,
+): RouteScope['useMatchRoute'] {
+ return function useScopedMatchRoute() {
+ const bind = useBoundOptions(moduleId)
+ const matchRoute = useMatchRoute()
+ const routeId = React.useContext(matchContext)
+ return React.useCallback(
+ (options: any) =>
+ matchRoute({ ...bind(options), _nearestRoute: routeId }),
+ [matchRoute, bind, routeId],
+ )
+ } as any
+}
+
+export function bindRouteScopeUseRouter(
+ moduleId: string,
+): RouteScope['useRouter'] {
+ return function useScopedRouter(options?: { warn?: boolean }) {
+ return getScopedRouterView(
+ useRouter(options),
+ moduleId,
+ React.useContext(matchContext),
+ )
+ } as any
+}
+
+export function bindRouteScopeGetRouteApi(
+ moduleId: string,
+): RouteScope['getRouteApi'] {
+ const toInstallation = getInstallationRouteIdMapper(moduleId)
+ return (
+ toInstallation
+ ? (id: string) => getRouteApi(toInstallation(id) as never)
+ : getRouteApi
+ ) as any
+}
+
+export function bindRouteScopeUseMatch(
+ moduleId: string,
+): RouteScope