diff --git a/.changeset/react-start-prebundle-store-path.md b/.changeset/react-start-prebundle-store-path.md
new file mode 100644
index 0000000000..5c5b78c8da
--- /dev/null
+++ b/.changeset/react-start-prebundle-store-path.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/react-start': patch
+---
+
+fix: Vite pre-bundles `@tanstack/react-store` for a project that depends on `@tanstack/react-start` but not on `@tanstack/react-router` itself. Start named the dependency by a path through `@tanstack/react-router`, which only resolves from a project that depends on the router. In such a project Vite warned "Failed to resolve dependency: @tanstack/react-router > @tanstack/react-store", and a browser failed to load the store's CommonJS dependency (`use-sync-external-store`).
diff --git a/.changeset/start-mock-server-fn.md b/.changeset/start-mock-server-fn.md
new file mode 100644
index 0000000000..6dbd9b72e3
--- /dev/null
+++ b/.changeset/start-mock-server-fn.md
@@ -0,0 +1,24 @@
+---
+'@tanstack/start-client-core': minor
+'@tanstack/react-start': minor
+'@tanstack/solid-start': minor
+'@tanstack/vue-start': minor
+'@tanstack/start-plugin-core': minor
+---
+
+Add `mockServerFn` and `resetServerFnMocks` for client tests, exported from `@tanstack/react-start/testing`, `@tanstack/solid-start/testing` and `@tanstack/vue-start/testing`. Experimental.
+
+A client test has no server. When Vitest compiles a project with Start's plugin, a server function call in client code no longer sends a request. It goes to the mock a test registered for that function, and fails with an error that names the function when there is none.
+
+```ts
+import { mockServerFn } from '@tanstack/react-start/testing'
+
+test('greets', async () => {
+ mockServerFn(greet, ({ data }) => `Hello ${data}`)
+ // ...
+})
+```
+
+A mock that a test registers ends with that test. Start's plugin adds a setup file to every Vitest project for this. `resetServerFnMocks` removes mocks earlier.
+
+The mock is typed from the server function: it gets the `data` the function is called with, and has to return what the function's handler returns. It stands for the server side of the function (its server middleware, validator and handler); the function's client middleware runs as in the app. Unlike a module mock, it also answers a call made in the file that defines the server function.
diff --git a/.changeset/start-server-test-harness.md b/.changeset/start-server-test-harness.md
new file mode 100644
index 0000000000..a1226bd5c8
--- /dev/null
+++ b/.changeset/start-server-test-harness.md
@@ -0,0 +1,37 @@
+---
+'@tanstack/start-server-core': minor
+'@tanstack/start-client-core': minor
+'@tanstack/start-plugin-core': minor
+'@tanstack/start-storage-context': patch
+'@tanstack/react-start': minor
+'@tanstack/solid-start': minor
+'@tanstack/vue-start': minor
+---
+
+Add `runInRequest`, `mockMiddleware` and `runMiddleware` for server tests, exported from `@tanstack/react-start/testing/server`, `@tanstack/solid-start/testing/server` and `@tanstack/vue-start/testing/server`. Experimental.
+
+```ts
+import {
+ mockMiddleware,
+ runInRequest,
+ runMiddleware,
+} from '@tanstack/react-start/testing/server'
+
+test('likePost counts a like', async () => {
+ await runInRequest({ headers: { cookie: 'session=ada' } }, async () => {
+ expect(await likePost({ data: '1' })).toBe(1)
+ expect(getResponseHeader('cache-control')).toBe('no-store')
+ })
+})
+```
+
+- `runInRequest` runs a callback as the code that handles one request. The request middleware of `src/start.ts` runs first. A server function call inside the callback runs as a loader's call does during server rendering: its middleware, its validator and its handler. Start's request and response helpers work inside the callback. `globalMiddleware: 'skip'` leaves the middleware of `src/start.ts` out and takes a `context` that is typed from the start instance.
+- `mockMiddleware` replaces a middleware with a function that is typed from it. A mock ends with the test that registered it, or with the request when it was registered inside `runInRequest`.
+- `runMiddleware` calls the server function of one middleware, for a function middleware and for a request middleware.
+
+A server function that a test calls outside of `runInRequest` fails with an error that names `runInRequest`.
+
+Fixes for test runs:
+
+- A server test could not call a server function when Vitest served the calling module from its module cache, which is the default from the second run on. The call failed with "Invalid server function ID". In a test run the server now finds a function by its id alone.
+- A project without a router entry could not load `@tanstack/react-start/server` in a server test (`Missing "#tanstack-router-entry" specifier`).
diff --git a/.changeset/start-vitest-test-runs.md b/.changeset/start-vitest-test-runs.md
new file mode 100644
index 0000000000..16da837679
--- /dev/null
+++ b/.changeset/start-vitest-test-runs.md
@@ -0,0 +1,15 @@
+---
+'@tanstack/start-plugin-core': minor
+'@tanstack/router-plugin': minor
+'@tanstack/router-generator': minor
+---
+
+Start's Vite plugin can be used in a Vitest config. When Vitest resolves the config to run tests, the plugin compiles the code as it does in the app (`createServerFn`, `createIsomorphicFn`, `createServerOnlyFn`, `createClientOnlyFn`, the server-only route options), for the client in browser mode and in jsdom or happy-dom, and for the server in the Node environment. It does not set up the app's dev server, preview server or build.
+
+- A project needs no router entry and no routes. A package that only uses Start's compile-time APIs used to fail with "Could not resolve entry for router entry".
+- The route tree is generated once, when Vitest starts, and only for a project with a router entry and a root route. It is not regenerated while Vitest watches.
+- A test run never writes route files: a route file with an outdated route path and an empty route file are left as they are, with a warning.
+- A module that calls `createFileRoute`, `createRootRoute` or `createRootRouteWithContext` loses its `server`, `ssr` and `headers` options in client code even when the route generator does not know the module.
+- Start's own packages go through the Start compiler in jsdom, happy-dom and Node tests of a project that installs them from the registry. Vitest's translation of the wildcards in `resolve.noExternal` misses a package name with a dash, so `@tanstack/start-client-core` ran uncompiled and a server function call in a client test failed with "No Start context found in AsyncLocalStorage". In a test run Start now names its packages with regular expressions.
+
+For this, `Generator` of `@tanstack/router-generator` takes `writeRouteFiles: false`, and `tanstackRouterGenerator` and `tanStackRouterCodeSplitter` of `@tanstack/router-plugin/vite` take options for the plugin that embeds them.
diff --git a/docs/start/config.json b/docs/start/config.json
index 36af0e6e0d..0e8946253e 100644
--- a/docs/start/config.json
+++ b/docs/start/config.json
@@ -129,6 +129,10 @@
{
"label": "Server Routes",
"to": "framework/react/guide/server-routes"
+ },
+ {
+ "label": "Testing",
+ "to": "framework/react/guide/testing"
}
]
},
diff --git a/docs/start/framework/react/guide/testing.md b/docs/start/framework/react/guide/testing.md
new file mode 100644
index 0000000000..5323575dc4
--- /dev/null
+++ b/docs/start/framework/react/guide/testing.md
@@ -0,0 +1,554 @@
+---
+id: testing
+title: Testing
+---
+
+> **Experimental:** Start's support for test runners is experimental and subject to change. It works with Vitest.
+
+Start's Vite plugin compiles your code for the environment it runs in. In client code a server function becomes a request to the server, and an isomorphic function keeps its client implementation. Code that only the server uses is removed, together with its imports. Tests need the same compilation: without it, a client test imports your database client and every other module that only the server can load.
+
+When Vitest loads a config that contains `tanstackStart()`, the plugin compiles your code as it does in the app. It leaves out the parts that serve or build the app, so a test run starts no dev server and needs no built output.
+
+The examples on this page use React. `@tanstack/solid-start` and `@tanstack/vue-start` export the same functions from the same subpaths.
+
+## Setup
+
+Add `tanstackStart()` to the config your tests use. An app can use one `vite.config.ts` for the app and for its tests:
+
+```ts title="vite.config.ts"
+import { defineConfig } from 'vitest/config'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import react from '@vitejs/plugin-react'
+import { playwright } from '@vitest/browser-playwright'
+
+export default defineConfig({
+ plugins: [tanstackStart(), react()],
+ test: {
+ projects: [
+ {
+ extends: true,
+ test: {
+ name: 'client',
+ include: ['tests/**/*.client.test.{ts,tsx}'],
+ browser: {
+ enabled: true,
+ provider: playwright(),
+ instances: [{ browser: 'chromium' }],
+ },
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: 'server',
+ environment: 'node',
+ include: ['tests/**/*.server.test.ts'],
+ },
+ },
+ ],
+ },
+})
+```
+
+The two projects and the file names are a convention of this example. A test file is compiled for the environment its project runs in.
+
+A package that only uses Start's APIs, such as a shared library of server functions, uses the same config. In a test run the plugin does not ask for a router entry or for routes.
+
+Start treats a run as a test run when Vitest resolves the config in its default mode, `test`. With another mode (`vitest --mode staging`) the plugin sets up the app's dev server as usual.
+
+## Which code a test gets
+
+| Test environment | Code the test gets |
+| ----------------------------------------------------------------------- | ------------------ |
+| [Browser mode](https://vitest.dev/guide/browser/), `jsdom`, `happy-dom` | Client |
+| `node` | Server |
+
+Take a module with an isomorphic function whose server implementation reads a secret:
+
+```ts title="src/runtime.ts"
+import { createIsomorphicFn } from '@tanstack/react-start'
+import { readSecret } from './secrets.server'
+
+export const describeRuntime = createIsomorphicFn()
+ .server(() => `server with ${readSecret()}`)
+ .client(() => 'client')
+```
+
+In a client test `describeRuntime()` returns `'client'`, and `./secrets.server` is never loaded. In a server test it runs the server implementation.
+
+`createServerOnlyFn` and `createClientOnlyFn` behave as in the app too: the function runs in its own environment and throws in the other one.
+
+## Routes in a test run
+
+A test can import a route file or the generated route tree.
+
+The route tree is generated once, when Vitest starts, and only for a project that has a router entry and a root route. It is not regenerated while Vitest watches. After you add, move or delete a route file, restart Vitest.
+
+A test run never writes to your route files. The dev server fills in an empty route file and corrects the path in a file you moved. A test run leaves both as they are and logs a warning.
+
+In client code a route loses its `server`, `ssr` and `headers` options, as in the app. That holds for every module that calls `createFileRoute`, `createRootRoute` or `createRootRouteWithContext`, including one outside the routes directory.
+
+## Mocking server functions in client tests
+
+A client test has no server. When client code calls a server function in a test run, no request is sent. The call goes to a mock that the test registered for that function with `mockServerFn`.
+
+Take a route whose loader gets a post from a server function:
+
+```ts title="src/posts.ts"
+import { notFound } from '@tanstack/react-router'
+import { createServerFn } from '@tanstack/react-start'
+import { findPost } from './db.server'
+
+export const fetchPost = createServerFn()
+ .validator((postId: string) => postId)
+ .handler(async ({ data }) => {
+ const post = await findPost(data)
+ if (!post) {
+ throw notFound()
+ }
+ return post
+ })
+```
+
+```tsx title="src/routes/posts.$postId.tsx"
+import { createFileRoute } from '@tanstack/react-router'
+import { fetchPost } from '../posts'
+
+export const Route = createFileRoute('/posts/$postId')({
+ loader: ({ params }) => fetchPost({ data: params.postId }),
+ component: PostPage,
+})
+
+function PostPage() {
+ const post = Route.useLoaderData()
+
+ return
{post.title}
+}
+```
+
+The test renders the route. The mock answers the loader's call in place of the server:
+
+```tsx title="tests/post-page.client.test.tsx"
+import { cleanup, render, screen } from '@testing-library/react'
+import {
+ RouterProvider,
+ createMemoryHistory,
+ createRouter,
+} from '@tanstack/react-router'
+import { mockServerFn } from '@tanstack/react-start/testing'
+import { afterEach, expect, test } from 'vitest'
+import { fetchPost } from '../src/posts'
+import { routeTree } from '../src/routeTree.gen'
+
+afterEach(() => {
+ cleanup()
+})
+
+test('the post page shows the title of the post', async () => {
+ mockServerFn(fetchPost, ({ data }) => ({
+ id: data,
+ title: 'Testing with TanStack Start',
+ }))
+ const router = createRouter({
+ routeTree,
+ history: createMemoryHistory({ initialEntries: ['/posts/42'] }),
+ })
+
+ render()
+
+ expect((await screen.findByRole('heading')).textContent).toBe(
+ 'Testing with TanStack Start',
+ )
+})
+```
+
+The mock stands for the server side of the function: its server middleware, its validator and its handler. It is called where the app would send the request, so the function's client middleware runs as in the app, before the mock and after it.
+
+A mock also answers a call that is made in the module that defines the server function. A module mock (`vi.mock`) cannot replace such a call, because it only changes what other modules import.
+
+A call to a server function that has no mock fails with an error that names the function:
+
+```
+The server function "fetchPost" (/src/posts.ts) was called in a client test, where no server runs. Answer the call with mockServerFn() before it is made.
+```
+
+### `mockServerFn(serverFn, mock)`
+
+Registers `mock` as the answer to every call of `serverFn`. A mock that a test registers ends with that test, see [How long a mock lasts](#how-long-a-mock-lasts). A second call for the same function replaces the first mock.
+
+`mock` is typed from the server function. It gets one object:
+
+| Property | Type | Value |
+| --------- | -------------------------- | ------------------------------------------------------------------------------ |
+| `data` | The function's input | The `data` of the call, as the caller passed it. The validator has not run. |
+| `method` | `'GET' \| 'POST'` | The method of the server function. |
+| `headers` | `Headers` | The headers of the call, with the ones the function's client middleware added. |
+| `signal` | `AbortSignal \| undefined` | The signal of the call. |
+
+`mock` returns what the call resolves to, or a promise for it. The return type is the handler's return type, literal types included: a mock of a handler that returns `{ status: 'ok' }` has to return exactly that. The value reaches the caller as it is. It is not passed through the serializer, so the test does not notice a value that the server could not send, such as a function.
+
+What `mock` throws rejects the call. To test how your code handles a redirect or a failed call, throw `redirect(...)` or an error in the mock.
+
+To check how a server function was called, pass a mock function of your test runner. Take a button that likes a post. `likePost` is a server function that takes the id of a post and returns its new number of likes:
+
+```tsx title="src/components/LikeButton.tsx"
+import { useState } from 'react'
+import { likePost } from '../posts'
+
+export function LikeButton({ postId }: { postId: string }) {
+ const [likes, setLikes] = useState()
+
+ return (
+
+ )
+}
+```
+
+```tsx title="tests/like-button.client.test.tsx"
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { mockServerFn } from '@tanstack/react-start/testing'
+import { afterEach, expect, test, vi } from 'vitest'
+import { LikeButton } from '../src/components/LikeButton'
+import { likePost } from '../src/posts'
+
+afterEach(() => {
+ cleanup()
+})
+
+test('likes the post and shows the new count', async () => {
+ const like = vi.fn(() => 5)
+ mockServerFn(likePost, like)
+ render()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Like' }))
+
+ expect(await screen.findByRole('button', { name: '5 likes' })).toBeDefined()
+ expect(like).toHaveBeenCalledWith(expect.objectContaining({ data: '42' }))
+})
+```
+
+`mockServerFn` works in client tests only. In a server test it throws, because the function was not compiled for the client. A server test runs the function itself, as the next section shows.
+
+### `resetServerFnMocks()`
+
+Removes every mock that `mockServerFn` registered. Start ends the mocks of a test when the test ends, so most tests never call it. Use it to remove mocks before a test ends, for example to check that a call without a mock fails.
+
+## Testing server functions and middleware in server tests
+
+In a server test your code runs as it does on the server, and a server function runs in full: its middleware, its validator and its handler. The helpers for server tests come from `@tanstack/react-start/testing/server`.
+
+### Calling a server function
+
+On the server, a server function runs for a request. It reads the cookies of that request, sets headers on the response, and gets context from the middleware that ran before it. A server function that a test calls outside of a request fails:
+
+```
+No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime. In a test, run this code inside runInRequest(), which the testing/server entry of your Start package exports (for example '@tanstack/react-start/testing/server').
+```
+
+`runInRequest` runs a callback as the code that handles one request to your server. Take `fetchPost` and `likePost` from above. `likePost` uses a middleware that finds the user of the session cookie:
+
+```ts title="src/middleware/auth.ts"
+import { createMiddleware } from '@tanstack/react-start'
+import { getCookie } from '@tanstack/react-start/server'
+import { findUserBySession } from '../db.server'
+
+export const authMiddleware = createMiddleware({ type: 'function' }).server(
+ async ({ next }) => {
+ const user = await findUserBySession(getCookie('session'))
+ if (!user) {
+ throw new Error('Not signed in')
+ }
+ return next({ context: { user } })
+ },
+)
+```
+
+```ts title="src/posts.ts"
+import { createServerFn } from '@tanstack/react-start'
+import { setResponseHeader } from '@tanstack/react-start/server'
+import { addLike } from './db.server'
+import { authMiddleware } from './middleware/auth'
+
+export const likePost = createServerFn({ method: 'POST' })
+ .middleware([authMiddleware])
+ .validator((postId: string) => postId)
+ .handler(async ({ data, context }) => {
+ setResponseHeader('cache-control', 'no-store')
+ // Counts each user once and returns the number of likes.
+ return addLike(data, context.user.id)
+ })
+```
+
+```ts title="tests/posts.server.test.ts"
+import { getResponseHeader } from '@tanstack/react-start/server'
+import { runInRequest } from '@tanstack/react-start/testing/server'
+import { expect, test } from 'vitest'
+import { fetchPost, likePost } from '../src/posts'
+
+test('fetchPost returns the post', async () => {
+ const post = await runInRequest(() => fetchPost({ data: '1' }))
+
+ expect(post.title).toBe('The first post')
+})
+
+test('fetchPost fails for a post that does not exist', async () => {
+ await expect(
+ runInRequest(() => fetchPost({ data: 'unknown' })),
+ ).rejects.toMatchObject({ isNotFound: true })
+})
+
+test('likePost counts a user once', async () => {
+ await runInRequest({ headers: { cookie: 'session=ada' } }, async () => {
+ expect(await likePost({ data: '1' })).toBe(1)
+ expect(await likePost({ data: '1' })).toBe(1)
+
+ expect(getResponseHeader('cache-control')).toBe('no-store')
+ })
+})
+
+test('likePost refuses a request without a session', async () => {
+ await expect(runInRequest(() => likePost({ data: '1' }))).rejects.toThrow(
+ 'Not signed in',
+ )
+})
+```
+
+The handlers in these tests use the real `./db.server`. A server test loads your server code as it is, so the test has to provide the data that code reads, for example a test database with a post `1` and a session `ada`.
+
+Each server function call inside the callback runs like a call that a loader makes while the server renders a page. The middleware of the function runs, client functions first and server functions after them, then the validator and the handler. The data and the result are passed as they are and do not go through the serializer.
+
+Start's request and response helpers work inside the callback: `getRequest`, `getCookie`, `setResponseHeader`, `getResponseHeader` and the other functions of `@tanstack/react-start/server`. A test can call several server functions in one request and check the response between the calls, as the third test does.
+
+### `runInRequest(options, callback)`
+
+Runs `callback` for one request. It resolves to what the callback returns and rejects with what the callback throws. `options` can be left out: `runInRequest(callback)`.
+
+| Option | Type | Value |
+| ------------------ | -------------------- | ----------------------------------------------------------------------------------------------------------------------- |
+| `url` | `string \| URL` | The URL of the request. A relative URL is resolved against `http://localhost`. The default is `/`. |
+| `method` | `string` | The method of the request. The default is `GET`. |
+| `headers` | `HeadersInit` | The headers of the request. Cookies go into the `cookie` header. |
+| `request` | `Request` | A request that is used as it is. It takes the place of `url`, `method` and `headers`. |
+| `context` | Your request context | The context your server entry passes to Start with a request. It is required when your app registers a request context. |
+| `globalMiddleware` | `'skip'` | Leaves out the middleware of `src/start.ts`. [Global middleware](#global-middleware) describes it. |
+
+The request counts as a request for a page. Request middleware gets `handlerType: 'router'`, so a middleware that only acts on server function requests lets it through. The CSRF middleware in its usual setup is one of them.
+
+`getRouterInstance()` returns the router of your router entry, at the URL of the request.
+
+### Global middleware
+
+`runInRequest` runs the request middleware of `src/start.ts` before the callback, and the function middleware of `src/start.ts` with each server function call. Take an app whose request middleware reads the language of the request:
+
+```ts title="src/start.ts"
+import { createMiddleware, createStart } from '@tanstack/react-start'
+
+type Locale = 'en' | 'de'
+
+const localeMiddleware = createMiddleware().server(({ next, request }) => {
+ const locale: Locale = request.headers
+ .get('accept-language')
+ ?.startsWith('de')
+ ? 'de'
+ : 'en'
+ return next({ context: { locale } })
+})
+
+export const startInstance = createStart(() => ({
+ requestMiddleware: [localeMiddleware],
+}))
+```
+
+If the handler of `fetchPost` looks the post up with `findPost(data, context.locale)`, a test chooses the language with a header:
+
+```ts
+test('fetchPost returns the post in the language of the request', async () => {
+ const post = await runInRequest(
+ { headers: { 'accept-language': 'de-DE' } },
+ () => fetchPost({ data: '1' }),
+ )
+
+ expect(post.title).toBe('Der erste Beitrag')
+})
+```
+
+When a request middleware answers the request itself or throws, the callback does not run and `runInRequest` rejects. It rejects with what the middleware threw, or with an error that has the middleware's response as its `cause`.
+
+To keep the global middleware out of a test, pass `globalMiddleware: 'skip'`. Neither list of `src/start.ts` runs then. `context` takes the place of the context the two lists pass on:
+
+```ts
+test('fetchPost returns the English post', async () => {
+ const post = await runInRequest(
+ { globalMiddleware: 'skip', context: { locale: 'en' } },
+ () => fetchPost({ data: '1' }),
+ )
+
+ expect(post.title).toBe('The first post')
+})
+```
+
+The type of `context` comes from your start instance. TypeScript reports a missing property and a value the middleware could not have produced, such as `locale: 'fr'` here. The option needs no reference to a middleware, so it also works for middleware that `src/start.ts` does not export. A server function that lists one of the global middleware itself still runs it.
+
+### `mockMiddleware(middleware, mock)`
+
+Replaces a middleware in server tests. `likePost` needs a session, and the test below puts a user in its place:
+
+```ts title="tests/posts.server.test.ts"
+import {
+ mockMiddleware,
+ runInRequest,
+} from '@tanstack/react-start/testing/server'
+import { expect, test } from 'vitest'
+import { authMiddleware } from '../src/middleware/auth'
+import { likePost } from '../src/posts'
+
+test('likePost counts the like of a user', async () => {
+ mockMiddleware(authMiddleware, ({ next }) =>
+ next({ context: { user: { id: 'u2', name: 'Grace' } } }),
+ )
+
+ await expect(runInRequest(() => likePost({ data: '2' }))).resolves.toBe(1)
+})
+```
+
+`mock` stands for the server function of the middleware and is typed from it. It gets what that function gets: `data`, `context`, `method`, `serverFnMeta`, `signal` and `next` for a function middleware, and `request`, `pathname`, `context`, `handlerType` and `next` for a request middleware.
+
+A mock goes on with the call by returning `next()`. When the middleware passes context on, `next` requires that context, because the code after the middleware reads it. A mock can also end the call the way the middleware can: by throwing, or by returning a `Response` in the mock of a request middleware.
+
+While a middleware is mocked, its client function does not run either. A server test would otherwise run that function in Node, where code written for a browser can fail.
+
+A mock registered inside the callback of `runInRequest` belongs to that request. It takes precedence over a mock of the test, and it ends with the request. If nothing in the request ran it, `runInRequest` rejects, because a mock that never runs usually means the test does not exercise what it was written for.
+
+The request middleware of `src/start.ts` has already run when the callback starts. Mock one of them before you call `runInRequest`.
+
+`mockMiddleware` replaces one middleware object. On the server, Start loads the file of a server function a second time, for the server side of the function. A middleware that is created in that file therefore exists twice, and a mock reaches only one of the two. Create a middleware that tests replace in a file of its own, like `src/middleware/auth.ts` above.
+
+### `runMiddleware(middleware, input, next)`
+
+Calls the server function of one middleware and nothing else. The middleware that it lists itself does not run, and neither does its validator or its client function. Call it inside `runInRequest`, which provides the request.
+
+```ts title="tests/auth.server.test.ts"
+import {
+ runInRequest,
+ runMiddleware,
+} from '@tanstack/react-start/testing/server'
+import { expect, test } from 'vitest'
+import { authMiddleware } from '../src/middleware/auth'
+
+test('authMiddleware passes the user of the session on', async () => {
+ await runInRequest({ headers: { cookie: 'session=ada' } }, async () => {
+ const { context } = await runMiddleware(authMiddleware, {})
+
+ expect(context.user).toEqual({ id: 'u1', name: 'Ada' })
+ })
+})
+
+test('authMiddleware refuses a request without a session', async () => {
+ await runInRequest(async () => {
+ await expect(runMiddleware(authMiddleware, {})).rejects.toThrow(
+ 'Not signed in',
+ )
+ })
+})
+```
+
+`input` is what the server function of the middleware receives. Its type comes from the middleware.
+
+| Property | For | Value |
+| -------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------ |
+| `data` | Function middleware | The validated data. It is required when the middleware or a middleware it lists has a validator. |
+| `context` | Both | The context of the middleware that runs before this one. It is required when that context has a required property. |
+| `method` | Function middleware | The method of the server function. The default is `GET`. |
+| `signal` | Function middleware | The signal of the call. The default is the signal of the request. |
+| `handlerType` | Request middleware | `'router'` for a page request, `'serverFn'` for a server function request. The default is `'router'`. |
+| `serverFnMeta` | Both | The id, the name and the file of the server function that the call is for. |
+
+`next` is optional. It stands for everything that runs after the middleware, and it gets what the middleware passed on. For a function middleware it gets `context` and `sendContext`, and what it returns is the result of the call. For a request middleware it gets `context`, `request` and `pathname`, and it returns the `Response` of the request. Without it, the response is an empty one with status 200.
+
+`runMiddleware` resolves to an object:
+
+| Property | For | Value |
+| ------------- | ------------------- | ----------------------------------------------------------------------------------------------- |
+| `context` | Both | The context after the middleware: what it received and what it added. |
+| `sendContext` | Function middleware | The context the middleware sends back to the client. |
+| `result` | Function middleware | What `next` returned. |
+| `response` | Request middleware | The response the middleware answers the request with: its own, or the one that `next` returned. |
+
+A request middleware often changes the response of the request. Take a middleware that derives a tenant from the host name:
+
+```ts title="src/middleware/tenant.ts"
+import { createMiddleware } from '@tanstack/react-start'
+
+export const tenantMiddleware = createMiddleware().server(
+ async ({ next, request }) => {
+ const tenant = new URL(request.url).hostname.split('.')[0]!
+ if (tenant === 'www') {
+ return new Response('No tenant', { status: 404 })
+ }
+ const result = await next({ context: { tenant } })
+ result.response.headers.set('x-tenant', tenant)
+ return result
+ },
+)
+```
+
+```ts title="tests/tenant.server.test.ts"
+import {
+ runInRequest,
+ runMiddleware,
+} from '@tanstack/react-start/testing/server'
+import { expect, test, vi } from 'vitest'
+import { tenantMiddleware } from '../src/middleware/tenant'
+
+test('tenantMiddleware names the tenant in the context and in a header', async () => {
+ await runInRequest({ url: 'https://acme.example.com/posts' }, async () => {
+ const { context, response } = await runMiddleware(
+ tenantMiddleware,
+ {},
+ ({ context }) => new Response(`Posts of ${context.tenant}`),
+ )
+
+ expect(context).toEqual({ tenant: 'acme' })
+ expect(response.headers.get('x-tenant')).toBe('acme')
+ await expect(response.text()).resolves.toBe('Posts of acme')
+ })
+})
+
+test('tenantMiddleware answers a request without a tenant itself', async () => {
+ await runInRequest({ url: 'https://www.example.com/posts' }, async () => {
+ const next = vi.fn()
+ const { response } = await runMiddleware(tenantMiddleware, {}, next)
+
+ expect(response.status).toBe(404)
+ expect(next).not.toHaveBeenCalled()
+ })
+})
+```
+
+A `Response` that a request middleware throws counts as its answer, as in the app, so `response` holds it. What a function middleware throws rejects the call.
+
+If `tenantMiddleware` is listed in `src/start.ts`, `runInRequest` also runs it for the request of the test, before the callback. For the second test that run would end the request. Such a test passes `globalMiddleware: 'skip'`.
+
+`runMiddleware` calls the real server function of a middleware, also while `mockMiddleware` replaces that middleware.
+
+## How long a mock lasts
+
+Start's plugin adds a setup file to every Vitest project. The file ends a mock of `mockServerFn` or `mockMiddleware` together with the test that registered it:
+
+- A mock registered in a test, or in a `beforeEach` hook, lasts until that test ends.
+- A mock registered at the top of a test file, or in a `beforeAll` hook, lasts for the whole file.
+- A mock registered with `mockMiddleware` inside the callback of `runInRequest` lasts until that request ends.
+
+Start adds the file through a plugin hook that Vitest has had since version 3.1.
+
+Tests that run at the same time (`test.concurrent`) share the mocks that are registered outside of `runInRequest`, and the first test that ends removes them for the others. In such tests, register a middleware mock inside the callback of `runInRequest`: each request keeps its own mocks. A mock of `mockServerFn` has no such scope, so concurrent client tests should not mock the same server function in different ways.
+
+## Limits
+
+- Vitest is the only supported test runner.
+- `runInRequest` sends no HTTP request. A server function call inside it skips the serializer, and a test cannot call a server route through it.
+- A test cannot call the handler of a server function without its middleware and its validator. To take a middleware out of the way, replace it with `mockMiddleware`.
+- `mockMiddleware` cannot replace a middleware that is created in the same file as a server function that uses it.
+- The route tree is not regenerated while Vitest watches.
diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md
index f373ecba4f..22c7d3ad92 100644
--- a/e2e/AGENTS.md
+++ b/e2e/AGENTS.md
@@ -7,3 +7,4 @@
- For new browser tests, reuse the local error-checking fixture. The shared `test` from `@tanstack/router-e2e-utils` fails on unexpected `console.error`, including hydration errors; allow only expected errors with `whitelistErrors`.
- HMR/watch tests edit real app sources. Reuse existing edit/restore helpers such as `createHmrFileEditor`, restore edits in teardown even after failures, and preserve the suites' single-worker and Nx `parallelism: false` settings.
- `@tanstack/router-e2e-utils:test:unit` is a placeholder. Validate helper changes through consuming e2e projects.
+- An e2e project resolves `@tanstack/*` to links into `packages/*`, which Vite and Vitest treat as source code: always compiled, never externalized. A user has them in `node_modules`. For changes to what our plugins tell a bundler or a test runner about dependencies (`resolve.noExternal`, `resolve.external`, `optimizeDeps`, inline lists), run the project as a user's project too with [`scripts/e2e/run-as-installed.mjs`](../scripts/e2e/run-as-installed.md); `e2e/react-start/vitest-*` do so in `test:e2e`.
diff --git a/e2e/react-start/vitest-app/.gitignore b/e2e/react-start/vitest-app/.gitignore
new file mode 100644
index 0000000000..e915670a21
--- /dev/null
+++ b/e2e/react-start/vitest-app/.gitignore
@@ -0,0 +1,7 @@
+node_modules
+.DS_Store
+dist
+.output
+.tanstack
+*.local
+__screenshots__
diff --git a/e2e/react-start/vitest-app/package.json b/e2e/react-start/vitest-app/package.json
new file mode 100644
index 0000000000..5ab825b383
--- /dev/null
+++ b/e2e/react-start/vitest-app/package.json
@@ -0,0 +1,44 @@
+{
+ "name": "tanstack-react-start-e2e-vitest-app",
+ "private": true,
+ "sideEffects": false,
+ "type": "module",
+ "scripts": {
+ "test:e2e": "pnpm run test:e2e:types && pnpm run test:e2e:linked && pnpm run test:e2e:cached && pnpm run test:e2e:installed",
+ "test:e2e:types": "tsc --noEmit",
+ "test:e2e:linked": "vitest --clearCache && vitest run",
+ "test:e2e:cached": "vitest run",
+ "test:e2e:installed": "node ../../../scripts/e2e/run-as-installed.mjs vitest run"
+ },
+ "dependencies": {
+ "@tanstack/react-router": "workspace:^",
+ "@tanstack/react-start": "workspace:^",
+ "react": "catalog:",
+ "react-dom": "catalog:"
+ },
+ "devDependencies": {
+ "@testing-library/react": "catalog:",
+ "@types/node": "^22.10.2",
+ "@types/react": "catalog:",
+ "@types/react-dom": "catalog:",
+ "@vitejs/plugin-react": "catalog:",
+ "@vitest/browser-playwright": "5.0.4",
+ "jsdom": "catalog:",
+ "playwright": "^1.63.0",
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
+ "vite": "catalog:",
+ "vitest": "catalog:"
+ },
+ "nx": {
+ "targets": {
+ "test:e2e": {
+ "inputs": [
+ "buildProduction",
+ "^production",
+ "dependentTaskOutputs",
+ "{workspaceRoot}/scripts/e2e/run-as-installed.mjs"
+ ]
+ }
+ }
+ }
+}
diff --git a/e2e/react-start/vitest-app/src/components/LikeButton.tsx b/e2e/react-start/vitest-app/src/components/LikeButton.tsx
new file mode 100644
index 0000000000..36a3864a1a
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/components/LikeButton.tsx
@@ -0,0 +1,12 @@
+import { useState } from 'react'
+import { likePost } from '../posts'
+
+export function LikeButton({ postId }: { postId: string }) {
+ const [likes, setLikes] = useState()
+
+ return (
+
+ )
+}
diff --git a/e2e/react-start/vitest-app/src/embedded/root.tsx b/e2e/react-start/vitest-app/src/embedded/root.tsx
new file mode 100644
index 0000000000..d7781ef5c5
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/embedded/root.tsx
@@ -0,0 +1,25 @@
+import { Outlet, createRootRoute } from '@tanstack/react-router'
+import { readSecret } from '../server-only'
+
+// The root of a second route tree that is built by hand, for a part of the
+// app that is embedded elsewhere. It is not in the routes directory, so the
+// route generator never sees this module.
+export const Route = createRootRoute({
+ // Only the server uses the three options below.
+ server: {
+ handlers: {
+ GET: () => new Response(readSecret()),
+ },
+ },
+ headers: () => ({ 'x-secret-length': String(readSecret().length) }),
+ ssr: 'data-only',
+ component: EmbeddedRoot,
+})
+
+function EmbeddedRoot() {
+ return (
+
+
+
+ )
+}
diff --git a/e2e/react-start/vitest-app/src/middleware/auth.ts b/e2e/react-start/vitest-app/src/middleware/auth.ts
new file mode 100644
index 0000000000..3adbc956e3
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/middleware/auth.ts
@@ -0,0 +1,13 @@
+import { createMiddleware } from '@tanstack/react-start'
+import { getCookie } from '@tanstack/react-start/server'
+import { findUserBySession } from '../server-only'
+
+export const authMiddleware = createMiddleware({ type: 'function' }).server(
+ ({ next }) => {
+ const user = findUserBySession(getCookie('session'))
+ if (!user) {
+ throw new Error('Not signed in')
+ }
+ return next({ context: { user } })
+ },
+)
diff --git a/e2e/react-start/vitest-app/src/posts.ts b/e2e/react-start/vitest-app/src/posts.ts
new file mode 100644
index 0000000000..90a13cb7e8
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/posts.ts
@@ -0,0 +1,23 @@
+import { notFound } from '@tanstack/react-router'
+import { createServerFn } from '@tanstack/react-start'
+import { setResponseHeader } from '@tanstack/react-start/server'
+import { authMiddleware } from './middleware/auth'
+import { addLike, findPost } from './server-only'
+
+export const fetchPost = createServerFn()
+ .validator((postId: string) => postId)
+ .handler(({ data, context }) => {
+ const post = findPost(data, context.locale)
+ if (!post) {
+ throw notFound()
+ }
+ return post
+ })
+
+export const likePost = createServerFn({ method: 'POST' })
+ .middleware([authMiddleware])
+ .validator((postId: string) => postId)
+ .handler(({ data, context }) => {
+ setResponseHeader('cache-control', 'no-store')
+ return addLike(data, context.user.id)
+ })
diff --git a/e2e/react-start/vitest-app/src/routeTree.gen.ts b/e2e/react-start/vitest-app/src/routeTree.gen.ts
new file mode 100644
index 0000000000..ae3849a161
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/routeTree.gen.ts
@@ -0,0 +1,105 @@
+/* eslint-disable */
+
+// @ts-nocheck
+
+// noinspection JSUnusedGlobalSymbols
+
+// This file was automatically generated by TanStack Router.
+// You should NOT make any changes in this file as it will be overwritten.
+// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
+
+import { Route as rootRouteImport } from './routes/__root'
+import { Route as IndexRouteImport } from './routes/index'
+import { Route as ApiHealthRouteImport } from './routes/api/health'
+import { Route as PostsPostIdRouteImport } from './routes/posts.$postId'
+
+const IndexRoute = IndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const ApiHealthRoute = ApiHealthRouteImport.update({
+ id: '/api/health',
+ path: '/api/health',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const PostsPostIdRoute = PostsPostIdRouteImport.update({
+ id: '/posts/$postId',
+ path: '/posts/$postId',
+ getParentRoute: () => rootRouteImport,
+} as any)
+
+export interface FileRoutesByFullPath {
+ '/': typeof IndexRoute
+ '/api/health': typeof ApiHealthRoute
+ '/posts/$postId': typeof PostsPostIdRoute
+}
+export interface FileRoutesByTo {
+ '/': typeof IndexRoute
+ '/api/health': typeof ApiHealthRoute
+ '/posts/$postId': typeof PostsPostIdRoute
+}
+export interface FileRoutesById {
+ __root__: typeof rootRouteImport
+ '/': typeof IndexRoute
+ '/api/health': typeof ApiHealthRoute
+ '/posts/$postId': typeof PostsPostIdRoute
+}
+export interface FileRouteTypes {
+ fileRoutesByFullPath: FileRoutesByFullPath
+ fullPaths: '/' | '/api/health' | '/posts/$postId'
+ fileRoutesByTo: FileRoutesByTo
+ to: '/' | '/api/health' | '/posts/$postId'
+ id: '__root__' | '/' | '/api/health' | '/posts/$postId'
+ fileRoutesById: FileRoutesById
+}
+export interface RootRouteChildren {
+ IndexRoute: typeof IndexRoute
+ ApiHealthRoute: typeof ApiHealthRoute
+ PostsPostIdRoute: typeof PostsPostIdRoute
+}
+
+declare module '@tanstack/react-router' {
+ interface FileRoutesByPath {
+ '/': {
+ id: '/'
+ path: '/'
+ fullPath: '/'
+ preLoaderRoute: typeof IndexRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/api/health': {
+ id: '/api/health'
+ path: '/api/health'
+ fullPath: '/api/health'
+ preLoaderRoute: typeof ApiHealthRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/posts/$postId': {
+ id: '/posts/$postId'
+ path: '/posts/$postId'
+ fullPath: '/posts/$postId'
+ preLoaderRoute: typeof PostsPostIdRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ }
+}
+
+const rootRouteChildren: RootRouteChildren = {
+ IndexRoute: IndexRoute,
+ ApiHealthRoute: ApiHealthRoute,
+ PostsPostIdRoute: PostsPostIdRoute,
+}
+export const routeTree = rootRouteImport
+ ._addFileChildren(rootRouteChildren)
+ ._addFileTypes()
+
+import type { getRouter } from './router.tsx'
+import type { startInstance } from './start.ts'
+declare module '@tanstack/react-start' {
+ interface Register {
+ ssr: true
+ router: Awaited>
+ config: Awaited>
+ }
+}
diff --git a/e2e/react-start/vitest-app/src/router.tsx b/e2e/react-start/vitest-app/src/router.tsx
new file mode 100644
index 0000000000..58f4d54e88
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/router.tsx
@@ -0,0 +1,6 @@
+import { createRouter } from '@tanstack/react-router'
+import { routeTree } from './routeTree.gen'
+
+export function getRouter() {
+ return createRouter({ routeTree })
+}
diff --git a/e2e/react-start/vitest-app/src/routes/__root.tsx b/e2e/react-start/vitest-app/src/routes/__root.tsx
new file mode 100644
index 0000000000..e835ba678f
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/routes/__root.tsx
@@ -0,0 +1,16 @@
+import { Link, Outlet, createRootRoute } from '@tanstack/react-router'
+
+export const Route = createRootRoute({
+ component: RootComponent,
+})
+
+function RootComponent() {
+ return (
+ <>
+
+
+ >
+ )
+}
diff --git a/e2e/react-start/vitest-app/src/routes/api/health.ts b/e2e/react-start/vitest-app/src/routes/api/health.ts
new file mode 100644
index 0000000000..961d0911ae
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/routes/api/health.ts
@@ -0,0 +1,11 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { readSecret } from '../../server-only'
+
+// A route with nothing for the client: Start leaves it out of the client's route tree.
+export const Route = createFileRoute('/api/health')({
+ server: {
+ handlers: {
+ GET: () => Response.json({ ok: true, secret: readSecret() }),
+ },
+ },
+})
diff --git a/e2e/react-start/vitest-app/src/routes/index.tsx b/e2e/react-start/vitest-app/src/routes/index.tsx
new file mode 100644
index 0000000000..db792756d1
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/routes/index.tsx
@@ -0,0 +1,16 @@
+import { Link, createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/')({
+ component: HomePage,
+})
+
+function HomePage() {
+ return (
+
+
Home
+
+ First post
+
+
+ )
+}
diff --git a/e2e/react-start/vitest-app/src/routes/posts.$postId.tsx b/e2e/react-start/vitest-app/src/routes/posts.$postId.tsx
new file mode 100644
index 0000000000..08987b34ce
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/routes/posts.$postId.tsx
@@ -0,0 +1,27 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { fetchPost } from '../posts'
+import { readSecret } from '../server-only'
+
+export const Route = createFileRoute('/posts/$postId')({
+ loader: ({ params }) => fetchPost({ data: params.postId }),
+ // Only the server uses the three options below.
+ server: {
+ handlers: {
+ POST: ({ params }) =>
+ Response.json({ postId: params.postId, secret: readSecret() }),
+ },
+ },
+ headers: () => ({ 'x-secret-length': String(readSecret().length) }),
+ ssr: 'data-only',
+ component: PostPage,
+})
+
+function PostPage() {
+ const post = Route.useLoaderData()
+
+ return (
+
+
{post.title}
+
+ )
+}
diff --git a/e2e/react-start/vitest-app/src/server-only.ts b/e2e/react-start/vitest-app/src/server-only.ts
new file mode 100644
index 0000000000..273722e9c5
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/server-only.ts
@@ -0,0 +1,58 @@
+// Stands for code that must never load in a browser: a database client, a
+// secret, a Node API. Loading it leaves a mark that tests can look for.
+declare global {
+ var __SERVER_ONLY_MODULE_LOADED__: boolean | undefined
+}
+
+globalThis.__SERVER_ONLY_MODULE_LOADED__ = true
+
+export function readSecret() {
+ return 'the server secret'
+}
+
+export type Locale = 'en' | 'de'
+
+export interface Post {
+ id: string
+ title: string
+}
+
+export interface User {
+ id: string
+ name: string
+}
+
+const posts = new Map>([
+ ['1', { en: 'The first post', de: 'Der erste Beitrag' }],
+ ['2', { en: 'The second post', de: 'Der zweite Beitrag' }],
+ ['3', { en: 'The third post', de: 'Der dritte Beitrag' }],
+])
+const users = new Map([['ada', { id: 'u1', name: 'Ada' }]])
+const likes = new Map>()
+const calls: Array = []
+
+export function findPost(id: string, locale: Locale): Post | undefined {
+ const titles = posts.get(id)
+ return titles && { id, title: titles[locale] }
+}
+
+/** The user of a session cookie. */
+export function findUserBySession(session: string | undefined) {
+ return session ? users.get(session) : undefined
+}
+
+/** Counts each user once. Returns the number of likes of the post. */
+export function addLike(postId: string, userId: string): number {
+ const users = likes.get(postId) ?? new Set()
+ likes.set(postId, users.add(userId))
+ return users.size
+}
+
+/** The audit log of the app: the server functions that were called. */
+export function recordCall(name: string) {
+ calls.push(name)
+}
+
+export function recordedCalls(): ReadonlyArray {
+ return calls
+}
diff --git a/e2e/react-start/vitest-app/src/start.ts b/e2e/react-start/vitest-app/src/start.ts
new file mode 100644
index 0000000000..7511caa077
--- /dev/null
+++ b/e2e/react-start/vitest-app/src/start.ts
@@ -0,0 +1,27 @@
+import { createMiddleware, createStart } from '@tanstack/react-start'
+import { recordCall } from './server-only'
+import type { Locale } from './server-only'
+
+// The global middleware of the app. It is not exported, as in most apps.
+// tests/posts.server.test.ts shows how a test runs it and how a test leaves
+// it out.
+const localeMiddleware = createMiddleware().server(({ next, request }) => {
+ const locale: Locale = request.headers
+ .get('accept-language')
+ ?.startsWith('de')
+ ? 'de'
+ : 'en'
+ return next({ context: { locale } })
+})
+
+const auditMiddleware = createMiddleware({ type: 'function' }).server(
+ ({ next, serverFnMeta }) => {
+ recordCall(serverFnMeta.name)
+ return next()
+ },
+)
+
+export const startInstance = createStart(() => ({
+ requestMiddleware: [localeMiddleware],
+ functionMiddleware: [auditMiddleware],
+}))
diff --git a/e2e/react-start/vitest-app/tests/jsdom.setup.ts b/e2e/react-start/vitest-app/tests/jsdom.setup.ts
new file mode 100644
index 0000000000..0af0e221e5
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/jsdom.setup.ts
@@ -0,0 +1,3 @@
+// jsdom has no layout, so it cannot scroll. The router scrolls to the top
+// after a navigation.
+window.scrollTo = () => {}
diff --git a/e2e/react-start/vitest-app/tests/like-button.client.test.tsx b/e2e/react-start/vitest-app/tests/like-button.client.test.tsx
new file mode 100644
index 0000000000..e36128e8d7
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/like-button.client.test.tsx
@@ -0,0 +1,21 @@
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { mockServerFn } from '@tanstack/react-start/testing'
+import { afterEach, expect, test, vi } from 'vitest'
+import { LikeButton } from '../src/components/LikeButton'
+import { likePost } from '../src/posts'
+
+afterEach(() => {
+ cleanup()
+})
+
+test('a component sends its data to a server function and shows the answer', async () => {
+ const like = vi.fn(() => 5)
+ mockServerFn(likePost, like)
+ render()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Like' }))
+
+ expect(await screen.findByRole('button', { name: '5 likes' })).toBeDefined()
+ expect(like).toHaveBeenCalledOnce()
+ expect(like).toHaveBeenCalledWith(expect.objectContaining({ data: '42' }))
+})
diff --git a/e2e/react-start/vitest-app/tests/posts.server.test.ts b/e2e/react-start/vitest-app/tests/posts.server.test.ts
new file mode 100644
index 0000000000..fb3af174dc
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/posts.server.test.ts
@@ -0,0 +1,113 @@
+import { getRouterInstance } from '@tanstack/react-start'
+import { getResponseHeader } from '@tanstack/react-start/server'
+import {
+ mockMiddleware,
+ runInRequest,
+ runMiddleware,
+} from '@tanstack/react-start/testing/server'
+import { expect, test } from 'vitest'
+import { authMiddleware } from '../src/middleware/auth'
+import { fetchPost, likePost } from '../src/posts'
+import { recordedCalls } from '../src/server-only'
+
+test('runInRequest resolves to what a server function returns', async () => {
+ const post = await runInRequest(() => fetchPost({ data: '1' }))
+
+ expect(post.title).toBe('The first post')
+})
+
+test('a server function runs behind the global middleware of src/start.ts', async () => {
+ const post = await runInRequest(
+ { headers: { 'accept-language': 'de-DE' } },
+ () => fetchPost({ data: '1' }),
+ )
+
+ expect(post).toEqual({ id: '1', title: 'Der erste Beitrag' })
+ // (the global function middleware of the app wrote its audit log)
+ expect(recordedCalls()).toContain('fetchPost')
+})
+
+test('a server function fails as in the app', async () => {
+ await expect(
+ runInRequest(() => fetchPost({ data: 'unknown' })),
+ ).rejects.toMatchObject({ isNotFound: true })
+})
+
+test('a test checks between two calls and reads what a handler set on the response', async () => {
+ await runInRequest({ headers: { cookie: 'session=ada' } }, async () => {
+ expect(await likePost({ data: '1' })).toBe(1)
+ // (a user counts once)
+ expect(await likePost({ data: '1' })).toBe(1)
+
+ expect(getResponseHeader('cache-control')).toBe('no-store')
+ })
+})
+
+test('the middleware of a server function refuses a request without a session', async () => {
+ await expect(runInRequest(() => likePost({ data: '1' }))).rejects.toThrow(
+ 'Not signed in',
+ )
+})
+
+test('mockMiddleware puts a user of the test in place of the session', async () => {
+ mockMiddleware(authMiddleware, ({ next }) =>
+ next({ context: { user: { id: 'u2', name: 'Grace' } } }),
+ )
+
+ await expect(runInRequest(() => likePost({ data: '2' }))).resolves.toBe(1)
+})
+
+test('runMiddleware calls a middleware on its own', async () => {
+ await runInRequest({ headers: { cookie: 'session=ada' } }, async () => {
+ const { context } = await runMiddleware(authMiddleware, {})
+
+ expect(context.user).toEqual({ id: 'u1', name: 'Ada' })
+ })
+
+ await runInRequest(async () => {
+ await expect(runMiddleware(authMiddleware, {})).rejects.toThrow(
+ 'Not signed in',
+ )
+ })
+})
+
+test('globalMiddleware: skip leaves the middleware of src/start.ts out', async () => {
+ const callsBefore = recordedCalls().length
+
+ const post = await runInRequest(
+ {
+ // (the header would make the request middleware choose German)
+ headers: { 'accept-language': 'de-DE' },
+ globalMiddleware: 'skip',
+ context: { locale: 'en' },
+ },
+ () => fetchPost({ data: '3' }),
+ )
+
+ expect(post.title).toBe('The third post')
+ expect(recordedCalls()).toHaveLength(callsBefore)
+})
+
+test('the context that stands for the global middleware is typed', () => {
+ // Checked by `tsc` (`test:e2e:types`), never called.
+ const check = () => [
+ // @ts-expect-error the request middleware of src/start.ts passes a locale on
+ runInRequest({ globalMiddleware: 'skip' }, () => undefined),
+ runInRequest(
+ // @ts-expect-error the app has no French
+ { globalMiddleware: 'skip', context: { locale: 'fr' } },
+ () => undefined,
+ ),
+ ]
+
+ expect(check).toBeTypeOf('function')
+})
+
+test('the router of the app is at the URL of the request', async () => {
+ await runInRequest({ url: '/posts/1?from=test' }, async () => {
+ const router = await getRouterInstance()
+
+ expect(router.history.location.href).toBe('/posts/1?from=test')
+ expect(Object.keys(router.routesById)).toContain('/posts/$postId')
+ })
+})
diff --git a/e2e/react-start/vitest-app/tests/route-files.client.test.ts b/e2e/react-start/vitest-app/tests/route-files.client.test.ts
new file mode 100644
index 0000000000..5fa2dc4820
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/route-files.client.test.ts
@@ -0,0 +1,12 @@
+import { expect, test } from 'vitest'
+import { Route as HealthRoute } from '../src/routes/api/health'
+import { Route as PostRoute } from '../src/routes/posts.$postId'
+
+test('the options that only the server uses are not in client code', () => {
+ expect(Object.keys(PostRoute.options).sort()).toEqual(['component', 'loader'])
+ expect(Object.keys(HealthRoute.options)).toEqual([])
+})
+
+test('the module that only server code uses is never loaded', () => {
+ expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined()
+})
diff --git a/e2e/react-start/vitest-app/tests/route-files.server.test.ts b/e2e/react-start/vitest-app/tests/route-files.server.test.ts
new file mode 100644
index 0000000000..c3b4d60113
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/route-files.server.test.ts
@@ -0,0 +1,25 @@
+import { expect, test } from 'vitest'
+import { Route as HealthRoute } from '../src/routes/api/health'
+import { Route as PostRoute } from '../src/routes/posts.$postId'
+
+test('the options that only the server uses are in server code', () => {
+ expect(Object.keys(PostRoute.options).sort()).toEqual([
+ 'component',
+ 'headers',
+ 'loader',
+ 'server',
+ 'ssr',
+ ])
+})
+
+test('a server route handler can be called', async () => {
+ const { handlers } = (HealthRoute.options as any).server
+ const response: Response = await handlers.GET({
+ request: new Request('http://localhost/api/health'),
+ })
+
+ expect(await response.json()).toEqual({
+ ok: true,
+ secret: 'the server secret',
+ })
+})
diff --git a/e2e/react-start/vitest-app/tests/route-modules.client.test.ts b/e2e/react-start/vitest-app/tests/route-modules.client.test.ts
new file mode 100644
index 0000000000..22db660d3b
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/route-modules.client.test.ts
@@ -0,0 +1,10 @@
+import { expect, test } from 'vitest'
+import { Route } from '../src/embedded/root'
+
+test('a route module outside the routes directory has no server-only options in client code', () => {
+ expect(Object.keys(Route.options)).toEqual(['component'])
+})
+
+test('the module that only server code uses is never loaded', () => {
+ expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined()
+})
diff --git a/e2e/react-start/vitest-app/tests/route-modules.server.test.ts b/e2e/react-start/vitest-app/tests/route-modules.server.test.ts
new file mode 100644
index 0000000000..231372b0fb
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/route-modules.server.test.ts
@@ -0,0 +1,11 @@
+import { expect, test } from 'vitest'
+import { Route } from '../src/embedded/root'
+
+test('a route module outside the routes directory keeps its server-only options in server code', () => {
+ expect(Object.keys(Route.options).sort()).toEqual([
+ 'component',
+ 'headers',
+ 'server',
+ 'ssr',
+ ])
+})
diff --git a/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx b/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx
new file mode 100644
index 0000000000..f0018c1074
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx
@@ -0,0 +1,42 @@
+import { cleanup, render, screen } from '@testing-library/react'
+import {
+ RouterProvider,
+ createMemoryHistory,
+ createRouter,
+} from '@tanstack/react-router'
+import { mockServerFn } from '@tanstack/react-start/testing'
+import { afterEach, expect, test } from 'vitest'
+import { fetchPost } from '../src/posts'
+import { routeTree } from '../src/routeTree.gen'
+
+afterEach(() => {
+ cleanup()
+})
+
+test('the route tree of the client has no server-only route', () => {
+ const router = createRouter({ routeTree, history: createMemoryHistory() })
+
+ expect(Object.keys(router.routesById).sort()).toEqual([
+ '/',
+ '/posts/$postId',
+ '__root__',
+ ])
+})
+
+test('a route renders what its loader gets from a server function', async () => {
+ mockServerFn(fetchPost, ({ data }) => ({
+ id: data,
+ title: 'Testing with TanStack Start',
+ }))
+ const router = createRouter({
+ routeTree,
+ history: createMemoryHistory({ initialEntries: ['/posts/42'] }),
+ })
+
+ render()
+
+ expect((await screen.findByRole('heading')).textContent).toBe(
+ 'Testing with TanStack Start',
+ )
+ expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined()
+})
diff --git a/e2e/react-start/vitest-app/tests/route-tree.server.test.ts b/e2e/react-start/vitest-app/tests/route-tree.server.test.ts
new file mode 100644
index 0000000000..cc47994485
--- /dev/null
+++ b/e2e/react-start/vitest-app/tests/route-tree.server.test.ts
@@ -0,0 +1,14 @@
+import { createMemoryHistory, createRouter } from '@tanstack/react-router'
+import { expect, test } from 'vitest'
+import { routeTree } from '../src/routeTree.gen'
+
+test('the route tree of the server has every route', () => {
+ const router = createRouter({ routeTree, history: createMemoryHistory() })
+
+ expect(Object.keys(router.routesById).sort()).toEqual([
+ '/',
+ '/api/health',
+ '/posts/$postId',
+ '__root__',
+ ])
+})
diff --git a/e2e/react-start/vitest-app/tsconfig.json b/e2e/react-start/vitest-app/tsconfig.json
new file mode 100644
index 0000000000..279e9c623c
--- /dev/null
+++ b/e2e/react-start/vitest-app/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "noEmit": true,
+ "types": ["node", "vite/client"]
+ },
+ "include": ["src", "tests", "vite.config.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/e2e/react-start/vitest-app/vite.config.ts b/e2e/react-start/vitest-app/vite.config.ts
new file mode 100644
index 0000000000..26c913082e
--- /dev/null
+++ b/e2e/react-start/vitest-app/vite.config.ts
@@ -0,0 +1,58 @@
+import { defineConfig } from 'vitest/config'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import react from '@vitejs/plugin-react'
+import { playwright } from '@vitest/browser-playwright'
+
+// A Start app. The same config serves the app and its tests.
+//
+// `test:e2e` type-checks the project and runs these tests three times:
+// - here, where `@tanstack/*` are links to `packages/*`, with an empty Vitest
+// cache (`test:e2e:linked`),
+// - here again, now with the compiled modules of the first run in Vitest's
+// cache (`test:e2e:cached`): a test run must not depend on the Start
+// compiler having seen a file in the same process,
+// - in a copy that is installed like a user's project
+// (`test:e2e:installed`, `scripts/e2e/run-as-installed.md` says why that
+// differs).
+export default defineConfig({
+ plugins: [tanstackStart(), react()],
+ test: {
+ watch: false,
+ // Vitest keeps the modules it compiled in one cache for the whole
+ // repository. This project keeps its own, so that `test:e2e:linked` can
+ // empty it and compile every file with the packages as they are built now.
+ fsModuleCachePath: 'node_modules/.vitest-cache',
+ projects: [
+ {
+ extends: true,
+ test: {
+ name: 'browser',
+ include: ['tests/**/*.client.test.ts?(x)'],
+ browser: {
+ enabled: true,
+ headless: true,
+ provider: playwright(),
+ instances: [{ browser: 'chromium' }],
+ },
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: 'jsdom',
+ environment: 'jsdom',
+ include: ['tests/**/*.client.test.ts?(x)'],
+ setupFiles: ['tests/jsdom.setup.ts'],
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: 'node',
+ environment: 'node',
+ include: ['tests/**/*.server.test.ts'],
+ },
+ },
+ ],
+ },
+})
diff --git a/e2e/react-start/vitest-library/.gitignore b/e2e/react-start/vitest-library/.gitignore
new file mode 100644
index 0000000000..e915670a21
--- /dev/null
+++ b/e2e/react-start/vitest-library/.gitignore
@@ -0,0 +1,7 @@
+node_modules
+.DS_Store
+dist
+.output
+.tanstack
+*.local
+__screenshots__
diff --git a/e2e/react-start/vitest-library/package.json b/e2e/react-start/vitest-library/package.json
new file mode 100644
index 0000000000..920dcc4ef5
--- /dev/null
+++ b/e2e/react-start/vitest-library/package.json
@@ -0,0 +1,42 @@
+{
+ "name": "tanstack-react-start-e2e-vitest-library",
+ "private": true,
+ "sideEffects": false,
+ "type": "module",
+ "scripts": {
+ "test:e2e": "pnpm run test:e2e:types && pnpm run test:e2e:linked && pnpm run test:e2e:cached && pnpm run test:e2e:installed",
+ "test:e2e:types": "tsc --noEmit",
+ "test:e2e:linked": "vitest --clearCache && vitest run",
+ "test:e2e:cached": "vitest run",
+ "test:e2e:installed": "node ../../../scripts/e2e/run-as-installed.mjs vitest run"
+ },
+ "dependencies": {
+ "@tanstack/react-start": "workspace:^",
+ "react": "catalog:",
+ "react-dom": "catalog:"
+ },
+ "devDependencies": {
+ "@types/node": "^22.10.2",
+ "@types/react": "catalog:",
+ "@types/react-dom": "catalog:",
+ "@vitejs/plugin-react": "catalog:",
+ "@vitest/browser-playwright": "5.0.4",
+ "jsdom": "catalog:",
+ "playwright": "^1.63.0",
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
+ "vite": "catalog:",
+ "vitest": "catalog:"
+ },
+ "nx": {
+ "targets": {
+ "test:e2e": {
+ "inputs": [
+ "buildProduction",
+ "^production",
+ "dependentTaskOutputs",
+ "{workspaceRoot}/scripts/e2e/run-as-installed.mjs"
+ ]
+ }
+ }
+ }
+}
diff --git a/e2e/react-start/vitest-library/src/account.ts b/e2e/react-start/vitest-library/src/account.ts
new file mode 100644
index 0000000000..a6663262be
--- /dev/null
+++ b/e2e/react-start/vitest-library/src/account.ts
@@ -0,0 +1,10 @@
+import { createServerFn } from '@tanstack/react-start'
+import { setResponseHeader } from '@tanstack/react-start/server'
+import { sessionMiddleware } from './session'
+
+export const getAccount = createServerFn()
+ .middleware([sessionMiddleware])
+ .handler(({ context }) => {
+ setResponseHeader('cache-control', 'private')
+ return { name: context.user }
+ })
diff --git a/e2e/react-start/vitest-library/src/greeting.ts b/e2e/react-start/vitest-library/src/greeting.ts
new file mode 100644
index 0000000000..fb3cf17136
--- /dev/null
+++ b/e2e/react-start/vitest-library/src/greeting.ts
@@ -0,0 +1,24 @@
+import { createMiddleware, createServerFn } from '@tanstack/react-start'
+import { readSecret } from './server-only'
+
+export const secretMiddleware = createMiddleware({ type: 'function' })
+ .client(({ next }) => next({ headers: { 'x-greeting': 'from the client' } }))
+ .server(({ next }) => next({ context: { secret: readSecret() } }))
+
+export const greet = createServerFn({ method: 'POST' })
+ .middleware([secretMiddleware])
+ .validator((name: string) => {
+ if (!name) {
+ throw new Error('A name is required')
+ }
+ return name
+ })
+ // (typed as a string: a mock returns the type of the handler, and the type
+ // of this template would be `Hello ${string}, ${string}`)
+ .handler(({ data, context }): string => `Hello ${data}, ${context.secret}`)
+
+// Stands for a route loader or a component in the file that defines the
+// server function it calls.
+export function welcome(name: string) {
+ return greet({ data: name })
+}
diff --git a/e2e/react-start/vitest-library/src/runtime.ts b/e2e/react-start/vitest-library/src/runtime.ts
new file mode 100644
index 0000000000..4137c7802d
--- /dev/null
+++ b/e2e/react-start/vitest-library/src/runtime.ts
@@ -0,0 +1,14 @@
+import {
+ createClientOnlyFn,
+ createIsomorphicFn,
+ createServerOnlyFn,
+} from '@tanstack/react-start'
+import { readSecret } from './server-only'
+
+export const describeRuntime = createIsomorphicFn()
+ .server(() => `server with ${readSecret()}`)
+ .client(() => 'client')
+
+export const getSecret = createServerOnlyFn(() => readSecret())
+
+export const getLanguage = createClientOnlyFn(() => navigator.language)
diff --git a/e2e/react-start/vitest-library/src/server-only.ts b/e2e/react-start/vitest-library/src/server-only.ts
new file mode 100644
index 0000000000..106cd6e23a
--- /dev/null
+++ b/e2e/react-start/vitest-library/src/server-only.ts
@@ -0,0 +1,11 @@
+// Stands for code that must never load in a browser: a database client, a
+// secret, a Node API. Loading it leaves a mark that tests can look for.
+declare global {
+ var __SERVER_ONLY_MODULE_LOADED__: boolean | undefined
+}
+
+globalThis.__SERVER_ONLY_MODULE_LOADED__ = true
+
+export function readSecret() {
+ return 'the server secret'
+}
diff --git a/e2e/react-start/vitest-library/src/session.ts b/e2e/react-start/vitest-library/src/session.ts
new file mode 100644
index 0000000000..24566aa4d5
--- /dev/null
+++ b/e2e/react-start/vitest-library/src/session.ts
@@ -0,0 +1,23 @@
+import { createMiddleware } from '@tanstack/react-start'
+import { getCookie } from '@tanstack/react-start/server'
+
+// A middleware in a file of its own, so that a test can replace it with
+// `mockMiddleware` (see tests/account.server.test.ts).
+export const sessionMiddleware = createMiddleware({ type: 'function' })
+ .client(({ next }) => {
+ // Stands for client code that needs a browser. A server test runs the
+ // client function of a middleware first, as server rendering does.
+ globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__ = true
+ return next()
+ })
+ .server(({ next }) => {
+ const user = getCookie('session')
+ if (!user) {
+ throw new Error('Not signed in')
+ }
+ return next({ context: { user } })
+ })
+
+declare global {
+ var __SESSION_CLIENT_MIDDLEWARE_RAN__: boolean | undefined
+}
diff --git a/e2e/react-start/vitest-library/src/tenant.ts b/e2e/react-start/vitest-library/src/tenant.ts
new file mode 100644
index 0000000000..08f6b9a594
--- /dev/null
+++ b/e2e/react-start/vitest-library/src/tenant.ts
@@ -0,0 +1,15 @@
+import { createMiddleware } from '@tanstack/react-start'
+
+// A request middleware: it runs for every request, before any route or
+// server function. tests/tenant.server.test.ts runs it on its own.
+export const tenantMiddleware = createMiddleware().server(
+ async ({ next, request }) => {
+ const tenant = new URL(request.url).hostname.split('.')[0]!
+ if (tenant === 'www') {
+ return new Response('No tenant', { status: 404 })
+ }
+ const result = await next({ context: { tenant } })
+ result.response.headers.set('x-tenant', tenant)
+ return result
+ },
+)
diff --git a/e2e/react-start/vitest-library/tests/account.server.test.ts b/e2e/react-start/vitest-library/tests/account.server.test.ts
new file mode 100644
index 0000000000..069f83e4df
--- /dev/null
+++ b/e2e/react-start/vitest-library/tests/account.server.test.ts
@@ -0,0 +1,97 @@
+import { getRouterInstance } from '@tanstack/react-start'
+import { getResponseHeader } from '@tanstack/react-start/server'
+import {
+ mockMiddleware,
+ runInRequest,
+ runMiddleware,
+} from '@tanstack/react-start/testing/server'
+import { beforeEach, expect, test } from 'vitest'
+import { getAccount } from '../src/account'
+import { sessionMiddleware } from '../src/session'
+
+beforeEach(() => {
+ globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__ = undefined
+})
+
+test('a server function cannot be called outside of a request', async () => {
+ await expect(getAccount()).rejects.toThrow(
+ /No Start context found.*runInRequest\(\)/,
+ )
+})
+
+test('a server function runs its middleware and its handler for the request of the test', async () => {
+ await runInRequest({ headers: { cookie: 'session=ada' } }, async () => {
+ await expect(getAccount()).resolves.toEqual({ name: 'ada' })
+
+ expect(getResponseHeader('cache-control')).toBe('private')
+ })
+ // (as during server rendering, the client function of the middleware ran)
+ expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBe(true)
+})
+
+test('runInRequest resolves to what the callback returns', async () => {
+ const account = await runInRequest(
+ { headers: { cookie: 'session=ada' } },
+ () => getAccount(),
+ )
+
+ expect(account).toEqual({ name: 'ada' })
+})
+
+test('a server function fails as in the app when its middleware refuses the request', async () => {
+ await expect(runInRequest(() => getAccount())).rejects.toThrow(
+ 'Not signed in',
+ )
+})
+
+test('mockMiddleware replaces a middleware, its client function included', async () => {
+ mockMiddleware(sessionMiddleware, ({ next }) =>
+ next({ context: { user: 'grace' } }),
+ )
+
+ await expect(runInRequest(() => getAccount())).resolves.toEqual({
+ name: 'grace',
+ })
+ expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBeUndefined()
+})
+
+test('a mock ends with the test that registered it', async () => {
+ await expect(runInRequest(() => getAccount())).rejects.toThrow(
+ 'Not signed in',
+ )
+})
+
+test('a mock registered inside a request ends with that request', async () => {
+ await runInRequest(async () => {
+ mockMiddleware(sessionMiddleware, ({ next }) =>
+ next({ context: { user: 'grace' } }),
+ )
+
+ await expect(getAccount()).resolves.toEqual({ name: 'grace' })
+ })
+
+ await expect(runInRequest(() => getAccount())).rejects.toThrow(
+ 'Not signed in',
+ )
+})
+
+test('runMiddleware calls the server function of one middleware', async () => {
+ await runInRequest({ headers: { cookie: 'session=ada' } }, async () => {
+ const { context } = await runMiddleware(sessionMiddleware, {})
+
+ expect(context).toEqual({ user: 'ada' })
+ })
+
+ await runInRequest(async () => {
+ await expect(runMiddleware(sessionMiddleware, {})).rejects.toThrow(
+ 'Not signed in',
+ )
+ })
+ expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBeUndefined()
+})
+
+test('a project without a router entry has no router in a request', async () => {
+ await expect(runInRequest(() => getRouterInstance())).rejects.toThrow(
+ 'This project has no router entry',
+ )
+})
diff --git a/e2e/react-start/vitest-library/tests/greeting.client.test.ts b/e2e/react-start/vitest-library/tests/greeting.client.test.ts
new file mode 100644
index 0000000000..9f58c5d6f4
--- /dev/null
+++ b/e2e/react-start/vitest-library/tests/greeting.client.test.ts
@@ -0,0 +1,39 @@
+import { mockServerFn } from '@tanstack/react-start/testing'
+import { expect, test } from 'vitest'
+import { greet, welcome } from '../src/greeting'
+
+test('a mock answers the call with the data of the call', async () => {
+ mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`)
+
+ await expect(greet({ data: 'Ada' })).resolves.toBe('Hello Ada, from the mock')
+})
+
+// The test above registered a mock. Start's setup file ended it with that
+// test, so no test of this file removes mocks itself.
+test('a server function call without a mock fails with an error that names the function', async () => {
+ await expect(greet({ data: 'Ada' })).rejects.toThrow(
+ 'The server function "greet" (/src/greeting.ts) was called in a client test, where no server runs.',
+ )
+})
+
+test('a mock answers a call that is made in the file of the server function', async () => {
+ mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`)
+
+ await expect(welcome('Ada')).resolves.toBe('Hello Ada, from the mock')
+})
+
+test("the function's client middleware runs before the mock", async () => {
+ let header: string | null = null
+ mockServerFn(greet, ({ data, headers }) => {
+ header = headers.get('x-greeting')
+ return `Hello ${data}, from the mock`
+ })
+
+ await greet({ data: 'Ada' })
+
+ expect(header).toBe('from the client')
+})
+
+test('the handler, the validator and the server middleware are not in the client code', () => {
+ expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined()
+})
diff --git a/e2e/react-start/vitest-library/tests/greeting.server.test.ts b/e2e/react-start/vitest-library/tests/greeting.server.test.ts
new file mode 100644
index 0000000000..ce80023cdc
--- /dev/null
+++ b/e2e/react-start/vitest-library/tests/greeting.server.test.ts
@@ -0,0 +1,50 @@
+import { mockServerFn } from '@tanstack/react-start/testing'
+import {
+ mockMiddleware,
+ runInRequest,
+} from '@tanstack/react-start/testing/server'
+import { expect, test } from 'vitest'
+import { greet, secretMiddleware, welcome } from '../src/greeting'
+
+test('a server function runs its middleware, its validator and its handler', async () => {
+ await expect(runInRequest(() => greet({ data: 'Ada' }))).resolves.toBe(
+ 'Hello Ada, the server secret',
+ )
+})
+
+test('a call that is made in the file of the server function runs it as well', async () => {
+ await expect(runInRequest(() => welcome('Ada'))).resolves.toBe(
+ 'Hello Ada, the server secret',
+ )
+})
+
+test('the validator of a server function rejects bad input', async () => {
+ await expect(runInRequest(() => greet({ data: '' }))).rejects.toThrow(
+ 'A name is required',
+ )
+})
+
+// On the server a server function runs for real. There is no request that a
+// mock could answer.
+test('mockServerFn refuses a server function in a server test', () => {
+ expect(() =>
+ mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`),
+ ).toThrow(
+ 'mockServerFn() needs a server function that the Start compiler compiled for a client test',
+ )
+})
+
+// `secretMiddleware` is created in the file of `greet`. The server loads that
+// file a second time for the server side of `greet`, with a middleware object
+// of its own, which the mock does not reach.
+test('a middleware that is created in the file of its server function cannot be mocked', async () => {
+ await expect(
+ runInRequest(async () => {
+ mockMiddleware(secretMiddleware, ({ next }) =>
+ next({ context: { secret: 'a mocked secret' } }),
+ )
+
+ await greet({ data: 'Ada' })
+ }),
+ ).rejects.toThrow('Create the middleware in a file of its own to mock it.')
+})
diff --git a/e2e/react-start/vitest-library/tests/runtime.client.test.ts b/e2e/react-start/vitest-library/tests/runtime.client.test.ts
new file mode 100644
index 0000000000..56cd4f4bdc
--- /dev/null
+++ b/e2e/react-start/vitest-library/tests/runtime.client.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from 'vitest'
+import { describeRuntime, getLanguage, getSecret } from '../src/runtime'
+
+test('an isomorphic function runs its client implementation', () => {
+ expect(describeRuntime()).toBe('client')
+})
+
+test('a client-only function runs', () => {
+ expect(getLanguage()).toBe(navigator.language)
+})
+
+test('a server-only function throws', () => {
+ expect(() => getSecret()).toThrow()
+})
+
+test('the module that only server code uses is never loaded', () => {
+ expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined()
+})
diff --git a/e2e/react-start/vitest-library/tests/runtime.server.test.ts b/e2e/react-start/vitest-library/tests/runtime.server.test.ts
new file mode 100644
index 0000000000..4d6204ed3a
--- /dev/null
+++ b/e2e/react-start/vitest-library/tests/runtime.server.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from 'vitest'
+import { describeRuntime, getLanguage, getSecret } from '../src/runtime'
+
+test('an isomorphic function runs its server implementation', () => {
+ expect(describeRuntime()).toBe('server with the server secret')
+})
+
+test('a server-only function runs', () => {
+ expect(getSecret()).toBe('the server secret')
+})
+
+test('a client-only function throws', () => {
+ expect(() => getLanguage()).toThrow()
+})
+
+test('the module that server code uses is loaded', () => {
+ expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBe(true)
+})
diff --git a/e2e/react-start/vitest-library/tests/tenant.server.test.ts b/e2e/react-start/vitest-library/tests/tenant.server.test.ts
new file mode 100644
index 0000000000..3636b8875d
--- /dev/null
+++ b/e2e/react-start/vitest-library/tests/tenant.server.test.ts
@@ -0,0 +1,30 @@
+import {
+ runInRequest,
+ runMiddleware,
+} from '@tanstack/react-start/testing/server'
+import { expect, test, vi } from 'vitest'
+import { tenantMiddleware } from '../src/tenant'
+
+test('a request middleware passes context on and can change the response', async () => {
+ await runInRequest({ url: 'https://acme.example.com/posts' }, async () => {
+ const { context, response } = await runMiddleware(
+ tenantMiddleware,
+ {},
+ ({ context }) => new Response(`Posts of ${context.tenant}`),
+ )
+
+ expect(context).toEqual({ tenant: 'acme' })
+ expect(response.headers.get('x-tenant')).toBe('acme')
+ await expect(response.text()).resolves.toBe('Posts of acme')
+ })
+})
+
+test('a request middleware can answer the request itself', async () => {
+ await runInRequest({ url: 'https://www.example.com/posts' }, async () => {
+ const next = vi.fn()
+ const { response } = await runMiddleware(tenantMiddleware, {}, next)
+
+ expect(response.status).toBe(404)
+ expect(next).not.toHaveBeenCalled()
+ })
+})
diff --git a/e2e/react-start/vitest-library/tsconfig.json b/e2e/react-start/vitest-library/tsconfig.json
new file mode 100644
index 0000000000..2fa8651e3f
--- /dev/null
+++ b/e2e/react-start/vitest-library/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "esModuleInterop": true,
+ "jsx": "react-jsx",
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "ESNext",
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": ["src", "tests", "vitest.config.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/e2e/react-start/vitest-library/vitest.config.ts b/e2e/react-start/vitest-library/vitest.config.ts
new file mode 100644
index 0000000000..ac9b6f1b1f
--- /dev/null
+++ b/e2e/react-start/vitest-library/vitest.config.ts
@@ -0,0 +1,59 @@
+import { defineConfig } from 'vitest/config'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import react from '@vitejs/plugin-react'
+import { playwright } from '@vitest/browser-playwright'
+
+// A package without routes and without a router entry, which depends on
+// Start only. It needs the Start compiler, so that each test environment gets
+// the code a Start app would run there.
+//
+// `test:e2e` type-checks the project and runs these tests three times:
+// - here, where `@tanstack/*` are links to `packages/*`, with an empty Vitest
+// cache (`test:e2e:linked`),
+// - here again, now with the compiled modules of the first run in Vitest's
+// cache (`test:e2e:cached`): a test run must not depend on the Start
+// compiler having seen a file in the same process,
+// - in a copy that is installed like a user's project
+// (`test:e2e:installed`, `scripts/e2e/run-as-installed.md` says why that
+// differs).
+export default defineConfig({
+ plugins: [tanstackStart(), react()],
+ test: {
+ watch: false,
+ // Vitest keeps the modules it compiled in one cache for the whole
+ // repository. This project keeps its own, so that `test:e2e:linked` can
+ // empty it and compile every file with the packages as they are built now.
+ fsModuleCachePath: 'node_modules/.vitest-cache',
+ projects: [
+ {
+ extends: true,
+ test: {
+ name: 'browser',
+ include: ['tests/**/*.client.test.ts'],
+ browser: {
+ enabled: true,
+ headless: true,
+ provider: playwright(),
+ instances: [{ browser: 'chromium' }],
+ },
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: 'jsdom',
+ environment: 'jsdom',
+ include: ['tests/**/*.client.test.ts'],
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: 'node',
+ environment: 'node',
+ include: ['tests/**/*.server.test.ts'],
+ },
+ },
+ ],
+ },
+})
diff --git a/packages/react-start/package.json b/packages/react-start/package.json
index 6d51a4c6d0..a99f2a2353 100644
--- a/packages/react-start/package.json
+++ b/packages/react-start/package.json
@@ -60,6 +60,24 @@
"default": "./dist/esm/client-rpc.js"
}
},
+ "./testing": {
+ "import": {
+ "types": "./dist/esm/testing.d.ts",
+ "default": "./dist/esm/testing.js"
+ }
+ },
+ "./testing/client-rpc": {
+ "import": {
+ "types": "./dist/esm/testing/client-rpc.d.ts",
+ "default": "./dist/esm/testing/client-rpc.js"
+ }
+ },
+ "./testing/server": {
+ "import": {
+ "types": "./dist/esm/testing/server.d.ts",
+ "default": "./dist/esm/testing/server.js"
+ }
+ },
"./server": {
"react-server": {
"types": "./dist/esm/server.rsc.d.ts",
diff --git a/packages/react-start/src/plugin/vite.ts b/packages/react-start/src/plugin/vite.ts
index 8849f39ea6..9323e02af0 100644
--- a/packages/react-start/src/plugin/vite.ts
+++ b/packages/react-start/src/plugin/vite.ts
@@ -105,7 +105,12 @@ export function tanstackStart(
: ['react-dom/server']),
// `@tanstack/react-store` has a dependency on `use-sync-external-store`, which is CJS.
// It therefore needs to be included so that it is converted to ESM.
- '@tanstack/react-router > @tanstack/react-store',
+ // The path starts at `@tanstack/react-start`, because a
+ // package that only uses Start's compile-time APIs (and runs
+ // its tests with this plugin) may not depend on
+ // `@tanstack/react-router` itself, and Vite resolves the path
+ // from the project.
+ '@tanstack/react-start > @tanstack/react-router > @tanstack/react-store',
...(options.optimizeDeps?.exclude?.find(
(x) => x === '@tanstack/react-form',
)
diff --git a/packages/react-start/src/testing.ts b/packages/react-start/src/testing.ts
new file mode 100644
index 0000000000..0384b6fb65
--- /dev/null
+++ b/packages/react-start/src/testing.ts
@@ -0,0 +1,10 @@
+export {
+ mockServerFn,
+ resetServerFnMocks,
+} from '@tanstack/start-client-core/testing'
+export type {
+ AnyClientServerFn,
+ ServerFnMock,
+ ServerFnMockContext,
+ ServerFnMockData,
+} from '@tanstack/start-client-core/testing'
diff --git a/packages/react-start/src/testing/client-rpc.ts b/packages/react-start/src/testing/client-rpc.ts
new file mode 100644
index 0000000000..80b041a388
--- /dev/null
+++ b/packages/react-start/src/testing/client-rpc.ts
@@ -0,0 +1 @@
+export * from '@tanstack/start-client-core/testing/client-rpc'
diff --git a/packages/react-start/src/testing/server.ts b/packages/react-start/src/testing/server.ts
new file mode 100644
index 0000000000..ec2ad1c8d8
--- /dev/null
+++ b/packages/react-start/src/testing/server.ts
@@ -0,0 +1 @@
+export * from '@tanstack/start-server-core/testing'
diff --git a/packages/react-start/vite.config.ts b/packages/react-start/vite.config.ts
index 652e4ef842..6395099e44 100644
--- a/packages/react-start/vite.config.ts
+++ b/packages/react-start/vite.config.ts
@@ -29,6 +29,9 @@ export default mergeConfig(
'./src/client.tsx',
'./src/hydration.ts',
'./src/client-rpc.ts',
+ './src/testing.ts',
+ './src/testing/client-rpc.ts',
+ './src/testing/server.ts',
'./src/server.tsx',
'./src/server.rsc.ts',
'./src/server-rpc.ts',
diff --git a/packages/router-generator/src/generator.ts b/packages/router-generator/src/generator.ts
index 91f87dadda..f47ea63af9 100644
--- a/packages/router-generator/src/generator.ts
+++ b/packages/router-generator/src/generator.ts
@@ -209,6 +209,7 @@ export class Generator {
public targetTemplate: TargetTemplate
private root: string
+ private writeRouteFiles: boolean
private routesDirectoryPath: string
private sessionId?: string
private fs: fs
@@ -243,10 +244,21 @@ export class Generator {
private static componentPieceRegex =
/[./](component|errorComponent|notFoundComponent|pendingComponent|loader|lazy)[.]/
- constructor(opts: { config: Config; root: string; fs?: fs }) {
+ constructor(opts: {
+ config: Config
+ root: string
+ fs?: fs
+ /**
+ * `false` keeps the generator from scaffolding empty route files and from
+ * updating the route path or factory in existing ones. Only the route tree
+ * is written. A route file that would have been written gets a warning.
+ */
+ writeRouteFiles?: boolean
+ }) {
this.config = opts.config
this.logger = logging({ disabled: this.config.disableLogging })
this.root = opts.root
+ this.writeRouteFiles = opts.writeRouteFiles ?? true
this.fs = opts.fs || DefaultFileSystem
this.generatedRouteTreePath = this.getGeneratedRouteTreePath()
this.targetTemplate = getTargetTemplate(this.config)
@@ -1034,6 +1046,12 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
let shouldWriteTree = false
// now we need to either scaffold the file or transform it
if (!existingRouteFile.fileContent) {
+ if (!this.writeRouteFiles) {
+ this.logger.warn(
+ `Warning: Route file "${node.fullPath}" is empty. It is left as it is and is not included in the route tree, because this run does not write route files.`,
+ )
+ return null
+ }
shouldWriteRouteFile = true
shouldWriteTree = true
// Creating a new lazy route file
@@ -1129,8 +1147,14 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
)
}
if (transformResult.result === 'modified') {
- updatedCacheEntry.fileContent = transformResult.output
- shouldWriteRouteFile = true
+ if (this.writeRouteFiles) {
+ updatedCacheEntry.fileContent = transformResult.output
+ shouldWriteRouteFile = true
+ } else {
+ this.logger.warn(
+ `Warning: Route file "${node.fullPath}" is out of date: its route path or route factory does not match its location. It is left as it is, because this run does not write route files.`,
+ )
+ }
}
}
@@ -1369,6 +1393,11 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved
// scaffold the root route
if (!rootNodeFile.fileContent) {
+ if (!this.writeRouteFiles) {
+ throw new Error(
+ `The root route file "${node.fullPath}" is empty, and this run does not write route files.`,
+ )
+ }
const rootTemplate = this.targetTemplate.rootRoute
const rootRouteContent = await fillTemplate(
this.config,
diff --git a/packages/router-generator/tests/write-route-files.test.ts b/packages/router-generator/tests/write-route-files.test.ts
new file mode 100644
index 0000000000..14f7340ef8
--- /dev/null
+++ b/packages/router-generator/tests/write-route-files.test.ts
@@ -0,0 +1,107 @@
+import fs from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { Generator, getConfig } from '../src'
+
+const rootRouteSource = `import { createRootRoute } from '@tanstack/react-router'
+
+export const Route = createRootRoute()
+`
+
+let tempDir: string | undefined
+
+afterEach(async () => {
+ vi.restoreAllMocks()
+ if (tempDir) {
+ await fs.rm(tempDir, { recursive: true, force: true })
+ tempDir = undefined
+ }
+})
+
+/** A project whose generator writes the route tree and no route file. */
+async function createProject(routes: Record) {
+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tsr-generator-tree-only-'))
+ const routesDirectory = path.join(tempDir, 'routes')
+ await fs.mkdir(routesDirectory)
+ for (const [file, content] of Object.entries(routes)) {
+ await fs.writeFile(path.join(routesDirectory, file), content)
+ }
+ const generatedRouteTree = path.join(tempDir, 'routeTree.gen.ts')
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'info').mockImplementation(() => {})
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const generator = new Generator({
+ config: getConfig(
+ {
+ routesDirectory,
+ generatedRouteTree,
+ tmpDir: path.join(tempDir, 'tmp'),
+ },
+ tempDir,
+ ),
+ root: tempDir,
+ writeRouteFiles: false,
+ })
+ return {
+ generator,
+ // (the generator names route files with forward slashes on every system)
+ route: (file: string) =>
+ path.join(routesDirectory, file).replaceAll('\\', '/'),
+ routeTree: () => fs.readFile(generatedRouteTree, 'utf8'),
+ warnings: () => warn.mock.calls.map((args) => args.join(' ')).join('\n'),
+ }
+}
+
+describe('generator that does not write route files', () => {
+ it('leaves a route file whose route path is out of date as it is and warns', async () => {
+ const movedRouteSource = `import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/moved-from')({
+ component: () => 'moved',
+})
+`
+ const project = await createProject({
+ '__root.tsx': rootRouteSource,
+ 'moved.tsx': movedRouteSource,
+ })
+
+ await project.generator.run()
+
+ expect(await fs.readFile(project.route('moved.tsx'), 'utf8')).toBe(
+ movedRouteSource,
+ )
+ // The route tree has the route by the location of its file.
+ const routeTree = await project.routeTree()
+ expect(routeTree).toContain(`'/moved'`)
+ expect(routeTree).not.toContain('moved-from')
+ expect(project.warnings()).toContain(
+ `Route file "${project.route('moved.tsx')}" is out of date`,
+ )
+ })
+
+ it('leaves an empty route file empty and out of the route tree, and warns', async () => {
+ const project = await createProject({
+ '__root.tsx': rootRouteSource,
+ 'empty.tsx': '',
+ })
+
+ await project.generator.run()
+
+ expect(await fs.readFile(project.route('empty.tsx'), 'utf8')).toBe('')
+ expect(await project.routeTree()).not.toContain('empty')
+ expect(project.warnings()).toContain(
+ `Route file "${project.route('empty.tsx')}" is empty`,
+ )
+ })
+
+ it('fails for an empty root route file, which it cannot fill', async () => {
+ const project = await createProject({ '__root.tsx': '' })
+
+ await expect(project.generator.run()).rejects.toThrow(
+ `The root route file "${project.route('__root.tsx')}" is empty`,
+ )
+ expect(await fs.readFile(project.route('__root.tsx'), 'utf8')).toBe('')
+ })
+})
diff --git a/packages/router-plugin/src/core/host-options.ts b/packages/router-plugin/src/core/host-options.ts
new file mode 100644
index 0000000000..bf8b4ad6a8
--- /dev/null
+++ b/packages/router-plugin/src/core/host-options.ts
@@ -0,0 +1,28 @@
+import type { Config } from './config'
+
+/**
+ * Lets a plugin that embeds the route generator, such as TanStack Start,
+ * change when it runs. Every function is called late, once the bundler's
+ * config is known, and every option defaults to the standalone behaviour.
+ */
+export interface RouterGeneratorHostOptions {
+ /** Return `false` to create no generator at all for this config. */
+ enabled?: (opts: { config: Config; root: string }) => boolean
+ /** Return `false` to ignore file changes after the first run. */
+ watch?: () => boolean
+ /** Return `false` to keep the generator from writing route files. */
+ writeRouteFiles?: () => boolean
+}
+
+/**
+ * Lets a plugin that embeds the code splitter, such as TanStack Start, change
+ * what it handles. The function is called for each module.
+ */
+export interface RouterCodeSplitterHostOptions {
+ /**
+ * Return `true` to also handle a module that calls a route factory but is
+ * unknown to the route generator. Nothing is split out of such a module;
+ * only the route options listed in `deleteNodes` are removed from it.
+ */
+ deleteNodesInUnknownRoutes?: () => boolean
+}
diff --git a/packages/router-plugin/src/core/router-code-splitter-plugin.ts b/packages/router-plugin/src/core/router-code-splitter-plugin.ts
index ecc7607d59..1e09bf8cf2 100644
--- a/packages/router-plugin/src/core/router-code-splitter-plugin.ts
+++ b/packages/router-plugin/src/core/router-code-splitter-plugin.ts
@@ -26,6 +26,7 @@ import type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'
import type { CodeSplitCompilerPlugin } from './code-splitter/plugins'
import type { Config } from './config'
import type { HmrStyle } from './hmr'
+import type { RouterCodeSplitterHostOptions } from './host-options'
import type { RouterPluginContext } from './router-plugin-context'
import type {
UnpluginFactory,
@@ -82,6 +83,7 @@ export function createRouterCodeSplitterPlugin(
options: Partial Config)> | undefined = {},
routerPluginContext: RouterPluginContext,
hmrStyle: HmrStyle = 'vite',
+ hostOptions: RouterCodeSplitterHostOptions = {},
): ReturnType Config)> | undefined>> {
let ROOT: string = process.cwd()
let userConfig: Config
@@ -209,6 +211,34 @@ export function createRouterCodeSplitterPlugin(
return compiledReferenceRoute
}
+ const handleDeletingNodesInUnknownRoute = (
+ code: string,
+ id: string,
+ ): UnpluginTransformResult => {
+ const deleteNodes = userConfig.codeSplittingOptions?.deleteNodes
+ if (!deleteNodes?.length) {
+ return null
+ }
+
+ if (debug) {
+ console.info('Deleting nodes in route unknown to the generator: ', id)
+ }
+
+ // Without split groupings the reference compiler only removes the listed
+ // route options and the code that nothing else uses anymore.
+ return compileCodeSplitReferenceRoute({
+ code,
+ codeSplitGroupings: [],
+ targetFramework: userConfig.target,
+ filename: id,
+ id,
+ isProduction,
+ deleteNodes: new Set(deleteNodes),
+ addHmr: false,
+ hmrStyle,
+ })
+ }
+
const handleCompilingVirtualFile = (
code: string,
id: string,
@@ -277,6 +307,10 @@ export function createRouterCodeSplitterPlugin(
)
}
+ if (hostOptions.deleteNodesInUnknownRoutes?.()) {
+ return handleDeletingNodesInUnknownRoute(code, normalizedId)
+ }
+
return null
},
},
diff --git a/packages/router-plugin/src/core/router-generator-plugin.ts b/packages/router-plugin/src/core/router-generator-plugin.ts
index 50dde9f55c..27e5dfc393 100644
--- a/packages/router-plugin/src/core/router-generator-plugin.ts
+++ b/packages/router-plugin/src/core/router-generator-plugin.ts
@@ -7,6 +7,7 @@ import type { GeneratorEvent } from '@tanstack/router-generator'
import type { FSWatcher } from 'chokidar'
import type { UnpluginFactory } from 'unplugin'
import type { Config } from './config'
+import type { RouterGeneratorHostOptions } from './host-options'
import type { RouterPluginContext } from './router-plugin-context'
const PLUGIN_NAME = 'unplugin:router-generator'
@@ -14,10 +15,11 @@ const PLUGIN_NAME = 'unplugin:router-generator'
export function createRouterGeneratorPlugin(
options: Partial Config)> | undefined = {},
routerPluginContext: RouterPluginContext,
+ hostOptions: RouterGeneratorHostOptions = {},
): ReturnType Config)> | undefined>> {
let ROOT: string = process.cwd()
let userConfig: Config
- let generator: Generator
+ let generator: Generator | undefined
const getRoutesDirectoryPath = () => {
return isAbsolute(userConfig.routesDirectory)
@@ -34,9 +36,14 @@ export function createRouterGeneratorPlugin(
} else {
userConfig = getConfig(options, ROOT)
}
+ if (hostOptions.enabled?.({ config: userConfig, root: ROOT }) === false) {
+ generator = undefined
+ return
+ }
generator = new Generator({
config: userConfig,
root: ROOT,
+ writeRouteFiles: hostOptions.writeRouteFiles?.(),
})
}
@@ -54,6 +61,10 @@ export function createRouterGeneratorPlugin(
generatorEvent = { path: filePath, type: opts.event }
}
+ if (!generator) {
+ return
+ }
+
try {
await generator.run(generatorEvent)
routerPluginContext.routesByFile = generator.getRoutesByFileMap()
@@ -66,6 +77,9 @@ export function createRouterGeneratorPlugin(
name: 'tanstack:router-generator',
enforce: 'pre',
async watchChange(id, { event }) {
+ if (hostOptions.watch?.() === false) {
+ return
+ }
await generate({
file: id,
event,
diff --git a/packages/router-plugin/src/vite.ts b/packages/router-plugin/src/vite.ts
index 3608887f33..2d40788e2a 100644
--- a/packages/router-plugin/src/vite.ts
+++ b/packages/router-plugin/src/vite.ts
@@ -6,6 +6,10 @@ import { createRouterGeneratorPlugin } from './core/router-generator-plugin'
import { unpluginRouterComposedFactory } from './core/router-composed-plugin'
import { createRouterPluginContext } from './core/router-plugin-context'
import type { CodeSplittingOptions, Config } from './core/config'
+import type {
+ RouterCodeSplitterHostOptions,
+ RouterGeneratorHostOptions,
+} from './core/host-options'
import type { RouterPluginContext } from './core/router-plugin-context'
type RouterPluginOptions = Partial Config)> | undefined
@@ -24,10 +28,11 @@ const defaultRouterPluginContext = createRouterPluginContext()
const tanstackRouterGenerator = (
options?: RouterPluginOptions,
routerPluginContext?: RouterPluginContext,
+ hostOptions?: RouterGeneratorHostOptions,
) => {
const pluginContext = routerPluginContext ?? defaultRouterPluginContext
return createVitePlugin((pluginOptions: RouterPluginOptions) =>
- createRouterGeneratorPlugin(pluginOptions, pluginContext),
+ createRouterGeneratorPlugin(pluginOptions, pluginContext, hostOptions),
)(options)
}
@@ -43,10 +48,16 @@ const tanstackRouterGenerator = (
const tanStackRouterCodeSplitter = (
options?: RouterPluginOptions,
routerPluginContext?: RouterPluginContext,
+ hostOptions?: RouterCodeSplitterHostOptions,
) => {
const pluginContext = routerPluginContext ?? defaultRouterPluginContext
return createVitePlugin((pluginOptions: RouterPluginOptions) =>
- createRouterCodeSplitterPlugin(pluginOptions, pluginContext),
+ createRouterCodeSplitterPlugin(
+ pluginOptions,
+ pluginContext,
+ undefined,
+ hostOptions,
+ ),
)(options)
}
diff --git a/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts b/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts
index dca96bfa28..5f251537ef 100644
--- a/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts
+++ b/packages/router-plugin/tests/code-splitter-plugin-pipeline.test.ts
@@ -189,6 +189,69 @@ export const Route = createFileRoute('/unshared')({
})
})
+describe('a route module the route generator does not know', () => {
+ const file = routeFile('unknown')
+ const code = `
+import { createFileRoute } from '@tanstack/react-router'
+import { secret } from './server-only'
+export const Route = createFileRoute('/unknown')({
+ server: { handlers: { GET: () => new Response(secret) } },
+ component: () =>
unknown
,
+})
+`
+ const options: Partial = {
+ codeSplittingOptions: { deleteNodes: ['server'] },
+ }
+
+ it('is left as it is', async () => {
+ const splitter = await createCodeSplitterTransforms(options, {})
+
+ expect(splitter.reference(code, file)).toBeNull()
+ })
+
+ // A plugin that embeds the code splitter can run where no generator does,
+ // e.g. TanStack Start for the tests of a package without routes.
+ it('loses the route options to delete, and nothing else, when the host plugin asks for it', async () => {
+ const splitter = await createCodeSplitterTransforms(
+ options,
+ {},
+ undefined,
+ { deleteNodesInUnknownRoutes: () => true },
+ )
+
+ const reference = splitter.reference(code, file)!
+ // (the import only the deleted option used goes with it)
+ expect(reference).not.toContain('server')
+ expect(importSources(reference)).toEqual(['@tanstack/react-router'])
+ expect(reference).toContain('
unknown
')
+ expect(reference).not.toContain('tsr-split')
+ await expectValidModules({ reference })
+ })
+
+ it('is left as it is when the host plugin asks for it and there are no route options to delete', async () => {
+ const splitter = await createCodeSplitterTransforms({}, {}, undefined, {
+ deleteNodesInUnknownRoutes: () => true,
+ })
+
+ expect(splitter.reference(code, file)).toBeNull()
+ })
+
+ it('does not change how a route module the generator knows is split', async () => {
+ const routes = { [file]: '/unknown' }
+ const hosted = await createCodeSplitterTransforms(
+ options,
+ routes,
+ undefined,
+ { deleteNodesInUnknownRoutes: () => true },
+ )
+ const standalone = await createCodeSplitterTransforms(options, routes)
+
+ const reference = hosted.reference(code, file)
+ expect(reference).toContain('tsr-split=component')
+ expect(reference).toBe(standalone.reference(code, file))
+ })
+})
+
describe('route HMR plugin without code splitting', () => {
function transformWith(
options: Partial & { target: 'solid' | 'vue' },
diff --git a/packages/router-plugin/tests/regression-helpers.ts b/packages/router-plugin/tests/regression-helpers.ts
index df482ffe78..9df375881b 100644
--- a/packages/router-plugin/tests/regression-helpers.ts
+++ b/packages/router-plugin/tests/regression-helpers.ts
@@ -26,6 +26,7 @@ import { getModuleErrors } from './validate-module'
import type { Config } from '../src/core/config'
import type { CodeSplitGroupings } from '../src/core/constants'
import type { HmrStyle } from '../src/core/hmr'
+import type { RouterCodeSplitterHostOptions } from '../src/core/host-options'
import type { TransformResult, UnpluginOptions } from 'unplugin'
import type { ESTree } from 'vite'
@@ -189,12 +190,14 @@ const sharedPluginName = 'tanstack-router:code-splitter:compile-shared-file'
* Drives the three code-splitter transforms the way a bundler does, for the
* given route files (absolute path to route id). `configPlugins` are the
* plugins of the resolved Vite config; by default the code splitter itself,
- * so its plugin-order check runs.
+ * so its plugin-order check runs. `hostOptions` are those of a plugin that
+ * embeds the code splitter.
*/
export async function createCodeSplitterTransforms(
options: Partial,
routes: Record,
configPlugins: Array<{ name: string }> = [{ name: referencePluginName }],
+ hostOptions?: RouterCodeSplitterHostOptions,
) {
const context = createRouterPluginContext()
for (const [file, routeId] of Object.entries(routes)) {
@@ -203,6 +206,8 @@ export async function createCodeSplitterTransforms(
const plugins = createRouterCodeSplitterPlugin(
{ target: 'react', autoCodeSplitting: true, ...options },
context,
+ undefined,
+ hostOptions,
)
const pluginArray = Array.isArray(plugins) ? plugins : [plugins]
const byName = (name: string) => {
diff --git a/packages/router-plugin/tests/router-generator-plugin.test.ts b/packages/router-plugin/tests/router-generator-plugin.test.ts
new file mode 100644
index 0000000000..0278d5870d
--- /dev/null
+++ b/packages/router-plugin/tests/router-generator-plugin.test.ts
@@ -0,0 +1,152 @@
+import fs from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { createRouterGeneratorPlugin } from '../src/core/router-generator-plugin'
+import { createRouterPluginContext } from '../src/core/router-plugin-context'
+import type { RouterGeneratorHostOptions } from '../src/core/host-options'
+import type { UnpluginOptions } from 'unplugin'
+
+const rootRouteSource = `import { createRootRoute } from '@tanstack/react-router'
+
+export const Route = createRootRoute()
+`
+
+const routeSource = (routePath: string) =>
+ `import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('${routePath}')({
+ component: () => 'route',
+})
+`
+
+let tempDir: string | undefined
+
+afterEach(async () => {
+ if (tempDir) {
+ await fs.rm(tempDir, { recursive: true, force: true })
+ tempDir = undefined
+ }
+})
+
+/**
+ * A project with the generator plugin as a plugin that embeds it sets it up,
+ * driven the way Vite drives it.
+ */
+async function createProject(
+ routes: Record,
+ hostOptions?: RouterGeneratorHostOptions,
+) {
+ tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tsr-generator-plugin-'))
+ const root = tempDir
+ const routesDirectory = path.join(root, 'routes')
+ const generatedRouteTree = path.join(root, 'routeTree.gen.ts')
+ await fs.mkdir(routesDirectory)
+ for (const [file, content] of Object.entries(routes)) {
+ await fs.writeFile(path.join(routesDirectory, file), content)
+ }
+ const plugin = createRouterGeneratorPlugin(
+ {
+ target: 'react',
+ routesDirectory,
+ generatedRouteTree,
+ tmpDir: path.join(root, 'tmp'),
+ disableLogging: true,
+ },
+ createRouterPluginContext(),
+ hostOptions,
+ ) as UnpluginOptions
+ return {
+ route: (file: string) => path.join(routesDirectory, file),
+ routeTree: () => fs.readFile(generatedRouteTree, 'utf8'),
+ /** Vite resolved its config. */
+ async start() {
+ const configResolved = plugin.vite!.configResolved as (config: {
+ root: string
+ }) => Promise
+ await configResolved.call({}, { root })
+ },
+ /** Vite's file watcher saw a new file. */
+ async add(file: string, content: string) {
+ const added = path.join(routesDirectory, file)
+ await fs.writeFile(added, content)
+ const watchChange = plugin.watchChange as (
+ id: string,
+ change: { event: 'create' | 'update' | 'delete' },
+ ) => Promise
+ await watchChange.call({}, added, { event: 'create' })
+ },
+ }
+}
+
+describe('route generator plugin', () => {
+ it('writes the route tree at startup and when a route is added', async () => {
+ const project = await createProject({ '__root.tsx': rootRouteSource })
+
+ await project.start()
+ expect(await project.routeTree()).not.toContain(`'/added'`)
+
+ await project.add('added.tsx', routeSource('/added'))
+ expect(await project.routeTree()).toContain(`'/added'`)
+ })
+})
+
+describe('route generator plugin embedded in a host plugin', () => {
+ it('generates nothing when the host disables it', async () => {
+ const project = await createProject(
+ { '__root.tsx': rootRouteSource },
+ { enabled: () => false },
+ )
+
+ await project.start()
+ await project.add('added.tsx', routeSource('/added'))
+
+ await expect(project.routeTree()).rejects.toThrow('ENOENT')
+ })
+
+ it('tells the host the config and the root it would generate for', async () => {
+ const seen: Array<{ routesDirectory: string; root: string }> = []
+ const project = await createProject(
+ { '__root.tsx': rootRouteSource },
+ {
+ enabled: ({ config, root }) => {
+ seen.push({ routesDirectory: config.routesDirectory, root })
+ return true
+ },
+ },
+ )
+
+ await project.start()
+
+ expect(seen).toEqual([
+ { routesDirectory: path.dirname(project.route('x')), root: tempDir },
+ ])
+ expect(await project.routeTree()).toContain('rootRouteImport')
+ })
+
+ it('writes the route tree at startup only when the host turns watching off', async () => {
+ const project = await createProject(
+ { '__root.tsx': rootRouteSource },
+ { watch: () => false },
+ )
+
+ await project.start()
+ const routeTree = await project.routeTree()
+ await project.add('added.tsx', routeSource('/added'))
+
+ expect(await project.routeTree()).toBe(routeTree)
+ })
+
+ it('leaves route files as they are when the host turns writing them off', async () => {
+ const moved = routeSource('/moved-from')
+ const project = await createProject(
+ { '__root.tsx': rootRouteSource, 'moved.tsx': moved },
+ { writeRouteFiles: () => false },
+ )
+
+ await project.start()
+
+ expect(await fs.readFile(project.route('moved.tsx'), 'utf8')).toBe(moved)
+ expect(await project.routeTree()).toContain(`'/moved'`)
+ })
+})
diff --git a/packages/solid-start/package.json b/packages/solid-start/package.json
index 2f378426cc..b49670d8c9 100644
--- a/packages/solid-start/package.json
+++ b/packages/solid-start/package.json
@@ -57,6 +57,24 @@
"default": "./dist/esm/client-rpc.js"
}
},
+ "./testing": {
+ "import": {
+ "types": "./dist/esm/testing.d.ts",
+ "default": "./dist/esm/testing.js"
+ }
+ },
+ "./testing/client-rpc": {
+ "import": {
+ "types": "./dist/esm/testing/client-rpc.d.ts",
+ "default": "./dist/esm/testing/client-rpc.js"
+ }
+ },
+ "./testing/server": {
+ "import": {
+ "types": "./dist/esm/testing/server.d.ts",
+ "default": "./dist/esm/testing/server.js"
+ }
+ },
"./server-rpc": {
"import": {
"types": "./dist/esm/server-rpc.d.ts",
diff --git a/packages/solid-start/src/testing.ts b/packages/solid-start/src/testing.ts
new file mode 100644
index 0000000000..0384b6fb65
--- /dev/null
+++ b/packages/solid-start/src/testing.ts
@@ -0,0 +1,10 @@
+export {
+ mockServerFn,
+ resetServerFnMocks,
+} from '@tanstack/start-client-core/testing'
+export type {
+ AnyClientServerFn,
+ ServerFnMock,
+ ServerFnMockContext,
+ ServerFnMockData,
+} from '@tanstack/start-client-core/testing'
diff --git a/packages/solid-start/src/testing/client-rpc.ts b/packages/solid-start/src/testing/client-rpc.ts
new file mode 100644
index 0000000000..80b041a388
--- /dev/null
+++ b/packages/solid-start/src/testing/client-rpc.ts
@@ -0,0 +1 @@
+export * from '@tanstack/start-client-core/testing/client-rpc'
diff --git a/packages/solid-start/src/testing/server.ts b/packages/solid-start/src/testing/server.ts
new file mode 100644
index 0000000000..ec2ad1c8d8
--- /dev/null
+++ b/packages/solid-start/src/testing/server.ts
@@ -0,0 +1 @@
+export * from '@tanstack/start-server-core/testing'
diff --git a/packages/solid-start/vite.config.ts b/packages/solid-start/vite.config.ts
index 2c1a42d0e4..0e94478654 100644
--- a/packages/solid-start/vite.config.ts
+++ b/packages/solid-start/vite.config.ts
@@ -29,6 +29,9 @@ export default mergeConfig(
'./src/client.tsx',
'./src/hydration.ts',
'./src/client-rpc.ts',
+ './src/testing.ts',
+ './src/testing/client-rpc.ts',
+ './src/testing/server.ts',
'./src/ssr-rpc.ts',
'./src/server-rpc.ts',
'./src/server.tsx',
diff --git a/packages/start-client-core/package.json b/packages/start-client-core/package.json
index c74dce13aa..d094c94fa7 100644
--- a/packages/start-client-core/package.json
+++ b/packages/start-client-core/package.json
@@ -60,6 +60,24 @@
"default": "./dist/esm/client-rpc/index.js"
}
},
+ "./testing": {
+ "import": {
+ "types": "./dist/esm/testing/index.d.ts",
+ "default": "./dist/esm/testing/index.js"
+ }
+ },
+ "./testing/client-rpc": {
+ "import": {
+ "types": "./dist/esm/testing/client-rpc.d.ts",
+ "default": "./dist/esm/testing/client-rpc.js"
+ }
+ },
+ "./testing/vitest": {
+ "import": {
+ "types": "./dist/esm/testing/vitest.d.ts",
+ "default": "./dist/esm/testing/vitest.js"
+ }
+ },
"./hydration": {
"import": {
"types": "./dist/esm/hydration.d.ts",
@@ -120,5 +138,13 @@
"@arethetypeswrong/cli": "catalog:",
"publint": "catalog:",
"rimraf": "catalog:"
+ },
+ "peerDependencies": {
+ "vitest": ">=3.1.0"
+ },
+ "peerDependenciesMeta": {
+ "vitest": {
+ "optional": true
+ }
}
}
diff --git a/packages/start-client-core/src/index.tsx b/packages/start-client-core/src/index.tsx
index e9a8b92d85..bda11979a8 100644
--- a/packages/start-client-core/src/index.tsx
+++ b/packages/start-client-core/src/index.tsx
@@ -40,6 +40,8 @@ export {
type FunctionClientResultWithContext,
type AssignAllClientContextBeforeNext,
type AssignAllMiddleware,
+ type AssignAllServerFnContext,
+ type AssignAllServerRequestContext,
type FunctionMiddlewareAfterValidator,
type FunctionMiddlewareClientFn,
type FunctionMiddlewareServerFnResult,
diff --git a/packages/start-client-core/src/testing/client-rpc.ts b/packages/start-client-core/src/testing/client-rpc.ts
new file mode 100644
index 0000000000..663386aaec
--- /dev/null
+++ b/packages/start-client-core/src/testing/client-rpc.ts
@@ -0,0 +1,2 @@
+// What compiled client code imports in a test run, in place of `../client-rpc`.
+export { createClientRpc } from './createClientRpc'
diff --git a/packages/start-client-core/src/testing/createClientRpc.ts b/packages/start-client-core/src/testing/createClientRpc.ts
new file mode 100644
index 0000000000..6f843973d8
--- /dev/null
+++ b/packages/start-client-core/src/testing/createClientRpc.ts
@@ -0,0 +1,24 @@
+import { TSS_SERVER_FUNCTION } from '../constants'
+import { callServerFnMock, registerClientRpc } from './serverFnMocks'
+import type { ClientFnMeta } from '../constants'
+
+/**
+ * The `createClientRpc` of a test run. The one of the app sends the call to
+ * the server (`../client-rpc/createClientRpc`). A client test has no server,
+ * so this one passes the call to the mock that `mockServerFn` registered.
+ */
+export function createClientRpc(functionId: string) {
+ const url = process.env.TSS_SERVER_FN_BASE + functionId
+ const serverFnMeta: ClientFnMeta = { id: functionId }
+ registerClientRpc(functionId)
+
+ const clientFn = (...args: Array) => {
+ return callServerFnMock(functionId, args[0])
+ }
+
+ return Object.assign(clientFn, {
+ url,
+ serverFnMeta,
+ [TSS_SERVER_FUNCTION]: true,
+ })
+}
diff --git a/packages/start-client-core/src/testing/index.ts b/packages/start-client-core/src/testing/index.ts
new file mode 100644
index 0000000000..c62c2fabf9
--- /dev/null
+++ b/packages/start-client-core/src/testing/index.ts
@@ -0,0 +1,8 @@
+export { mockServerFn, resetServerFnMocks } from './serverFnMocks'
+export { registerMockStore, saveMocks } from './mockStores'
+export type {
+ AnyClientServerFn,
+ ServerFnMock,
+ ServerFnMockContext,
+ ServerFnMockData,
+} from './serverFnMocks'
diff --git a/packages/start-client-core/src/testing/mockStores.ts b/packages/start-client-core/src/testing/mockStores.ts
new file mode 100644
index 0000000000..483d5b5913
--- /dev/null
+++ b/packages/start-client-core/src/testing/mockStores.ts
@@ -0,0 +1,32 @@
+/**
+ * The registries of `mockServerFn` and `mockMiddleware`. Each registers its
+ * map here, so that one hook of the test runner can put all of them back
+ * after a test.
+ */
+const stores = new Set