TanStack Router

Use this setup if you already use TanStack Query, or share route conventions with another TanStack app, and want Solid's server functions, streaming SSR, and single-flight mutations too. The fullstack-tanstack project shape is the fullstack shape with TanStack on the client.

TanStack Router owns routing and TanStack Query owns the data cache, while Solid's server functions, streaming SSR, single-flight mutations, sessions, and API routes work unchanged. The server does not depend on which router is used.

This page explains how the three fit together in that template. For the router's own API, route files, <Link>, loaders, search params, and so on, use the TanStack Router documentation; nothing there changes under Solid.

If you have not chosen a router yet

Pick a router weighs this shape against Solid Router. The short version: choose this one for TanStack Query or shared TanStack conventions; otherwise Solid Router has the file-system convention the other templates share and forms that work without JavaScript.


Who owns what

  • Solid and the Vite plugin handle server functions ("use server" functions compiled to typed fetches), single-flight responses, serialization, the generated entries, src/Document.tsx, sessions, and typed env.
  • TanStack Router handles routing: the file-based tree under src/routes (generated into src/routeTree.gen.ts), navigation, preloading, and per-route code splitting.
  • TanStack Query holds the client data cache: loaders prefetch into it, components read from it with useQuery, and all data from the server goes into it.

Single-flight mutations involve all three, using only public extension points. No package patches or wraps another.


The shape of a page

Here is the user detail route from the template, trimmed:

// src/routes/users.$id.tsx
import { useMutation, useQuery } from "@tanstack/solid-query";
import { createFileRoute } from "@tanstack/solid-router";
import { isPending } from "solid-js";
import { prefetch, userQuery } from "../lib/queries";
import { renameUser } from "../lib/users";
export const Route = createFileRoute("/users/$id")({
loader: ({ context, params }) => {
prefetch(context.queryClient, userQuery(params.id));
},
component: UserPage,
});
function UserPage() {
const params = Route.useParams();
const user = useQuery(() => userQuery(params().id));
const rename = useMutation(() => ({
mutationFn: (input: { id: string; name: string }) => renameUser(input),
}));
return (
<section style={{ opacity: isPending(() => user.data) ? 0.5 : 1 }}>
<h2>{user.data.name}</h2>
<form
onSubmit={(event) => {
event.preventDefault();
const name = new FormData(event.currentTarget).get("name");
rename.mutate({ id: params().id, name: String(name) });
}}
>
<input name="name" value={user.data.name} required />
<button type="submit" disabled={rename.isPending}>
Rename
</button>
</form>
</section>
);
}

Open /users/1, type a new name, and click Rename: the heading updates, the section dims briefly while the refetch is in flight, and the users list in the parent layout shows the new name too. Three things in this file differ from TanStack defaults on purpose.

The loader starts the request but does not wait for it. prefetch is void queryClient.prefetchQuery(...). The navigation happens at once, and reading user.data shows the nearest Loading fallback until the query finishes. On the server, this lets each boundary stream as soon as its own query finishes, instead of waiting for the slowest one.

Reads go through Solid's async model. user.data.name is read directly, with no isLoading guard, and isPending(() => user.data) dims the section during a refetch. These are the same primitives as the rest of Solid; Async reactivity explains them.

There is no invalidateQueries. When rename.mutate finishes, the cache already has the renamed user and the updated parent list. That is single-flight, covered below.


Reads: queryOptions around a GET server function

Every read is declared once, in src/lib/queries.ts, as TanStack queryOptions wrapping a server function:

src/lib/queries.ts
import { queryOptions } from "@tanstack/solid-query";
import { getUser, getUsers } from "./users";
export const usersQuery = () =>
queryOptions({ queryKey: ["users"], queryFn: () => getUsers() });
export const userQuery = (id: string) =>
queryOptions({ queryKey: ["users", id], queryFn: () => getUser(id) });
src/lib/users.ts
import { GET } from "@solidjs/web/server-functions";
export const getUser = GET(async (id: string) => {
"use server";
return findUser(id);
});

Loaders, components, and the single-flight code all use the same options, so each key is written in one place.

The GET wrapper matters here more than in the Solid Router template, where query applies it for you:

// Avoid: a bare server function is a POST, and every POST carries the single-flight header
export async function getUser(id: string) {
"use server";
return findUser(id);
}
// Prefer: declare the read as a GET
export const getUser = GET(async (id: string) => {
"use server";
return findUser(id);
});

In the Avoid version, each useQuery fetch asks the server to re-run the page's loaders and wait for them, because single-flight adds its header to every non-GET call. A read marked GET skips that header and can also be cached by HTTP.

Keep staleTime above zero

The shared QueryClient sets staleTime: 30_000. Data the server rendered, or a mutation refreshed, then counts as fresh. Without it, every useQuery would refetch when it mounts, which defeats both hydration and single-flight.


Mutations: server functions through useMutation

A mutation is a plain server function called through useMutation:

src/lib/users.ts
import { reload } from "@solidjs/web";
export async function renameUser(input: { id: string; name: string }) {
"use server";
if (!(await getSession())?.userId) throw new Error("Sign in to rename users");
updateUser(input.id, { name: input.name });
return reload({ revalidate: "users" });
}

Wrap the call in an arrow, as the route above does. useMutation calls mutationFn(variables, context), and a server function sends every argument it receives to the server; the arrow keeps the context object out of the request.

reload({ revalidate: "users" }) declares what the mutation changed. The template uses it to limit which data single-flight sends back; a mutation that returns nothing re-runs all of the page's loaders and sends everything they load.

