Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/server-route-fast-path.md
Original file line number Diff line number Diff line change
@@ -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.
35 changes: 18 additions & 17 deletions benchmarks/ssr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 4 additions & 1 deletion benchmarks/ssr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand All @@ -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"
],
Expand Down Expand Up @@ -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",
Expand Down
200 changes: 200 additions & 0 deletions benchmarks/ssr/scenarios/server-routes-matrix/bench.ts
Original file line number Diff line number Diff line change
@@ -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<void>
}

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<string, unknown>,
) {
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<string, unknown>
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<string, Shape>

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)
})
}
}
35 changes: 35 additions & 0 deletions benchmarks/ssr/scenarios/server-routes-matrix/hono.ts
Original file line number Diff line number Diff line change
@@ -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<Env>(async (c, next) => {
c.set(key, value)
await next()
})

export const honoApp = new Hono<Env>()

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 }))
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Generated by gen-many-routes.mjs and the Start build.
src/routes/api/many/
src/routeTree.gen.ts
Original file line number Diff line number Diff line change
@@ -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} }) } },
})
`,
)
}
Loading
Loading