From 8f771f5643a58b8abf17e25d63046e396e48f6f6 Mon Sep 17 00:00:00 2001 From: Tom Beckenham <34339192+tombeckenham@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:19:38 +1100 Subject: [PATCH 1/3] perf(start): dispatch server-only routes without constructing a Router The Start Vite plugin emits a server-only route tree (routes whose only file-route option is `server`, with `__root` swapped for a bare root). `createStartHandler` matches exact server-route requests against it on the raw pathname before touching the router entry, which now loads lazily on the first request that needs a Router. Misses, pages, methods without a handler and server functions take the existing path. The plugin exports `undefined` with a build warning when the root route defines `server` options or a server-only param route would shadow a page, so those apps keep the Router path. Router-level `caseSensitive` and `rewrite` are not applied on a fast-path hit; documented in the server routes guide. Rsbuild does not build the tree yet. Adds the `server-routes-matrix` SSR benchmark: one Start app and a Hono reference on the same route table across static, param, nested middleware, 200-route, page and 404 shapes. Claude-Session: https://claude.ai/code/session_01UFnjmy4rGstaARGzeUapga --- .changeset/server-route-fast-path.md | 11 + benchmarks/ssr/README.md | 35 +- benchmarks/ssr/package.json | 5 +- .../scenarios/server-routes-matrix/bench.ts | 200 ++++++++++ .../scenarios/server-routes-matrix/hono.ts | 35 ++ .../server-routes-matrix/react/.gitignore | 3 + .../react/gen-many-routes.mjs | 20 + .../server-routes-matrix/react/project.json | 32 ++ .../react/speed.api-miss.bench.ts | 6 + .../react/speed.many-routes.bench.ts | 6 + .../react/speed.nested-middleware.bench.ts | 6 + .../react/speed.page-fallback.bench.ts | 6 + .../react/speed.param.bench.ts | 6 + .../react/speed.static.bench.ts | 6 + .../react/src/middleware.ts | 6 + .../server-routes-matrix/react/src/router.tsx | 16 + .../react/src/routes/__root.tsx | 24 ++ .../react/src/routes/api.admin.$id.ts | 19 + .../react/src/routes/api.admin.ts | 9 + .../react/src/routes/api.health.ts | 9 + .../react/src/routes/api.users.$id.ts | 14 + .../react/src/routes/index.tsx | 9 + .../server-routes-matrix/react/src/server.ts | 6 + .../server-routes-matrix/react/tsconfig.json | 17 + .../server-routes-matrix/react/vite.config.ts | 32 ++ .../framework/react/guide/server-routes.md | 11 + packages/router-core/src/index.ts | 2 + .../src/vite/start-router-plugin/plugin.ts | 188 ++++++++++ .../tests/api-route-tree-dev.test.ts | 155 ++++++++ packages/start-server-core/package.json | 3 + .../src/createStartHandler.ts | 354 +++++++++++++----- .../src/empty-api-route-tree.ts | 5 + .../start-server-core/src/tanstack-start.d.ts | 7 + .../start-server-core/src/virtual-modules.ts | 2 + .../server-route-fast-path-basepath.test.ts | 81 ++++ .../tests/server-route-fast-path.test.ts | 318 ++++++++++++++++ packages/start-server-core/vite.config.ts | 6 + pnpm-lock.yaml | 30 +- 38 files changed, 1563 insertions(+), 137 deletions(-) create mode 100644 .changeset/server-route-fast-path.md create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/bench.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/hono.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/.gitignore create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/gen-many-routes.mjs create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/project.json create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/speed.api-miss.bench.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/speed.many-routes.bench.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/speed.nested-middleware.bench.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/speed.page-fallback.bench.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/speed.param.bench.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/speed.static.bench.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/middleware.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/router.tsx create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/__root.tsx create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.admin.$id.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.admin.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.health.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.users.$id.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/index.tsx create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/src/server.ts create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/tsconfig.json create mode 100644 benchmarks/ssr/scenarios/server-routes-matrix/react/vite.config.ts create mode 100644 packages/start-plugin-core/tests/api-route-tree-dev.test.ts create mode 100644 packages/start-server-core/src/empty-api-route-tree.ts create mode 100644 packages/start-server-core/tests/server-route-fast-path-basepath.test.ts create mode 100644 packages/start-server-core/tests/server-route-fast-path.test.ts diff --git a/.changeset/server-route-fast-path.md b/.changeset/server-route-fast-path.md new file mode 100644 index 00000000000..9cbc49750f5 --- /dev/null +++ b/.changeset/server-route-fast-path.md @@ -0,0 +1,11 @@ +--- +'@tanstack/start-server-core': minor +'@tanstack/start-plugin-core': minor +'@tanstack/router-core': minor +--- + +perf(start): dispatch server-only routes without constructing a Router. The Start plugin builds a server-only route tree, and `createStartHandler` matches exact server-route requests against it before touching the router entry, which now loads lazily. Apps whose root route defines `server` options, or where a server-only param route would shadow a page, keep the Router path with a build warning. + +Router-level `caseSensitive` and `rewrite` options are not applied to a request served from the server-only tree; route-level `caseSensitive` is. Only the Vite plugin builds the tree, so Rsbuild apps keep the Router path. + +`@tanstack/router-core` now exports `processRouteTree`, `findRouteMatch` and the `ProcessRouteTreeResult` type. diff --git a/benchmarks/ssr/README.md b/benchmarks/ssr/README.md index 3d90af15985..365349fd53c 100644 --- a/benchmarks/ssr/README.md +++ b/benchmarks/ssr/README.md @@ -35,23 +35,24 @@ Each scenario uses one app per framework instead of sharing routes in the baseli Each scenario isolates one Start server-side responsibility so benchmark changes can be attributed to a specific feature area. -| Scenario | Start server-side responsibility | -| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `react/`, `solid/`, `vue/` baseline apps | Document SSR for nested file routes, route matching, search parsing, and full-page HTML response generation. | -| `assets` | Per-request asset pipeline work: CSS inlining, CDN asset URL transforms with uncached manifest resolution, and response `Link` header collection for early hints. | -| `before-load` | Nested `beforeLoad` execution: sequential per-match context building, context merging across matches, and context consumption by loaders during document SSR. | -| `control-flow` | Loader-thrown `redirect`, `notFound`, plain errors, unmatched routes, and route `headers()` emission, including HTTP status selection, redirect `location` headers, route error boundaries, and not-found HTML rendering. | -| `global-middleware` | Global `createStart` middleware registration: request middleware wrapping document SSR, server-function, and server-route requests, plus global function middleware on server functions. | -| `head` | Nested route `head` evaluation, title/meta/link serialization, and head-entry deduplication during SSR. | -| `loaders` | Nested route loader execution, loader deps from search params, router context reads, and dehydrated loader payload generation. | -| `rewrites` | Composed location rewrites from router `basepath` plus locale input/output rewrites; unprefixed URLs redirect to `/app/*` when the basepath output rewrite canonicalizes them. | -| `serialization` | Dehydration and RPC serialization of rich non-plain-JSON types: seroval native types in loader payloads, custom serialization adapters, and shallow-error serialization. | -| `selective-ssr` | Route-level `ssr` modes: rendered server HTML with `ssr: true`, dehydrated data without HTML with `ssr: 'data-only'`, and client-only omission with `ssr: false`. | -| `server-fn-transport` | Non-JSON server-function transport: multipart/FormData request decoding, raw `Response` returns, and `RawStream` streamed responses through the binary frame protocol. | -| `server-fns` | `createServerFn` GET/POST request handling, thrown redirect/notFound results, sendContext serialization, SSR-time direct calls, middleware context, input validation, and URL discovery. | -| `server-routes` | File route `server.handlers` dispatch for parameterized JSON API routes without document HTML rendering. | -| `server-routes-middleware` | Server route request middleware chains, middleware-provided context merging, and handler access to accumulated context. | -| `streaming` | Deferred loader data, `Await`/Suspense fallback output, larger streamed HTML body scanning, streamed HTML ordering, and later dehydration payload emission. | +| Scenario | Start server-side responsibility | +| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `react/`, `solid/`, `vue/` baseline apps | Document SSR for nested file routes, route matching, search parsing, and full-page HTML response generation. | +| `assets` | Per-request asset pipeline work: CSS inlining, CDN asset URL transforms with uncached manifest resolution, and response `Link` header collection for early hints. | +| `before-load` | Nested `beforeLoad` execution: sequential per-match context building, context merging across matches, and context consumption by loaders during document SSR. | +| `control-flow` | Loader-thrown `redirect`, `notFound`, plain errors, unmatched routes, and route `headers()` emission, including HTTP status selection, redirect `location` headers, route error boundaries, and not-found HTML rendering. | +| `global-middleware` | Global `createStart` middleware registration: request middleware wrapping document SSR, server-function, and server-route requests, plus global function middleware on server functions. | +| `head` | Nested route `head` evaluation, title/meta/link serialization, and head-entry deduplication during SSR. | +| `loaders` | Nested route loader execution, loader deps from search params, router context reads, and dehydrated loader payload generation. | +| `rewrites` | Composed location rewrites from router `basepath` plus locale input/output rewrites; unprefixed URLs redirect to `/app/*` when the basepath output rewrite canonicalizes them. | +| `serialization` | Dehydration and RPC serialization of rich non-plain-JSON types: seroval native types in loader payloads, custom serialization adapters, and shallow-error serialization. | +| `selective-ssr` | Route-level `ssr` modes: rendered server HTML with `ssr: true`, dehydrated data without HTML with `ssr: 'data-only'`, and client-only omission with `ssr: false`. | +| `server-fn-transport` | Non-JSON server-function transport: multipart/FormData request decoding, raw `Response` returns, and `RawStream` streamed responses through the binary frame protocol. | +| `server-fns` | `createServerFn` GET/POST request handling, thrown redirect/notFound results, sendContext serialization, SSR-time direct calls, middleware context, input validation, and URL discovery. | +| `server-routes` | File route `server.handlers` dispatch for parameterized JSON API routes without document HTML rendering. | +| `server-routes-middleware` | Server route request middleware chains, middleware-provided context merging, and handler access to accumulated context. | +| `server-routes-matrix` | One app, two handlers: Start (server-only routes dispatch from the prebuilt API tree without a Router) and a Hono reference with the same route table. Shapes: static, param, nested middleware, 200-route tree, page request, 404 under /api (react only). | +| `streaming` | Deferred loader data, `Await`/Suspense fallback output, larger streamed HTML body scanning, streamed HTML ordering, and later dehydration payload emission. | ## Run diff --git a/benchmarks/ssr/package.json b/benchmarks/ssr/package.json index 20c18374680..6668fb36f4a 100644 --- a/benchmarks/ssr/package.json +++ b/benchmarks/ssr/package.json @@ -25,7 +25,8 @@ "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "catalog:" + "vitest": "catalog:", + "hono": "^4.7.10" }, "nx": { "targets": { @@ -48,6 +49,7 @@ "@benchmarks/ssr-server-fn-transport-react", "@benchmarks/ssr-server-fns-react", "@benchmarks/ssr-server-routes-react", + "@benchmarks/ssr-server-routes-matrix-react", "@benchmarks/ssr-server-routes-middleware-react", "@benchmarks/ssr-streaming-react" ], @@ -182,6 +184,7 @@ "@benchmarks/ssr-server-fn-transport-react", "@benchmarks/ssr-server-fns-react", "@benchmarks/ssr-server-routes-react", + "@benchmarks/ssr-server-routes-matrix-react", "@benchmarks/ssr-server-routes-middleware-react", "@benchmarks/ssr-streaming-react", "@benchmarks/ssr-solid", diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/bench.ts b/benchmarks/ssr/scenarios/server-routes-matrix/bench.ts new file mode 100644 index 00000000000..2579606fbf9 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/bench.ts @@ -0,0 +1,200 @@ +import { test } from 'vitest' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import { MANY_ROUTE_COUNT, honoApp } from './hono' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const concurrency = 16 + +const jsonRequestInit = { + method: 'GET', + headers: { accept: 'application/json' }, +} satisfies RequestInit + +const htmlRequestInit = { + method: 'GET', + headers: { accept: 'text/html' }, +} satisfies RequestInit + +interface Shape { + totalRequests: number + /** Page shapes skip Hono, which has no page to render. */ + fallback: boolean + options: { warmupIterations: number; time: number; throws: true } + buildRequest: (random: () => number) => Request + /** Defaults to requiring status 200. */ + validateResponse?: (response: Response, request: Request) => void + assert: (handler: StartRequestHandler) => Promise +} + +const fallbackOptions = { + warmupIterations: 10, + time: 10_000, + throws: true, +} as const + +async function expectHtml( + handler: StartRequestHandler, + path: string, + status: number, + marker: string, +) { + const response = await handler.fetch( + new Request(`http://localhost${path}`, htmlRequestInit), + ) + const html = await response.text() + if (response.status !== status || !html.includes(marker)) { + throw new Error( + `${path}: expected ${status} with "${marker}", received ${response.status}`, + ) + } +} + +const jsonOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} as const + +async function expectJson( + handler: StartRequestHandler, + path: string, + expected: Record, +) { + const response = await handler.fetch( + new Request(`http://localhost${path}`, jsonRequestInit), + ) + if (response.status !== 200) { + throw new Error(`${path}: expected 200, received ${response.status}`) + } + const body = (await response.json()) as Record + for (const [key, value] of Object.entries(expected)) { + if (body[key] !== value) { + throw new Error( + `${path}: expected ${key}=${value}, received ${body[key]}`, + ) + } + } +} + +export const shapes = { + // Exact static match, hits the matcher cache every time. + static: { + totalRequests: 208, + fallback: false, + options: jsonOptions, + buildRequest: () => + new Request('http://localhost/api/health', jsonRequestInit), + assert: (handler) => expectJson(handler, '/api/health', { ok: true }), + }, + // Same route as the upstream `server-routes` scenario: a fresh param each + // request, so the matcher cache misses every time. + param: { + totalRequests: 208, + fallback: false, + options: jsonOptions, + buildRequest: (random) => + new Request( + `http://localhost/api/users/${randomSegment(random)}`, + jsonRequestInit, + ), + assert: (handler) => + expectJson(handler, '/api/users/sanity', { name: 'user-sanity' }), + }, + // Three request middlewares up the branch: layout, route, handler. + 'nested-middleware': { + totalRequests: 208, + fallback: false, + options: jsonOptions, + buildRequest: (random) => + new Request( + `http://localhost/api/admin/${randomSegment(random)}`, + jsonRequestInit, + ), + assert: (handler) => + expectJson(handler, '/api/admin/sanity', { id: 'sanity', total: 6 }), + }, + // 200 static siblings, requests spread across all of them. + 'many-routes': { + totalRequests: 208, + fallback: false, + options: jsonOptions, + buildRequest: (random) => + new Request( + `http://localhost/api/many/r${Math.floor(random() * MANY_ROUTE_COUNT)}`, + jsonRequestInit, + ), + assert: (handler) => + expectJson(handler, `/api/many/r${MANY_ROUTE_COUNT - 1}`, { + n: MANY_ROUTE_COUNT - 1, + }), + }, + // A page request: the server-route fast path must miss at no extra cost. + 'page-fallback': { + totalRequests: 48, + fallback: true, + options: fallbackOptions, + buildRequest: () => new Request('http://localhost/', htmlRequestInit), + assert: (handler) => expectHtml(handler, '/', 200, 'server routes matrix'), + }, + // An unknown path under /api: the fast path misses, then the Router + // renders its 404 page. The worst case for the miss. + 'api-miss': { + totalRequests: 48, + fallback: true, + options: fallbackOptions, + buildRequest: () => + new Request('http://localhost/api/does-not-exist', htmlRequestInit), + validateResponse: (response, request) => { + if (response.status !== 404) { + throw new Error( + `Expected 404, received ${response.status} (${request.url})`, + ) + } + }, + assert: (handler) => + expectHtml(handler, '/api/does-not-exist', 404, 'Not Found'), + }, +} satisfies Record + +export type ShapeName = keyof typeof shapes + +export function runShapeLoop(handler: StartRequestHandler, shape: Shape) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency, + totalRequests: shape.totalRequests, + buildRequest: shape.buildRequest, + validateResponse: shape.validateResponse, + }) +} + +/** + * Registers one benchmark per handler for a shape: the built Start app and, + * for API shapes, a Hono reference serving the same route table. + */ +export async function defineShapeBenches( + shapeName: ShapeName, + appModuleUrl: string, +) { + const shape: Shape = shapes[shapeName] + const app = (await import(/* @vite-ignore */ appModuleUrl)) as { + default: StartRequestHandler + } + const handlers: Array<[label: string, handler: StartRequestHandler]> = [ + ['start (react)', app.default], + ] + if (!shape.fallback) { + handlers.push(['hono', honoApp]) + } + for (const [label, handler] of handlers) { + await shape.assert(handler) + test(label, async ({ bench }) => { + await bench(`ssr server-route ${shapeName} ${label}`, async () => + runShapeLoop(handler, shape), + ).run(shape.options) + }) + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/hono.ts b/benchmarks/ssr/scenarios/server-routes-matrix/hono.ts new file mode 100644 index 00000000000..bb13dbf3b02 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/hono.ts @@ -0,0 +1,35 @@ +import { Hono } from 'hono' +import { createMiddleware } from 'hono/factory' + +/** Static routes under /api/many/r{n}; keep in sync with gen-many-routes.mjs. */ +export const MANY_ROUTE_COUNT = 200 + +/** Reference point: the same route table on Hono, with no Start involved. */ +type Env = { Variables: { a: number; b: number; c: number } } + +const set = (key: keyof Env['Variables'], value: number) => + createMiddleware(async (c, next) => { + c.set(key, value) + await next() + }) + +export const honoApp = new Hono() + +honoApp.get('/api/health', (c) => c.json({ ok: true })) + +honoApp.get('/api/users/:id', (c) => { + const id = c.req.param('id') + return c.json({ id, name: `user-${id}`, roles: ['a', 'b', 'c'] }) +}) + +honoApp.use('/api/admin/*', set('a', 1), set('b', 2), set('c', 3)) +honoApp.get('/api/admin/:id', (c) => + c.json({ + id: c.req.param('id'), + total: c.get('a') + c.get('b') + c.get('c'), + }), +) + +for (let n = 0; n < MANY_ROUTE_COUNT; n++) { + honoApp.get(`/api/many/r${n}`, (c) => c.json({ n })) +} diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/.gitignore b/benchmarks/ssr/scenarios/server-routes-matrix/react/.gitignore new file mode 100644 index 00000000000..487569c855f --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/.gitignore @@ -0,0 +1,3 @@ +# Generated by gen-many-routes.mjs and the Start build. +src/routes/api/many/ +src/routeTree.gen.ts diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/gen-many-routes.mjs b/benchmarks/ssr/scenarios/server-routes-matrix/react/gen-many-routes.mjs new file mode 100644 index 00000000000..055affc210b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/gen-many-routes.mjs @@ -0,0 +1,20 @@ +// Writes 200 static server-only routes so the matcher is measured on a tree +// of realistic size. Output is gitignored; runs before every build. +import { mkdirSync, writeFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +const MANY_ROUTE_COUNT = 200 // keep in sync with ../hono.ts +const dir = fileURLToPath(new URL('./src/routes/api/many/', import.meta.url)) + +mkdirSync(dir, { recursive: true }) +for (let n = 0; n < MANY_ROUTE_COUNT; n++) { + writeFileSync( + `${dir}r${n}.ts`, + `import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/api/many/r${n}')({ + server: { handlers: { GET: () => Response.json({ n: ${n} }) } }, +}) +`, + ) +} diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/project.json b/benchmarks/ssr/scenarios/server-routes-matrix/react/project.json new file mode 100644 index 00000000000..c7304cbb665 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/project.json @@ -0,0 +1,32 @@ +{ + "name": "@benchmarks/ssr-server-routes-matrix-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "node {projectRoot}/gen-many-routes.mjs && NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + }, + "build:ssr" + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.api-miss.bench.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.api-miss.bench.ts new file mode 100644 index 00000000000..9f5a63fedf4 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.api-miss.bench.ts @@ -0,0 +1,6 @@ +import { defineShapeBenches } from '../bench' + +await defineShapeBenches( + 'api-miss', + new URL('./dist/server/server.js', import.meta.url).href, +) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.many-routes.bench.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.many-routes.bench.ts new file mode 100644 index 00000000000..e5d5b51448c --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.many-routes.bench.ts @@ -0,0 +1,6 @@ +import { defineShapeBenches } from '../bench' + +await defineShapeBenches( + 'many-routes', + new URL('./dist/server/server.js', import.meta.url).href, +) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.nested-middleware.bench.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.nested-middleware.bench.ts new file mode 100644 index 00000000000..c574f14e3af --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.nested-middleware.bench.ts @@ -0,0 +1,6 @@ +import { defineShapeBenches } from '../bench' + +await defineShapeBenches( + 'nested-middleware', + new URL('./dist/server/server.js', import.meta.url).href, +) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.page-fallback.bench.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.page-fallback.bench.ts new file mode 100644 index 00000000000..c6897bc105a --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.page-fallback.bench.ts @@ -0,0 +1,6 @@ +import { defineShapeBenches } from '../bench' + +await defineShapeBenches( + 'page-fallback', + new URL('./dist/server/server.js', import.meta.url).href, +) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.param.bench.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.param.bench.ts new file mode 100644 index 00000000000..edf2dd4385e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.param.bench.ts @@ -0,0 +1,6 @@ +import { defineShapeBenches } from '../bench' + +await defineShapeBenches( + 'param', + new URL('./dist/server/server.js', import.meta.url).href, +) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.static.bench.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.static.bench.ts new file mode 100644 index 00000000000..e4fcc5cbf06 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/speed.static.bench.ts @@ -0,0 +1,6 @@ +import { defineShapeBenches } from '../bench' + +await defineShapeBenches( + 'static', + new URL('./dist/server/server.js', import.meta.url).href, +) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/middleware.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/middleware.ts new file mode 100644 index 00000000000..054e5038de6 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/middleware.ts @@ -0,0 +1,6 @@ +import { createMiddleware } from '@tanstack/react-start' + +export const make = (key: TKey, value: number) => + createMiddleware({ type: 'request' }).server(({ next }) => + next({ context: { [key]: value } as Record }), + ) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/router.tsx b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/router.tsx new file mode 100644 index 00000000000..7c4eb0babe9 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/__root.tsx new file mode 100644 index 00000000000..ff1da4c3046 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.admin.$id.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.admin.$id.ts new file mode 100644 index 00000000000..927eb35c493 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.admin.$id.ts @@ -0,0 +1,19 @@ +import { createFileRoute } from '@tanstack/react-router' +import { make } from '../middleware' + +export const Route = createFileRoute('/api/admin/$id')({ + server: { + middleware: [make('b', 2)], + handlers: ({ createHandlers }) => + createHandlers({ + GET: { + middleware: [make('c', 3)], + handler: ({ params, context }) => + Response.json({ + id: params.id, + total: context.a + context.b + context.c, + }), + }, + }), + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.admin.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.admin.ts new file mode 100644 index 00000000000..bafce2aee2c --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.admin.ts @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' +import { make } from '../middleware' + +// Layout-level middleware: runs for every route under /api/admin. +export const Route = createFileRoute('/api/admin')({ + server: { + middleware: [make('a', 1)], + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.health.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.health.ts new file mode 100644 index 00000000000..0cc3a11139b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.health.ts @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/api/health')({ + server: { + handlers: { + GET: () => Response.json({ ok: true }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.users.$id.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.users.$id.ts new file mode 100644 index 00000000000..b43275a5c6e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/api.users.$id.ts @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/api/users/$id')({ + server: { + handlers: { + GET: ({ params }) => + Response.json({ + id: params.id, + name: `user-${params.id}`, + roles: ['a', 'b', 'c'], + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/index.tsx new file mode 100644 index 00000000000..1870d841626 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return
server routes matrix
+} diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/src/server.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/server.ts new file mode 100644 index 00000000000..1cb18f5dedd --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/src/server.ts @@ -0,0 +1,6 @@ +import { + createStartHandler, + defaultStreamHandler, +} from '@tanstack/react-start/server' + +export default { fetch: createStartHandler(defaultStreamHandler) } diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/tsconfig.json b/benchmarks/ssr/scenarios/server-routes-matrix/react/tsconfig.json new file mode 100644 index 00000000000..59350920762 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "declaration": false, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.*.bench.ts", + "vite.config.ts", + "../bench.ts", + "../hono.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-routes-matrix/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-matrix/react/vite.config.ts new file mode 100644 index 00000000000..4a168fafec2 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-matrix/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-routes-matrix (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/docs/start/framework/react/guide/server-routes.md b/docs/start/framework/react/guide/server-routes.md index 598f5864503..faf416a552b 100644 --- a/docs/start/framework/react/guide/server-routes.md +++ b/docs/start/framework/react/guide/server-routes.md @@ -115,6 +115,17 @@ The start handler is responsible for matching an incoming request to a server ro If you need to customize the server handler, you can do so by creating a custom handler and then passing the event to the start handler. See [The Server Entry Point](./server-entry-point). +### Server-only routes skip the Router + +When a route file defines only `server` options (no component, loader, or other UI options), Start serves exact matches for it from a prebuilt server-only route tree without constructing a Router. This happens automatically on the Vite plugin and needs no configuration. Requests that miss, including page requests and methods the route has no handler for, go through the Router as usual. + +Two router options are not visible on this path: + +- Router-level `caseSensitive` is not applied. A router configured with `caseSensitive: true` still serves `/API/health` from a server-only route at `/api/health`. Set `caseSensitive` on the route itself if you need it there. +- Location `rewrite` options are not applied before matching server-only routes. Put server-only routes at the path the request actually uses. + +Start falls back to the Router for the whole app, with a build warning, when the root route defines `server` options or when a server-only route with a path parameter would shadow a page route. Rsbuild builds always use the Router. + ## Defining a Server Route Server routes are created by adding a `server` property to your `createFileRoute` call. The `server` property contains: diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index 9206ef60dd8..c16d399709a 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -146,6 +146,8 @@ export { rootRouteId } from './root' export type { RootRouteId } from './root' export { BaseRoute, BaseRouteApi, BaseRootRoute } from './route' +export { processRouteTree, findRouteMatch } from './new-process-route-tree' +export type { ProcessRouteTreeResult } from './new-process-route-tree' export type { AnyPathParams, SearchSchemaInput, diff --git a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts index 8df06af4f58..fd03e4c83ff 100644 --- a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts @@ -1,4 +1,8 @@ +import { readFile } from 'node:fs/promises' +import * as t from '@babel/types' +import { parseAst } from '@tanstack/router-utils' import { createRouterPluginContext } from '@tanstack/router-plugin/context' +import { VIRTUAL_MODULES } from '@tanstack/start-server-core/virtual-modules' import { tanStackRouterCodeSplitter, tanstackRouterGenerator, @@ -20,6 +24,71 @@ import type { import type { DevEnvironment, Plugin, PluginOption } from 'vite' import type { TanStackStartInputConfig } from '../../schema' +/** + * URL-space path of a node: route groups and pathless layout segments + * removed. Escaped literal underscores are treated as pathless too, which only + * makes the shadow check stricter. + */ +function urlPath(node: RouteNode) { + return (node.routePath ?? '') + .split('/') + .filter((s) => !s.startsWith('_') && !/^\(.*\)$/.test(s)) + .join('/') +} + +/** Static path prefix before the first `$` segment, or undefined if none. */ +function dynamicPrefix(routePath: string) { + const segments = routePath.split('/') + const i = segments.findIndex((s) => s.includes('$')) + return i === -1 ? undefined : segments.slice(0, i).join('/') + '/' +} + +/** + * True unless the root file provably calls createRootRoute / + * createRootRouteWithContext with an object literal that has no `server` key. + */ +async function rootRouteMayHaveServerOptions(rootFilePath: string) { + const code = await readFile(rootFilePath, 'utf-8') + const ast = parseAst({ code, sourceFilename: rootFilePath }) + let verdict: boolean | undefined + const visit = (value: unknown): void => { + if (verdict !== undefined || !value || typeof value !== 'object') { + return + } + if (Array.isArray(value)) { + value.forEach(visit) + return + } + const node = value as t.Node + if (t.isCallExpression(node)) { + const callee = node.callee + const isRootCall = + (t.isIdentifier(callee) && callee.name === 'createRootRoute') || + (t.isCallExpression(callee) && + t.isIdentifier(callee.callee) && + callee.callee.name === 'createRootRouteWithContext') + if (isRootCall) { + const arg = node.arguments[0] + verdict = + !t.isObjectExpression(arg) || + arg.properties.some( + (p) => + !t.isObjectProperty(p) || + p.computed || + (t.isIdentifier(p.key) && p.key.name === SERVER_PROP) || + (t.isStringLiteral(p.key) && p.key.value === SERVER_PROP), + ) + return + } + } + for (const value of Object.values(node)) { + visit(value) + } + } + visit(ast.program) + return verdict ?? true +} + function isServerOnlyNode(node: RouteNode | undefined) { if (!node?.createFileRouteProps) { return false @@ -36,6 +105,8 @@ export function tanStackStartRouter( corePluginOpts: TanStackStartVitePluginCoreOptions, ): Array { const routerPluginContext = createRouterPluginContext() + const API_TREE_ID = VIRTUAL_MODULES.apiRouteTree + const RESOLVED_API_TREE_ID = '\0' + API_TREE_ID const getGeneratedRouteTreePath = () => { const { startConfig } = getConfig() @@ -57,6 +128,18 @@ export function tanStackStartRouter( clientEnvironment.hot.send({ type: 'full-reload', path: '*' }) } + let serverEnvironment: DevEnvironment | null = null + // The API tree is virtual, so no file change invalidates it. Adding or + // removing a route file must reach the dev runner, which re-fetches the + // module and its importers (the server entry) on the next request. + function invalidateApiTree() { + const mod = + serverEnvironment?.moduleGraph.getModuleById(RESOLVED_API_TREE_ID) + if (mod) { + serverEnvironment!.moduleGraph.invalidateModule(mod) + } + } + let generatorInstance: Generator | null = null const clientTreeGeneratorPlugin: GeneratorPlugin = { @@ -64,6 +147,9 @@ export function tanStackStartRouter( init({ generator }) { generatorInstance = generator }, + onRouteTreeChanged() { + invalidateApiTree() + }, afterTransform({ node, prevNode }) { if (isServerOnlyNode(node) !== isServerOnlyNode(prevNode)) { invalidate() @@ -136,8 +222,110 @@ export function tanStackStartRouter( }, }, } + // Server-only routes as their own tree, so createStartHandler can dispatch + // them without a Router. When the tree cannot be made safely the module + // exports `undefined` and every request takes the Router path. + const apiTreePlugin: Plugin = { + name: 'tanstack-start:route-tree-api-plugin', + enforce: 'pre', + applyToEnvironment: (env) => env.name === VITE_ENVIRONMENT_NAMES.server, + configureServer(server) { + serverEnvironment = server.environments[VITE_ENVIRONMENT_NAMES.server] + }, + resolveId(id) { + return id === API_TREE_ID ? RESOLVED_API_TREE_ID : undefined + }, + async load(id) { + if (id !== RESOLVED_API_TREE_ID) { + return undefined + } + if (!generatorInstance) { + throw new Error('Generator instance not initialized') + } + const crawlingResult = await generatorInstance.getCrawlingResult() + if (!crawlingResult) { + throw new Error('Crawling result not available') + } + const disabled = (reason: string) => { + this.warn( + `Server-route fast path disabled: ${reason} Server routes still work through the Router.`, + ) + return { code: 'export const apiRouteTree = undefined\n', map: null } + } + // The API tree replaces __root with a bare root, so root server + // middleware (often auth) would be silently skipped. Fail closed, + // including when the root options cannot be read statically. + if ( + await rootRouteMayHaveServerOptions( + crawlingResult.rootRouteNode.fullPath, + ) + ) { + return disabled( + 'the root route defines `server` options (or its options could not be read statically). Move root server middleware to the API routes or to global requestMiddleware.', + ) + } + // Keep only subtrees where every node is server-only, so the tree never + // imports a route file with a component. + const routeNodes: Array = [] + const pruned: Array = [] + const prune = (node: RouteNode) => { + pruned.push(node) + node.children?.forEach(prune) + } + const keep = (node: RouteNode): RouteNode | null => { + if (!isServerOnlyNode(node)) { + prune(node) + return null + } + const children = (node.children || []) + .map(keep) + .filter((n): n is RouteNode => n !== null) + routeNodes.push(node) + return { ...node, children } + } + const routeTree = crawlingResult.acc.routeTree + .map(keep) + .filter((n): n is RouteNode => n !== null) + // A kept param or splat route must not win a path that a pruned route + // would win in the full tree (`/api/$` vs a pruned `/api/docs` page). + for (const kept of routeNodes) { + const prefix = dynamicPrefix(urlPath(kept)) + if (prefix === undefined) { + continue + } + const shadowed = pruned.find((p) => urlPath(p).startsWith(prefix)) + if (shadowed) { + return disabled( + `server-only route "${kept.routePath}" would shadow "${shadowed.routePath}". Give the API route a static prefix no page route shares, or add a component to it.`, + ) + } + } + const buildResult = generatorInstance.buildRouteTree({ + ...crawlingResult, + acc: { ...crawlingResult.acc, routeTree, routeNodes }, + config: { + importRoutesUsingAbsolutePaths: true, + disableTypes: true, + enableRouteTreeFormatting: false, + routeTreeFileHeader: [], + routeTreeFileFooter: [], + }, + }) + // ponytail: the generator hardwires the __root import; swap it for a + // bare root so React never loads. Root server middleware is skipped. + const code = buildResult.routeTreeContent + .replace( + /import \{ Route as rootRouteImport \} from '[^']*'/, + `import { createRootRoute } from '@tanstack/${corePluginOpts.framework}-router'\nconst rootRouteImport = createRootRoute()`, + ) + .replace('export const routeTree =', 'export const apiRouteTree =') + return { code, map: null } + }, + } + return [ clientTreePlugin, + apiTreePlugin, tanstackRouterGenerator( () => startGeneratorConfig({ diff --git a/packages/start-plugin-core/tests/api-route-tree-dev.test.ts b/packages/start-plugin-core/tests/api-route-tree-dev.test.ts new file mode 100644 index 00000000000..cf4f8f3c3e0 --- /dev/null +++ b/packages/start-plugin-core/tests/api-route-tree-dev.test.ts @@ -0,0 +1,155 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import path from 'pathe' +import { parseStartConfig } from '../src/vite/schema' +import { tanStackStartRouter } from '../src/vite/start-router-plugin/plugin' +import type { TanStackStartVitePluginCoreOptions } from '../src/vite/types' + +// The router plugin only reads `framework` from these. +const corePluginOpts = { framework: 'react' as const } + +let root: string +let routesDir: string + +beforeEach(async () => { + root = await mkdtemp(path.join(tmpdir(), 'tss-api-tree-')) + routesDir = path.join(root, 'src/routes') + await mkdir(path.join(routesDir, 'api'), { recursive: true }) + await writeFile( + path.join(routesDir, '__root.tsx'), + `import { createRootRoute } from '@tanstack/react-router'\nexport const Route = createRootRoute({})\n`, + ) + await writeFile( + path.join(routesDir, 'api/health.ts'), + `import { createFileRoute } from '@tanstack/react-router'\nexport const Route = createFileRoute('/api/health')({ server: { handlers: { GET: () => new Response('ok') } } })\n`, + ) +}) + +afterEach(async () => { + await rm(root, { recursive: true, force: true }) +}) + +function fakeEnvironment() { + const mod = { id: '\0#tanstack-start-api-route-tree' } + return { + moduleGraph: { + getModuleById: vi.fn((id: string) => (id === mod.id ? mod : undefined)), + invalidateModule: vi.fn(), + }, + hot: { send: vi.fn() }, + runner: { evaluatedModules: { getModuleById: vi.fn() } }, + } +} + +function setup() { + const startConfig = parseStartConfig({}, corePluginOpts, root) + const plugins = tanStackStartRouter( + {}, + () => ({ startConfig, resolvedStartConfig: {} as any }), + corePluginOpts as TanStackStartVitePluginCoreOptions, + ) as Array + return { + plugins, + generator: plugins.find((p) => p.name === 'tanstack:router-generator'), + apiTree: plugins.find( + (p) => p.name === 'tanstack-start:route-tree-api-plugin', + ), + } +} + +describe('virtual API route tree', () => { + it('exports the server-only routes with a bare root', async () => { + const { generator, apiTree } = setup() + await generator.vite.configResolved({ root }) + const warn = vi.fn() + + const result = await apiTree.load.call( + { warn }, + '\0#tanstack-start-api-route-tree', + ) + + expect(warn).not.toHaveBeenCalled() + expect(result.code).toContain('export const apiRouteTree =') + expect(result.code).toContain('const rootRouteImport = createRootRoute()') + expect(result.code).toContain('api/health') + }, 30_000) + + it('exports undefined with a warning when the root route has server options', async () => { + await writeFile( + path.join(routesDir, '__root.tsx'), + `import { createRootRoute } from '@tanstack/react-router'\nexport const Route = createRootRoute({ server: { middleware: [] } })\n`, + ) + const { generator, apiTree } = setup() + await generator.vite.configResolved({ root }) + const warn = vi.fn() + + const result = await apiTree.load.call( + { warn }, + '\0#tanstack-start-api-route-tree', + ) + + expect(result.code).toBe('export const apiRouteTree = undefined\n') + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('Server-route fast path disabled'), + ) + }, 30_000) + + it('exports undefined with a warning when a server-only param route would shadow a page', async () => { + await writeFile( + path.join(routesDir, 'api/$.ts'), + `import { createFileRoute } from '@tanstack/react-router'\nexport const Route = createFileRoute('/api/$')({ server: { handlers: { GET: () => new Response('splat') } } })\n`, + ) + await writeFile( + path.join(routesDir, 'api/docs.tsx'), + `import { createFileRoute } from '@tanstack/react-router'\nexport const Route = createFileRoute('/api/docs')({ component: () => null })\n`, + ) + const { generator, apiTree } = setup() + await generator.vite.configResolved({ root }) + const warn = vi.fn() + + const result = await apiTree.load.call( + { warn }, + '\0#tanstack-start-api-route-tree', + ) + + expect(result.code).toBe('export const apiRouteTree = undefined\n') + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('would shadow "/api/docs"'), + ) + }, 30_000) +}) + +describe('virtual API route tree in dev', () => { + it('invalidates the server module when a server-only route file is created', async () => { + const startConfig = parseStartConfig({}, corePluginOpts, root) + const plugins = tanStackStartRouter( + {}, + () => ({ startConfig, resolvedStartConfig: {} as any }), + corePluginOpts as TanStackStartVitePluginCoreOptions, + ) as Array + const client = fakeEnvironment() + const server = fakeEnvironment() + const viteServer = { environments: { client, ssr: server } } + for (const plugin of plugins) { + await plugin.configureServer?.(viteServer) + } + const generator = plugins.find( + (p) => p.name === 'tanstack:router-generator', + ) + await generator.vite.configResolved({ root }) + + const file = path.join(routesDir, 'api/users.ts') + await writeFile( + file, + `import { createFileRoute } from '@tanstack/react-router'\nexport const Route = createFileRoute('/api/users')({ server: { handlers: { GET: () => new Response('[]') } } })\n`, + ) + await generator.watchChange(file, { event: 'create' }) + + expect(server.moduleGraph.invalidateModule).toHaveBeenCalledWith( + expect.objectContaining({ + id: '\0#tanstack-start-api-route-tree', + }), + ) + }, 30_000) +}) diff --git a/packages/start-server-core/package.json b/packages/start-server-core/package.json index 020747da699..beb0a5fefb5 100644 --- a/packages/start-server-core/package.json +++ b/packages/start-server-core/package.json @@ -96,6 +96,9 @@ }, "#tanstack-start-plugin-adapters": { "default": "./dist/esm/empty-plugin-adapters.js" + }, + "#tanstack-start-api-route-tree": { + "default": "./dist/esm/empty-api-route-tree.js" } }, "sideEffects": false, diff --git a/packages/start-server-core/src/createStartHandler.ts b/packages/start-server-core/src/createStartHandler.ts index f1be8fe0d9a..1fbe5bc4c38 100644 --- a/packages/start-server-core/src/createStartHandler.ts +++ b/packages/start-server-core/src/createStartHandler.ts @@ -11,9 +11,12 @@ import { } from '@tanstack/start-client-core' import { _getRenderedMatches, + findRouteMatch, isDangerousProtocol, isPromise, isRedirect, + processRouteTree, + trimPathRight, } from '@tanstack/router-core' import { attachRouterServerSsrUtils, @@ -68,6 +71,7 @@ import type { AnyRoute, AnyRouter, AnySerializationAdapter, + ProcessRouteTreeResult, Register, } from '@tanstack/router-core' import type { @@ -101,14 +105,21 @@ interface PluginAdaptersEntry { pluginSerializationAdapters: Array } +interface ApiRouteTreeEntry { + apiRouteTree: AnyRoute | undefined +} + interface Entries { startEntry: StartEntry - routerEntry: RouterEntry pluginAdapters: PluginAdaptersEntry + apiRouteTreeEntry: ApiRouteTreeEntry } // Share initialization, then reuse the loaded entries without a promise wait. let cachedEntries: Entries | Promise | undefined +// The router entry imports the whole app, so it loads on the first request +// that needs a Router rather than with the other entries. +let cachedRouterEntry: RouterEntry | Promise | undefined let hasWarnedMissingCsrfMiddleware = false const defaultCsrfMiddleware = createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn', @@ -126,18 +137,157 @@ const createEarlyHintsForRequest: typeof createEarlyHintsCollector = : createEarlyHintsCollector async function loadEntries(): Promise { - const [routerEntry, startEntry, pluginAdapters] = await Promise.all([ - // @ts-ignore When building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core - import('#tanstack-router-entry'), + const [startEntry, pluginAdapters, apiRouteTreeEntry] = await Promise.all([ // @ts-ignore When building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core import('#tanstack-start-entry'), // @ts-ignore When building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core import('#tanstack-start-plugin-adapters'), + import('#tanstack-start-api-route-tree'), ]) return { - routerEntry: routerEntry as unknown as RouterEntry, startEntry: startEntry as unknown as StartEntry, pluginAdapters: pluginAdapters as unknown as PluginAdaptersEntry, + apiRouteTreeEntry: apiRouteTreeEntry as unknown as ApiRouteTreeEntry, + } +} + +function getRouterEntry() { + if (!cachedRouterEntry) { + // @ts-ignore When building, we currently don't respect tsconfig.ts' `include` so we are not picking up the .d.ts from start-client-core + cachedRouterEntry = import('#tanstack-router-entry').then((entry) => { + cachedRouterEntry = entry as unknown as RouterEntry + return cachedRouterEntry + }) + } + return cachedRouterEntry +} + +// Server-only routes, matched without a Router. Rebuilt only when the +// virtual module hands over a new tree (dev invalidation). +let processedApiTree: + | { + tree: AnyRoute + processedTree: ProcessRouteTreeResult['processedTree'] + } + | undefined + +const EMPTY_START_OPTIONS = {} as AnyStartInstanceOptions + +interface RequestSetup { + requestStartOptions: AnyStartInstanceOptions + flattenedRequestMiddlewares: ReturnType + /** Read-only after setup: consumers copy or query it. */ + executedRequestMiddlewares: Set | undefined +} + +// Per Start options object (a new one after HMR), split by request kind +// because only server functions get the default CSRF middleware. +const requestSetups = new WeakMap< + AnyStartInstanceOptions, + { router?: RequestSetup; serverFn?: RequestSetup } +>() + +function getRequestSetup( + startOptions: AnyStartInstanceOptions, + hasStartInstance: boolean, + pluginAdapters: PluginAdaptersEntry, + isServerFnRequest: boolean, +): RequestSetup { + let byKind = requestSetups.get(startOptions) + if (!byKind) { + byKind = {} + requestSetups.set(startOptions, byKind) + } + const kind = isServerFnRequest ? 'serverFn' : 'router' + let setup = byKind[kind] + if (setup) { + return setup + } + const requestMiddleware = hasStartInstance + ? startOptions.requestMiddleware + : isServerFnRequest + ? [defaultCsrfMiddleware] + : undefined + const requestStartOptions = { + ...startOptions, + requestMiddleware, + serializationAdapters: [ + ...(startOptions.serializationAdapters || []), + ...(pluginAdapters.hasPluginAdapters + ? pluginAdapters.pluginSerializationAdapters + : []), + ServerFunctionSerializationAdapter, + ], + } + let executedRequestMiddlewares: Set | undefined + let flattenedRequestMiddlewares: ReturnType = [] + if (requestMiddleware?.length) { + // Reuse the flattening set for request middleware deduplication. + executedRequestMiddlewares = new Set() + flattenedRequestMiddlewares = flattenMiddlewares( + requestMiddleware, + undefined, + executedRequestMiddlewares, + ) + } + setup = { + requestStartOptions, + flattenedRequestMiddlewares, + executedRequestMiddlewares, + } + byKind[kind] = setup + return setup +} + +/** + * Exact server-route match from the server-only tree, or undefined when the + * request needs the full Router: pages, fuzzy matches, methods without a + * handler, or paths that need normalization. + */ +function matchApiRoute( + tree: AnyRoute | undefined, + pathname: string, + method: string, +): ServerRouteMatch | undefined { + if (!tree) { + return undefined + } + // Routes live under the router basepath; anything outside it is not ours. + let routePath = pathname + if (ROUTER_BASEPATH !== '/') { + const basepath = trimPathRight(ROUTER_BASEPATH) + if (pathname === basepath) { + routePath = '/' + } else if (pathname.startsWith(basepath + '/')) { + routePath = pathname.slice(basepath.length) + } else { + return undefined + } + } + if (processedApiTree?.tree !== tree) { + processedApiTree = { + tree, + processedTree: processRouteTree(tree).processedTree, + } + } + // ponytail: router-level `caseSensitive` and `rewrite` options live in the + // router entry, which is not loaded here. A miss falls back to the Router, + // so only a hit the Router would have routed elsewhere differs. + const match = findRouteMatch( + trimPathRight(routePath), + processedApiTree.processedTree, + false, + ) + if (!match || !resolveRouteHandler(match.route, method)?.handler) { + return undefined + } + const rawParams: Record = Object.create(null) + Object.assign(rawParams, match.rawParams) + return { + pathname, + matchedRoutes: match.branch, + rawParams, + foundRoute: match.route, } } @@ -657,14 +807,30 @@ export function createStartHandler( const requestUrl = event.requestUrl let url = requestUrl const pathname = url.pathname - // Plain RPC paths need no routing normalization. Their payload is read - // from the original query; normalize only if they later request a router. - if ( - !SERVER_FN_BASE || - !pathname.startsWith(SERVER_FN_BASE) || - pathname.includes('%') || - pathname.startsWith('//') - ) { + // Normalization only rewrites encoded or protocol-relative pathnames. + const isPlainPath = !pathname.includes('%') && !pathname.startsWith('//') + const isPlainServerFnPath = + isPlainPath && !!SERVER_FN_BASE && pathname.startsWith(SERVER_FN_BASE) + + const pendingEntries = getEntries() + const entries = isPromise(pendingEntries) + ? await waitForRequest(pendingEntries, signal) + : pendingEntries + + // A server-only route match on the raw pathname skips the Router and + // the normalization the Router would need; the handler can still ask + // for one lazily through getRouterInstance(). + const apiMatch = + isPlainPath && !isPlainServerFnPath + ? matchApiRoute( + entries.apiRouteTreeEntry.apiRouteTree, + pathname, + request.method, + ) + : undefined + // Plain RPC paths need no routing normalization either. Their payload is + // read from the original query; normalize only if they later request a router. + if (!apiMatch && !isPlainServerFnPath) { const normalized = getNormalizedURL(requestUrl) url = normalized.url if (normalized.handledProtocolRelativeURL) { @@ -672,10 +838,6 @@ export function createStartHandler( } } - const pendingEntries = getEntries() - const entries = isPromise(pendingEntries) - ? await waitForRequest(pendingEntries, signal) - : pendingEntries const isServerFnRequest = !!SERVER_FN_BASE && url.pathname.startsWith(SERVER_FN_BASE) const startInstance = entries.startEntry.startInstance @@ -687,48 +849,30 @@ export function createStartHandler( : pendingStartOptions signal.throwIfAborted() } else { - startOptions = {} as AnyStartInstanceOptions + startOptions = EMPTY_START_OPTIONS } - const { hasPluginAdapters, pluginSerializationAdapters } = - entries.pluginAdapters - - const serializationAdapters = [ - ...(startOptions.serializationAdapters || []), - ...(hasPluginAdapters ? pluginSerializationAdapters : []), - ServerFunctionSerializationAdapter, - ] - - const requestStartOptions = { - ...startOptions, - requestMiddleware: startInstance - ? startOptions.requestMiddleware - : isServerFnRequest - ? [defaultCsrfMiddleware] - : undefined, - serializationAdapters, - } - - const requestMiddleware = requestStartOptions.requestMiddleware - let executedRequestMiddlewares: Set | undefined - let flattenedRequestMiddlewares: ReturnType = - [] - if (requestMiddleware?.length) { - // Reuse the flattening set for request middleware deduplication. - executedRequestMiddlewares = new Set() - flattenedRequestMiddlewares = flattenMiddlewares( - requestMiddleware, - undefined, - executedRequestMiddlewares, - ) - } + const { + requestStartOptions, + flattenedRequestMiddlewares, + executedRequestMiddlewares, + } = getRequestSetup( + startOptions, + !!startInstance, + entries.pluginAdapters, + isServerFnRequest, + ) // Memoized router getter const getRouter = (): Promise => { routerPromise ??= (async () => { signal.throwIfAborted() const routerUrl = url === requestUrl ? getNormalizedURL(url).url : url - const pendingRouter = entries.routerEntry.getRouter() + const pendingRouterEntry = getRouterEntry() + const routerEntry = isPromise(pendingRouterEntry) + ? await waitForRequest(pendingRouterEntry, signal) + : pendingRouterEntry + const pendingRouter = routerEntry.getRouter() const requestRouter = isPromise(pendingRouter) ? await waitForRequest(pendingRouter, signal) : pendingRouter @@ -893,6 +1037,7 @@ export function createStartHandler( () => handleServerRoutes({ getRouter, + apiMatch, request, executeRouter, context, @@ -1129,8 +1274,42 @@ function withParsedParams( } } +interface ServerRouteMatch { + pathname: string + matchedRoutes: ReadonlyArray + rawParams: Record + foundRoute: AnyRoute | undefined +} + +/** + * The handler for a request method, with HEAD falling back to GET then ANY + * (RFC 9110 §9.3.2: HEAD returns the same header fields as GET). + */ +function resolveRouteHandler(route: AnyRoute | undefined, method: string) { + const server = route?.options.server + if (!server?.handlers) { + return undefined + } + const handlers = + typeof server.handlers === 'function' + ? server.handlers({ createHandlers: (d: any) => d }) + : server.handlers + const requestMethod = method.toUpperCase() as RouteMethod + const handler = + requestMethod === 'HEAD' + ? (handlers['HEAD'] ?? handlers['GET'] ?? handlers['ANY']) + : (handlers[requestMethod] ?? handlers['ANY']) + if (!handler) { + return undefined + } + return typeof handler === 'function' + ? { handler, middleware: undefined } + : { handler: handler.handler, middleware: handler.middleware } +} + async function handleServerRoutes({ getRouter, + apiMatch, request, executeRouter, context, @@ -1139,6 +1318,7 @@ async function handleServerRoutes({ event, }: { getRouter: () => Promise + apiMatch: ServerRouteMatch | undefined request: Request executeRouter: ( serverContext: any, @@ -1150,20 +1330,26 @@ async function handleServerRoutes({ signal: AbortSignal event: StartEvent }): Promise { - const router = await getRouter() - const { pathname } = router.latestLocation - // this will perform a fuzzy match, however for server routes we need an exact match - // if the route is not an exact match, executeRouter will handle rendering the app router - // The cached match avoids another route-tree traversal during the app router render. - const [matchedRoutes, rawParams, foundRoute] = - router.getMatchedRoutes(pathname) + let match = apiMatch + let router: AnyRouter | undefined + if (!match) { + router = await getRouter() + const { pathname } = router.latestLocation + // this will perform a fuzzy match, however for server routes we need an exact match + // if the route is not an exact match, executeRouter will handle rendering the app router + // The cached match avoids another route-tree traversal during the app router render. + const [matchedRoutes, rawParams, foundRoute] = + router.getMatchedRoutes(pathname) + match = { pathname, matchedRoutes, rawParams, foundRoute } + } + const { pathname, matchedRoutes, rawParams, foundRoute } = match const isExactMatch = foundRoute && rawParams['**'] === undefined // Collect and dedupe route middlewares const routeMiddlewares: Array = [] let terminalHandler: TODO = (ctx: TODO) => - executeRouter(ctx.context, matchedRoutes, router) + executeRouter(ctx.context, matchedRoutes, router!) let terminalNext: TODO // Collect middleware from matched routes, filtering out those already executed @@ -1183,41 +1369,23 @@ async function handleServerRoutes({ } // Add handler middleware if exact match - const server = foundRoute?.options.server - if (server?.handlers && isExactMatch) { - const handlers = - typeof server.handlers === 'function' - ? server.handlers({ createHandlers: (d: any) => d }) - : server.handlers - - const requestMethod = request.method.toUpperCase() as RouteMethod - // Per RFC 9110 §9.3.2, HEAD must return the same header fields as GET. - // Priority for HEAD: explicit HEAD handler → GET → ANY (last resort). - const handler = - requestMethod === 'HEAD' - ? (handlers['HEAD'] ?? handlers['GET'] ?? handlers['ANY']) - : (handlers[requestMethod] ?? handlers['ANY']) - if (handler) { - const mayDefer = !!foundRoute.options.component - - if (typeof handler !== 'function') { - if (handler.middleware?.length) { - const handlerMiddlewares = flattenMiddlewares(handler.middleware) - for (const m of handlerMiddlewares) { - routeMiddlewares.push(m.options.server) - } - } + const resolved = isExactMatch + ? resolveRouteHandler(foundRoute, request.method) + : undefined + if (resolved) { + const mayDefer = !!foundRoute!.options.component + if (resolved.middleware?.length) { + for (const m of flattenMiddlewares(resolved.middleware)) { + routeMiddlewares.push(m.options.server) } - const routeHandler = - typeof handler === 'function' ? handler : handler.handler - if (routeHandler) { - const parsedHandler = withParsedParams(routeHandler, matchedRoutes) - if (!mayDefer) { - terminalHandler = parsedHandler - terminalNext = throwIfMayNotDefer - } else { - routeMiddlewares.push(parsedHandler) - } + } + if (resolved.handler) { + const parsedHandler = withParsedParams(resolved.handler, matchedRoutes) + if (!mayDefer) { + terminalHandler = parsedHandler + terminalNext = throwIfMayNotDefer + } else { + routeMiddlewares.push(parsedHandler) } } } diff --git a/packages/start-server-core/src/empty-api-route-tree.ts b/packages/start-server-core/src/empty-api-route-tree.ts new file mode 100644 index 00000000000..a86a09f1b28 --- /dev/null +++ b/packages/start-server-core/src/empty-api-route-tree.ts @@ -0,0 +1,5 @@ +import type { AnyRoute } from '@tanstack/router-core' + +// Bundlers that do not build the server-only route tree resolve this instead, +// which keeps every request on the Router path. +export const apiRouteTree: AnyRoute | undefined = undefined diff --git a/packages/start-server-core/src/tanstack-start.d.ts b/packages/start-server-core/src/tanstack-start.d.ts index 651e1712520..2713118d122 100644 --- a/packages/start-server-core/src/tanstack-start.d.ts +++ b/packages/start-server-core/src/tanstack-start.d.ts @@ -10,6 +10,13 @@ declare module 'tanstack-start-route-tree:v' { export const routeTree: AnyRoute | undefined } +declare module '#tanstack-start-api-route-tree' { + import type { AnyRoute } from '@tanstack/router-core' + + /** Server-only routes (no UI) with a bare root, or undefined when unavailable. */ + export const apiRouteTree: AnyRoute | undefined +} + declare module '#tanstack-start-server-fn-resolver' { export type ServerFnLookupAccess = { origin: 'client' } | { origin: 'server' } diff --git a/packages/start-server-core/src/virtual-modules.ts b/packages/start-server-core/src/virtual-modules.ts index 6914fcce451..6711dd01604 100644 --- a/packages/start-server-core/src/virtual-modules.ts +++ b/packages/start-server-core/src/virtual-modules.ts @@ -2,4 +2,6 @@ export const VIRTUAL_MODULES = { startManifest: 'tanstack-start-manifest:v', serverFnResolver: '#tanstack-start-server-fn-resolver', pluginAdapters: '#tanstack-start-plugin-adapters', + /** Server-only route tree matched without a Router; `undefined` disables the fast path. */ + apiRouteTree: '#tanstack-start-api-route-tree', } as const diff --git a/packages/start-server-core/tests/server-route-fast-path-basepath.test.ts b/packages/start-server-core/tests/server-route-fast-path-basepath.test.ts new file mode 100644 index 00000000000..e523c9b51a3 --- /dev/null +++ b/packages/start-server-core/tests/server-route-fast-path-basepath.test.ts @@ -0,0 +1,81 @@ +// @vitest-environment node + +import { afterAll, describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + RouterCore, + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} from '@tanstack/router-core' +import { createStartHandler } from '../src/createStartHandler' +import type { AnyRoute } from '@tanstack/router-core' + +// The handler reads the basepath at module load, so it is set before import. +const mocks = vi.hoisted(() => { + const previous = process.env.TSS_ROUTER_BASEPATH + process.env.TSS_ROUTER_BASEPATH = '/app/' + return { previous, routerRequests: 0 } +}) + +afterAll(() => { + process.env.TSS_ROUTER_BASEPATH = mocks.previous +}) + +const rootRoute = new BaseRootRoute({}) +const healthRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/api/health', + server: { handlers: { GET: () => Response.json({ ok: true }) } }, +}) +const tree = rootRoute.addChildren([healthRoute]) as unknown as AnyRoute + +vi.mock('#tanstack-start-api-route-tree', () => ({ apiRouteTree: tree })) +vi.mock('#tanstack-start-entry', () => ({ startInstance: undefined })) +vi.mock('#tanstack-router-entry', () => ({ + getRouter: () => { + mocks.routerRequests++ + const router = new RouterCore( + { + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: tree, + basepath: '/app', + }, + () => ({ + createMutableStore: createNonReactiveMutableStore, + createReadonlyStore: createNonReactiveReadonlyStore, + batch: (fn: () => void) => fn(), + }), + ) + router.isServer = true + return router + }, +})) + +const handler = createStartHandler(() => new Response('page', { status: 599 })) +const fetch = (path: string) => + handler( + new Request(`http://localhost${path}`, { + headers: { accept: 'text/html' }, + }), + undefined as any, + ) + +describe('server-route fast path under a router basepath', () => { + it('matches routes below the basepath without a Router', async () => { + const res = await fetch('/app/api/health') + + expect(await res.json()).toEqual({ ok: true }) + expect(mocks.routerRequests).toBe(0) + }) + + it('leaves paths outside the basepath to the Router', async () => { + // Whatever the Router then does with them is its own behaviour; the fast + // path must not have answered. + for (const path of ['/api/health', '/app', '/application/api/health']) { + await fetch(path) + } + expect(mocks.routerRequests).toBe(3) + }) +}) diff --git a/packages/start-server-core/tests/server-route-fast-path.test.ts b/packages/start-server-core/tests/server-route-fast-path.test.ts new file mode 100644 index 00000000000..8668f858a0b --- /dev/null +++ b/packages/start-server-core/tests/server-route-fast-path.test.ts @@ -0,0 +1,318 @@ +// @vitest-environment node + +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + createMiddleware, + getGlobalStartContext, + getRouterInstance, +} from '@tanstack/start-client-core' +import { + BaseRootRoute, + BaseRoute, + RouterCore, + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} from '@tanstack/router-core' +import { createStartHandler } from '../src/createStartHandler' +import type { AnyRoute } from '@tanstack/router-core' + +const mocks = vi.hoisted(() => { + const previousServerFnBase = process.env.TSS_SERVER_FN_BASE + process.env.TSS_SERVER_FN_BASE = '/_serverFn/' + return { + previousServerFnBase, + apiTree: undefined as AnyRoute | undefined, + routerTree: undefined as AnyRoute | undefined, + startOptions: undefined as undefined | Record, + routerRequests: 0, + } +}) + +vi.mock('#tanstack-start-api-route-tree', () => ({ + get apiRouteTree() { + return mocks.apiTree + }, +})) + +vi.mock('#tanstack-start-entry', () => ({ + get startInstance() { + return mocks.startOptions + ? { getOptions: () => mocks.startOptions } + : undefined + }, +})) + +vi.mock('#tanstack-router-entry', () => ({ + getRouter: () => { + mocks.routerRequests++ + return makeRouter(mocks.routerTree!) + }, +})) + +afterAll(() => { + process.env.TSS_SERVER_FN_BASE = mocks.previousServerFnBase +}) + +const calls: Array = [] + +beforeEach(() => { + calls.length = 0 + mocks.startOptions = undefined + mocks.routerRequests = 0 +}) + +function makeTree(opts: { + parentServer?: any + routeServer?: any + params?: any +}) { + const rootRoute = new BaseRootRoute({}) + const apiRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/api', + server: opts.parentServer, + }) + const userRoute = new BaseRoute({ + getParentRoute: () => apiRoute, + path: '/users/$id', + params: opts.params, + server: opts.routeServer, + }) + return rootRoute.addChildren([ + apiRoute.addChildren([userRoute]), + ]) as unknown as AnyRoute +} + +// The Router path sees the same routes, so a miss renders the "page". +function makeRouter(routeTree: AnyRoute) { + const router = new RouterCore( + { + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree, + }, + () => ({ + createMutableStore: createNonReactiveMutableStore, + createReadonlyStore: createNonReactiveReadonlyStore, + batch: (fn: () => void) => fn(), + }), + ) + router.isServer = true + return router +} + +function makeHandler(tree: AnyRoute, startOptions?: Record) { + mocks.apiTree = tree + mocks.routerTree = tree + mocks.startOptions = startOptions + return createStartHandler(() => new Response('page', { status: 599 })) +} + +const fetch = ( + handler: ReturnType, + path: string, + init?: RequestInit, +) => + handler( + new Request(`http://localhost${path}`, { + ...init, + headers: { accept: 'text/html', ...init?.headers }, + }), + undefined as any, + ) + +describe('server-route fast path', () => { + it('dispatches an exact match with params without building a Router', async () => { + const handler = makeHandler( + makeTree({ + routeServer: { + handlers: { + GET: ({ params }: any) => Response.json({ id: params.id }), + }, + }, + }), + ) + + const res = await fetch(handler, '/api/users/42?x=1') + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ id: '42' }) + expect(mocks.routerRequests).toBe(0) + }) + + it('takes the Router path for unmatched, fuzzy, and method-less requests', async () => { + const handler = makeHandler( + makeTree({ + routeServer: { handlers: { GET: () => new Response('ok') } }, + }), + ) + + for (const [path, init] of [ + ['/nope', undefined], + ['/api/users/42/extra', undefined], + ['/api/users/42', { method: 'POST' }], + ['/api', undefined], + ] as const) { + const res = await fetch(handler, path, init) + expect(res.status).toBe(599) + } + expect(mocks.routerRequests).toBe(4) + }) + + it('takes the Router path when no API tree was built', async () => { + const handler = makeHandler( + makeTree({ + routeServer: { handlers: { GET: () => new Response('ok') } }, + }), + ) + mocks.apiTree = undefined + + const res = await fetch(handler, '/api/users/1') + + expect(await res.text()).toBe('ok') + expect(mocks.routerRequests).toBe(1) + }) + + it('serves HEAD from GET with the same headers and no body', async () => { + const handler = makeHandler( + makeTree({ + routeServer: { + handlers: { + GET: () => new Response('body', { headers: { 'x-a': '1' } }), + }, + }, + }), + ) + + const res = await fetch(handler, '/api/users/1', { method: 'HEAD' }) + + expect(res.status).toBe(200) + expect(res.headers.get('x-a')).toBe('1') + expect(res.body).toBeNull() + expect(mocks.routerRequests).toBe(0) + }) + + it('uses ANY when no method handler exists', async () => { + const handler = makeHandler( + makeTree({ + routeServer: { handlers: { ANY: () => new Response('any') } }, + }), + ) + + const res = await fetch(handler, '/api/users/1', { method: 'DELETE' }) + + expect(await res.text()).toBe('any') + expect(mocks.routerRequests).toBe(0) + }) + + it('runs global, parent, route, and handler middleware in order and merges context', async () => { + const mw = (name: string) => + createMiddleware({ type: 'request' }).server(({ next }) => { + calls.push(name) + return next({ context: { [name]: true } }) + }) + const handler = makeHandler( + makeTree({ + parentServer: { middleware: [mw('parent')] }, + routeServer: { + middleware: [mw('route')], + handlers: { + GET: { + middleware: [mw('handler')], + handler: ({ context }: any) => { + calls.push('fn') + return Response.json(context) + }, + }, + }, + }, + }), + { requestMiddleware: [mw('global')] }, + ) + + const res = await fetch(handler, '/api/users/1') + + expect(calls).toEqual(['global', 'parent', 'route', 'handler', 'fn']) + expect(await res.json()).toEqual({ + global: true, + parent: true, + route: true, + handler: true, + }) + expect(mocks.routerRequests).toBe(0) + }) + + it('does not rerun route middleware that already ran as global middleware', async () => { + const shared = createMiddleware({ type: 'request' }).server(({ next }) => { + calls.push('shared') + return next() + }) + const handler = makeHandler( + makeTree({ + parentServer: { middleware: [shared] }, + routeServer: { + middleware: [shared], + handlers: { GET: () => new Response() }, + }, + }), + { requestMiddleware: [shared] }, + ) + + await fetch(handler, '/api/users/1') + + expect(calls).toEqual(['shared']) + }) + + it('runs route middleware and handlers inside the Start request context', async () => { + const handler = makeHandler( + makeTree({ + routeServer: { + middleware: [ + createMiddleware({ type: 'request' }).server(({ next }) => + next({ context: { seenGlobal: getGlobalStartContext() } }), + ), + ], + handlers: { + GET: async ({ context }: any) => + Response.json({ + ...context, + hasRouter: !!(await getRouterInstance()), + }), + }, + }, + }), + { + requestMiddleware: [ + createMiddleware({ type: 'request' }).server(({ next }) => + next({ context: { fromGlobal: 1 } }), + ), + ], + }, + ) + + const res = await fetch(handler, '/api/users/1') + + expect(await res.json()).toEqual({ + fromGlobal: 1, + seenGlobal: { fromGlobal: 1 }, + hasRouter: true, + }) + // Only the handler's explicit getRouterInstance() built one. + expect(mocks.routerRequests).toBe(1) + }) + + it('applies params.parse before the handler', async () => { + const handler = makeHandler( + makeTree({ + params: { parse: (p: any) => ({ id: Number(p.id) }) }, + routeServer: { + handlers: { GET: ({ params }: any) => Response.json(params) }, + }, + }), + ) + + const res = await fetch(handler, '/api/users/7') + + expect(await res.json()).toEqual({ id: 7 }) + }) +}) diff --git a/packages/start-server-core/vite.config.ts b/packages/start-server-core/vite.config.ts index 09e3bf95397..b201e81415f 100644 --- a/packages/start-server-core/vite.config.ts +++ b/packages/start-server-core/vite.config.ts @@ -27,6 +27,9 @@ const fakeStartManifest = fileURLToPath( const fakePluginAdapters = fileURLToPath( new URL('./src/empty-plugin-adapters.ts', import.meta.url), ) +const fakeApiRouteTree = fileURLToPath( + new URL('./src/empty-api-route-tree.ts', import.meta.url), +) const fakeServerFnResolver = fileURLToPath( new URL('./src/fake-start-server-fn-resolver.ts', import.meta.url), ) @@ -46,6 +49,7 @@ export default mergeConfig( './src/virtual-modules.ts', './src/fake-start-server-fn-resolver.ts', './src/empty-plugin-adapters.ts', + './src/empty-api-route-tree.ts', ], externalDeps: [ 'cookie-es', @@ -54,6 +58,7 @@ export default mergeConfig( '#tanstack-router-entry', '#tanstack-start-server-fn-resolver', '#tanstack-start-plugin-adapters', + '#tanstack-start-api-route-tree', ], cjs: false, }), @@ -63,6 +68,7 @@ export default mergeConfig( '#tanstack-start-entry': fakeStartEntry, '#tanstack-router-entry': fakeRouterEntry, '#tanstack-start-plugin-adapters': fakePluginAdapters, + '#tanstack-start-api-route-tree': fakeApiRouteTree, '#tanstack-start-server-fn-resolver': fakeServerFnResolver, 'tanstack-start-manifest:v': fakeStartManifest, }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5db197f9546..d613cc73fd8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -710,6 +710,9 @@ importers: '@vitejs/plugin-vue-jsx': specifier: ^5.1.5 version: 5.1.5(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(@typescript/typescript6@6.0.2)) + hono: + specifier: ^4.7.10 + version: 4.13.9 jsdom: specifier: 29.1.1 version: 29.1.1(@noble/hashes@2.0.1) @@ -14969,7 +14972,7 @@ importers: version: 8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vite-plugin-solid: specifier: ^2.11.10 || ^3.0.0-0 - version: 2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) zod: specifier: 'catalog:' version: 4.5.4 @@ -29301,16 +29304,6 @@ packages: '@testing-library/jest-dom': optional: true - vite-plugin-solid@2.11.16: - resolution: {integrity: sha512-qguFUmqY2ICuoGHrZjm+cWpvKkqVyWDMptipC/BIEGr9q6wEzwTWYOjM9pEWJ+yoTuF6T5OpysI2Okdy7rsVlQ==} - peerDependencies: - '@testing-library/jest-dom': ^5.16.6 || ^5.17.0 || ^6.0.0 || ^7.0.0 - solid-js: 1.9.12 - vite: ^8.3.8 - peerDependenciesMeta: - '@testing-library/jest-dom': - optional: true - vite-tsconfig-paths@6.1.1: resolution: {integrity: sha512-2cihq7zliibCCZ8P9cKJrQBkfgdvcFkOOc3Y02o3GWUDLgqjWsZudaoiuOwO/gzTzy17cS5F7ZPo4bsnS4DGkg==} peerDependencies: @@ -44465,21 +44458,6 @@ snapshots: transitivePeerDependencies: - supports-color - vite-plugin-solid@2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): - dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) - '@types/babel__core': 7.20.5 - babel-preset-solid: 1.9.10(@babel/core@7.29.7(supports-color@10.2.2))(solid-js@1.9.12) - merge-anything: 5.1.7 - solid-js: 1.9.12 - solid-refresh: 0.6.3(solid-js@1.9.12)(supports-color@10.2.2) - vite: 8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) - vitefu: 1.1.3(vite@8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) - optionalDependencies: - '@testing-library/jest-dom': 6.6.3 - transitivePeerDependencies: - - supports-color - vite-tsconfig-paths@6.1.1(@typescript/typescript6@6.0.2)(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: debug: 4.4.3(supports-color@10.2.2) From 8d87213eac2ec5e0e39f18a326350d4dbf095f48 Mon Sep 17 00:00:00 2001 From: Tom Beckenham <34339192+tombeckenham@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:28:02 +1100 Subject: [PATCH 2/3] test(start-plugin-core): keep the generator temp dir on the fixture's device Claude-Session: https://claude.ai/code/session_01UFnjmy4rGstaARGzeUapga --- .../tests/api-route-tree-dev.test.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/start-plugin-core/tests/api-route-tree-dev.test.ts b/packages/start-plugin-core/tests/api-route-tree-dev.test.ts index cf4f8f3c3e0..1518e9272f0 100644 --- a/packages/start-plugin-core/tests/api-route-tree-dev.test.ts +++ b/packages/start-plugin-core/tests/api-route-tree-dev.test.ts @@ -43,7 +43,11 @@ function fakeEnvironment() { } function setup() { - const startConfig = parseStartConfig({}, corePluginOpts, root) + const startConfig = parseStartConfig( + { router: { tmpDir: path.join(root, '.tanstack/tmp') } }, + corePluginOpts, + root, + ) const plugins = tanStackStartRouter( {}, () => ({ startConfig, resolvedStartConfig: {} as any }), @@ -122,7 +126,11 @@ describe('virtual API route tree', () => { describe('virtual API route tree in dev', () => { it('invalidates the server module when a server-only route file is created', async () => { - const startConfig = parseStartConfig({}, corePluginOpts, root) + const startConfig = parseStartConfig( + { router: { tmpDir: path.join(root, '.tanstack/tmp') } }, + corePluginOpts, + root, + ) const plugins = tanStackStartRouter( {}, () => ({ startConfig, resolvedStartConfig: {} as any }), From 4c2a69ce1bc8d9d7b1a8a9821cc70efa8ebfef87 Mon Sep 17 00:00:00 2001 From: Tom Beckenham <34339192+tombeckenham@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:54:03 +1100 Subject: [PATCH 3/3] perf(start-plugin-core): skip the API route tree when no route is server-only Apps without server-only routes paid for a per-request lookup that could never match. Emit an undefined tree instead, and only then check the root route, so those apps no longer see the fast-path warning either. Claude-Session: https://claude.ai/code/session_01UFnjmy4rGstaARGzeUapga --- .../src/vite/start-router-plugin/plugin.ts | 28 +++++++++++-------- .../tests/api-route-tree-dev.test.ts | 19 +++++++++++++ 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts index fd03e4c83ff..86fedfa1aeb 100644 --- a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts @@ -252,18 +252,6 @@ export function tanStackStartRouter( ) return { code: 'export const apiRouteTree = undefined\n', map: null } } - // The API tree replaces __root with a bare root, so root server - // middleware (often auth) would be silently skipped. Fail closed, - // including when the root options cannot be read statically. - if ( - await rootRouteMayHaveServerOptions( - crawlingResult.rootRouteNode.fullPath, - ) - ) { - return disabled( - 'the root route defines `server` options (or its options could not be read statically). Move root server middleware to the API routes or to global requestMiddleware.', - ) - } // Keep only subtrees where every node is server-only, so the tree never // imports a route file with a component. const routeNodes: Array = [] @@ -286,6 +274,22 @@ export function tanStackStartRouter( const routeTree = crawlingResult.acc.routeTree .map(keep) .filter((n): n is RouteNode => n !== null) + // No server-only routes: skip the per-request match entirely. + if (routeNodes.length === 0) { + return { code: 'export const apiRouteTree = undefined\n', map: null } + } + // The API tree replaces __root with a bare root, so root server + // middleware (often auth) would be silently skipped. Fail closed, + // including when the root options cannot be read statically. + if ( + await rootRouteMayHaveServerOptions( + crawlingResult.rootRouteNode.fullPath, + ) + ) { + return disabled( + 'the root route defines `server` options (or its options could not be read statically). Move root server middleware to the API routes or to global requestMiddleware.', + ) + } // A kept param or splat route must not win a path that a pruned route // would win in the full tree (`/api/$` vs a pruned `/api/docs` page). for (const kept of routeNodes) { diff --git a/packages/start-plugin-core/tests/api-route-tree-dev.test.ts b/packages/start-plugin-core/tests/api-route-tree-dev.test.ts index 1518e9272f0..7a6e545ef8c 100644 --- a/packages/start-plugin-core/tests/api-route-tree-dev.test.ts +++ b/packages/start-plugin-core/tests/api-route-tree-dev.test.ts @@ -79,6 +79,25 @@ describe('virtual API route tree', () => { expect(result.code).toContain('api/health') }, 30_000) + it('exports undefined without a warning when no route is server-only', async () => { + await rm(path.join(routesDir, 'api'), { recursive: true, force: true }) + await writeFile( + path.join(routesDir, '__root.tsx'), + `import { createRootRoute } from '@tanstack/react-router'\nexport const Route = createRootRoute({ server: { middleware: [] } })\n`, + ) + const { generator, apiTree } = setup() + await generator.vite.configResolved({ root }) + const warn = vi.fn() + + const result = await apiTree.load.call( + { warn }, + '\0#tanstack-start-api-route-tree', + ) + + expect(result.code).toBe('export const apiRouteTree = undefined\n') + expect(warn).not.toHaveBeenCalled() + }, 30_000) + it('exports undefined with a warning when the root route has server options', async () => { await writeFile( path.join(routesDir, '__root.tsx'),