Forms here are scripted (onSubmit calling mutate), the usual TanStack shape. For forms that must work without JavaScript, use the fullstack shape with Solid Router form actions; Progressive enhancement describes what the server does with a form POST sent without JavaScript, whatever the router.


What the server does per request

The plugin's start.serverRenderSetup hook lets a router that is not part of Solid drive streaming SSR. src/setup.tsx runs for each SSR request:

// src/setup.tsx (trimmed)
export default async function setup(
event: RequestEvent & { response: ResponseStub }
) {
const url = new URL(event.request.url);
const queryClient = createQueryClient();
const router = createAppRouter(
queryClient,
createMemoryHistory({ initialEntries: [url.pathname + url.search] })
);
await router.load();
const result = router._serverResult;
if (result?.type === "redirect") {
result.redirect.headers.forEach((value, key) =>
event.response.headers.set(key, value)
);
event.response.status = result.redirect.status;
return () => null;
}
if (result) event.response.status = result.status;
return () => (
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
);
}

Read it top to bottom:

  1. A fresh QueryClient and router per request, so one user's data never renders into another's page.
  2. router.load() matches the URL and starts the loaders' prefetches; rendering starts while they run.
  3. A redirect() thrown in beforeLoad or a loader does not throw on the server; it is stored in router._serverResult. Setup copies its status and Location onto the response so the browser gets a real 30x instead of a 200 with an empty body. Not-found and errored loads set 404 and 500 the same way.
  4. The returned component renders in App's place inside Document.

The providers pass server data to the client. QueryClientProvider streams each query's data into Solid's hydration data as the query finishes, and on the client it fills the cache from that data as it arrives. RouterProvider does the same for the matched routes, so the client router starts with the server's matches: no router.load() on startup, no loader re-runs, and each route's lazy chunk loads under the boundary the server rendered. There is no inline window.__QUERY_STATE__ or window.$_TSR script.

The client entry mirrors the tree with one session-long QueryClient:

// src/App.tsx (trimmed)
const queryClient = createQueryClient();
const router = createAppRouter(queryClient);
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
);
}

Single-flight mutations with TanStack Router

Rename a user with the network tab open. There is one POST /_server, and both the detail heading and the users list in the parent layout update from that one response.

On the client, QueryClientProvider registers a named single-flight data source ("sq") while it is mounted, and fills the cache from any data that comes back under that name. Registering turns single-flight on: while the provider is mounted, mutation calls send the single-flight header.

The server side is src/server-config.ts, loaded before any server function is dispatched through serverFunctions.serverSetup in vite.config.ts:

// src/server-config.ts (trimmed)
import { registerFlightDataSource } from "@solidjs/web/server-functions/server";
import { FLIGHT_DATA_SOURCE, dehydrateSettled } from "@tanstack/solid-query";
import { loadFlightTarget } from "@tanstack/solid-router/ssr/server";
registerFlightDataSource(FLIGHT_DATA_SOURCE, (event, outcome) => {
const queryClient = createQueryClient();
return loadFlightTarget({
router: createAppRouter(queryClient),
event,
outcome,
async collect() {
const state = await dehydrateSettled(queryClient);
return state.queries.length > 0 ? state : undefined;
},
});
});

loadFlightTarget builds a router for the page the browser will show after the mutation, including any cookies the mutation set, and runs its loaders into a new QueryClient. dehydrateSettled waits for those prefetches and returns the dehydrated cache, which is sent back with the response. The client reads it with TanStack's own hydrate.

The template goes one step further in src/lib/flight.ts: mutation requests list what the client already has cached, and the server skips anything the mutation's revalidate keys did not name. This is ordinary app code built on the same hooks, and the template's comments explain it. Without it, single-flight still works.


What stays the same

Sessions, typed env, API routes, and deployment are the fullstack shape's, unchanged. The one adjustment is where API routes live: src/routes belongs to TanStack Router, so the fileRoutes plugin scans src/api and mounts it under /api instead.


Limits to know

  • start.serverRenderSetup runs only with the plugin's generated server entry and only when ssr is on. An authored server entry has to prepare the router and render it itself.
  • TanStack's own SSR protocol (RouterServer, RouterClient, and the $_TSR stream handlers) expects to control the HTML stream, but in start mode the plugin controls it. The template does not use that protocol; it passes data through Solid's hydration data as described above.
  • disableGlobalCatchBoundary: true in src/router.tsx is a design choice, not a workaround. Errors, including a redirect() during SSR, bubble past the router to the app's own boundaries and stream handler instead of stopping at the router's ErrorComponent. Route-level errorComponent and pendingComponent still work.

Recap

  • Declare every read once as queryOptions around a GET server function, so each key is written in one place.
  • Treat the loader as a prefetch: void the promise and let the nearest Loading boundary show its fallback.
  • Read query.data directly and use isPending for refetch state; skip the isLoading guards.
  • Call mutations through useMutation with an arrow around the server function, and return reload({ revalidate }) to limit what single-flight sends back.
  • Keep staleTime above zero so hydrated and single-flight data count as fresh.
  • Build a fresh router and QueryClient per request in start.serverRenderSetup, and copy a redirect or status from router._serverResult onto the response.
  • Leave disableGlobalCatchBoundary: true in place so errors and redirects reach the app's own boundaries during SSR.

Next steps

  • Server functions: the reads and mutations wrapped in queryOptions and useMutation, including why GET matters.
  • Integrate a router: the start.serverRenderSetup and flight-data hooks this template is built on, for adapting the pattern to another router.
  • Choose a rendering mode: ssr: false, a static shell plus an API server, works for this shape too.
  • Middleware and API routes: the src/api handlers, and why they live outside src/routes in this shape.
Last updated: 11/17/26, 5:53 PMEdit this pageReport an issue with this page