TanStack Router and Start
Use Effetch Query in TanStack Router and TanStack Start.
Your app's routes are TanStack Router's, with or without Start.
connectQueryClient, from @monarcode/effetch-query/react/tanstack-router,
connects a query client to the router, as TanStack's
setupRouterSsrQueryIntegration does for TanStack Query. What your
loaders load goes with the page, and is in the browser's cache before
React hydrates, with no HydrationBoundary and no QueryProvider of your
own.
This page shows the router's side. The rules every framework shares, a
staleTime, streaming and redirects, are in
Frameworks, and the round trip itself is in
Send the cache. The examples import api.ts and
todos.ts from Getting started, and
todo-list.tsx from Send the cache.
Before you begin
You need:
- React 19;
@tanstack/react-router1.170.33 or later, below 2.0.0. The integration imports it, so a Start app installs it beside@tanstack/react-start.
1. Install the router
Install @tanstack/react-router, even in a Start app:
pnpm add @tanstack/react-router2. Connect the client where the router is made
That's Start's getRouter, or your server and browser entries. Make the
client with the router, give it a staleTime, and connect it to no
other router:
import * as from "effect/ManagedRuntime";
import { } from "@monarcode/effetch-query";
import { } from "@monarcode/effetch-query/react/tanstack-router";
import {
,
,
,
,
} from "@tanstack/react-router";
import { } from "./api.js";
import { } from "./todo-list.js";
import { } from "./todos.js";
export const = <{
readonly : .;
}>()({ : });
const = ({
: () => ,
: "/",
// Returns the cached value while it's fresh, and fetches it otherwise.
: ({ }) => ..(()),
: ,
});
// Builds your services once, for every request's client to share.
const = .();
// Start calls `getRouter` once per request on the server, and once in the
// browser, so each request gets its own client.
export function () {
const = .({
: ,
: { : { : "30 seconds" } },
});
const = ({
: .([]),
: { },
// Loaders always run, and the queries' staleTime decides what's fetched.
: 0,
});
({ , });
return ;
}The sample is trimmed to the parts Effetch Query needs. In a Start app,
the route tree is generated, and the root route renders the document, as
the
tanstack-start example's
__root.tsx does.
Load data in loaders with context.queryClient.fetch(query), which
returns the cached value while it's fresh. defaultPreloadStaleTime: 0
lets the queries' staleTime decide what's refetched, rather than the
router's own loader cache. Without a staleTime, nothing is ever fresh:
every loader run fetches, and the browser refetches what the server sent.
What the integration does
From there, the integration does the rest:
- On the server, what the loaders loaded goes with the page, and queries started while rendering stream in as they start, those still loading as promises the browser waits for. A loader can start a prefetch without awaiting it, as Frameworks explains. The client is disposed when the request ends, so on the server it must be the request's own.
- In the browser, it all loads into the client before React hydrates,
and nothing is fetched while it's fresh. The integration wraps the
router in a
QueryProviderfor the client, so you render none. - Preloading a route on hover runs its loader, and
client.fetchfetches only what's stale. - Only queries with a schema cross to the browser, as What's sent explains.
Redirect from a query
A query or mutation that dies with the router's redirect() navigates
there. Make the redirect inside the Effect, and use Effect.die, as
Redirect from a query explains:
import * as from "effect/Effect";
import * as from "effect/Schema";
import { } from "@monarcode/effetch-query";
import { } from "@tanstack/react-router";
import { } from "./api.js";
const = .({ : . });
export const = .({
: ["viewer"],
: .(() => .("/me", { : })).(
.("HttpError", () =>
. === 401
? .(({ : "/login" }))
: .(),
),
),
: { : },
});If your client maps a 401 to its own error with statusErrors, catch
that error's tag, as the
tanstack-start
and
react-router
examples do with Unauthorized. See
Errors by status. A 401 whose
body doesn't decode stays an HttpError, so keep that branch if your
server can send one.
In a loader, client.fetch rejects with the redirect and the router
follows it, on the server too. Load a query that may redirect with
client.fetch. client.prefetch never rejects, so the router doesn't
get the redirect: the components that read the query show it as a
failure. A preload's redirect is dropped, as the router drops it.
In the browser, the integration also follows a redirect from a fetch
that nothing awaits, such as one a component starts, unless you turn off
handleRedirects.
Guard every page under a layout
To check the user once for every page under a layout, fetch the query in
the layout route's beforeLoad, which runs before any page below it
loads. What it returns joins those pages' context:
import { , } from "@tanstack/react-router";
import { } from "./router.js";
import { } from "./viewer.js";
export const = ({
: () => ,
: "signed-in",
// Redirects to /login when the user isn't signed in.
: async ({ }) => ({
: await ..(),
}),
: ,
});
export const = ({
: () => ,
: "/profile",
: ({ }) => ..,
});The
tanstack-start example
does the same with its _app layout. The pages' loaders wait for the
guard, so give its query a staleTime: while it's fresh, fetch answers
from the cache at once.
Options
connectQueryClient takes the following options besides router and
queryClient:
| Option | What it does | Default |
|---|---|---|
dehydrate | queries to send only some queries, and failures: "include" to send failures, as QueryClient.dehydrate takes them. Queries still loading are always sent, as promises. | Every query, without failures |
handleRedirects | In the browser, follow a redirect() a query or mutation fails or dies with, unless an Effect awaits the fetch, as a loader's client.fetch does. | true |
wrapQueryClient | Wrap the router's Wrap in a QueryProvider for the client. With false, render your own. | true |
What's next
- The
tanstack-startexample: a whole Start app, with sign-in, a guarded layout and streamed pages.tanstack-start-httpclientis the same app with Effect'sHttpClient. - Stream the cache: what happens to a query still loading when the page is sent.
- Sign out and switch accounts: keep one user's cached data away from the next.