TanStack Router
Keep the client in Router context, guard private routes before they load, and use the hooks without a provider.
Your app uses TanStack Router, and some of its routes are for signed-in users
only. In this guide, you add Session kit to the app from Getting started: a
sign-in route, private routes that send signed-out users to it, and hooks that
read the client from the Router. The guards run in beforeLoad, so a private
route never loads or renders for someone who isn't signed in.
The hooks come from @monarcode/session-kit/tanstack-router. They're typed by
the Router you register, and they need no AuthProvider. A complete app is in
examples/tanstack-router.
For TanStack Start in SPA mode, follow this guide with the changes for Start. For TanStack Start with server rendering, follow TanStack Start instead.
Before you begin
- A Vite app with React, using
@vitejs/plugin-react. Installation adds a plugin to itsvite.config.ts. - The app from Getting started, through step 3. This
guide uses its client in
src/auth.tsand its form insrc/sign-in.tsx.
Installation
Install Session kit, the Router and Zod, and the Router's Vite plugin as a dev dependency:
npm install @monarcode/session-kit @tanstack/react-router zod
npm install -D @tanstack/router-pluginThis guide uses file-based routing: the plugin generates
src/routeTree.gen.ts from the files under src/routes. Add it to
vite.config.ts, before the React plugin, or the build fails:
import { } from "@tanstack/router-plugin/vite";
import from "@vitejs/plugin-react";
import { } from "vite";
export default ({
: [
({ : "react", : true }),
(),
],
});1. Type the root route
The root route declares that Router context holds the client, so every guard
gets a typed context.auth. It stays mounted while pages come and go, which
makes it the place to show auth errors:
import { } from "@monarcode/session-kit/tanstack-router";
import { , } from "@tanstack/react-router";
import type { } from "../auth.js";
export const = <{ : }>()({
: ,
});
function () {
// Shows failures that outlive the page that caused them, such as a sign-out
// that couldn't clear storage.
const = (() => .);
return (
<>
{ && < ="alert">{.}</>}
< />
</>
);
}useAuth reads the client's state from Router context. It's typed with your
user after you register the Router in step 4, and it's typed never until
then.
2. Add the sign-in route
The sign-in route renders the form from Getting started. Its guard sends a user who's already signed in on to the page they asked for:
import { } from "@monarcode/session-kit";
import { } from "@monarcode/session-kit/tanstack-router";
import { } from "@tanstack/react-router";
import { } from "../sign-in.js";
export const = ("/login")({
: (: <string, unknown>) => ({
: (.redirectTo),
}),
: ({ , }) =>
(., { : . }),
: ,
});The form doesn't navigate after it signs in, because this guard does it. When the session changes, the Router runs the guard again, and it sends the signed-in user on. Step 4 sets that up.
redirectTo is the search param that the private routes' guard sets.
safeReturnTo turns it into a path that's safe to send the user to. Anything
that leads out of your app, or back to the sign-in page, becomes /, so a
stale redirectTo can't loop. redirectIfSignedIn checks it the same way.
The safeReturnTo reference lists every
rule.
3. Guard private routes
Guard private routes with a pathless layout route. Its child routes are
guarded without _authenticated appearing in their URLs:
import {
,
,
,
} from "@monarcode/session-kit/tanstack-router";
import {
,
type ,
} from "@tanstack/react-router";
export const = ("/_authenticated")({
: ({ , }) =>
(., { }),
: ,
: () => < ={<>Checking session…</>} />,
});
/** Shown after a failed refresh; a repeated failure shows here again. */
function ({ }: ) {
const = ();
return (
< ="alert">
<>{ instanceof ? . : "Something went wrong"}</>
< ={() => void .().(() => {})}>Retry</>
</>
);
}requireSession lets a signed-in user through, and puts { session } in
route context. It sends a signed-out user to /login, or the loginPath you
pass, with redirectTo set to where they were going. A signed-out user who
opens /orders?tab=2 lands on /login?redirectTo=%2Forders%3Ftab%3D2, and
returns to /orders?tab=2 after signing in.
A session that can't be used isn't a sign-out. When the access token has
expired and a refresh fails, such as while your backend is down, the status
is unavailable. The saved session is kept, and auth.retry() can restore
access. So requireSession doesn't redirect: it throws the error to the
route's error component, which offers a retry. If the retry fails too, the
new error shows there again.
SessionOutlet renders the child routes while the session the guard accepted
is still the signed-in one. After a sign-out or an account switch, it shows
pending until the guard runs again. It also remounts the child routes for
the new account, so nothing from the previous one stays on screen. Profile
updates and token refreshes keep them mounted.
Child routes read the session from route context, where user is typed and
never null:
import { } from "@monarcode/session-kit/tanstack-router";
import { } from "@tanstack/react-router";
export const = ("/_authenticated/")({
: ,
});
function () {
const { } = .();
const = ();
return (
<>
<>Welcome, {..}</>
< ={() => void .().(() => {})}>
Sign out
</>
</>
);
}A sign-out that fails shows in the root route's alert from step 1, so the button can ignore the rejection.
4. Create and connect the Router
Create the Router with the client in its context, then connect the two:
import { } from "@monarcode/session-kit/tanstack-router";
import { } from "@tanstack/react-router";
import { } from "./auth.js";
import { } from "./routeTree.gen.js";
export const = ({
,
: { },
: () => <>Loading…</>,
});
// Restores the session, runs expiry timers and tab sync, and re-runs guards
// when auth changes. Call it once, beside the Router.
export const = ();
declare module "@tanstack/react-router" {
interface Register {
: typeof ;
}
}connectAuth does for the Router what AuthProvider does for a plain React
app: it restores the saved session, starts the refresh timer, and follows
other tabs. When the session changes, it does two more things:
- It clears the Router's cached and preloaded route data, so one account's data never shows for the next.
- It runs the guards again, so a sign-in on the sign-in page sends the user on, and a sign-out in another tab redirects this one.
Registering the Router types useAuth and useAuthClient with your client.
5. Render the app
Render the Router in src/main.tsx:
import { } from "react";
import { } from "@tanstack/react-router";
import { } from "react-dom/client";
import { } from "./router.js";
(.("root")!).(
<>
< ={} />
</>,
);To check the app:
- Signed out, open
/. The Router sends you to/login?redirectTo=%2F. - Sign in. You're back on
/, with the welcome message. - Reload the page. You're still signed in.
- Open a second tab and sign out there. The first tab goes to
/login.
Layouts around guarded pages
A guarded route often has UI of its own around its pages, such as a sidebar
and a top bar. Render it in the route's component, with SessionOutlet where
the pages go:
import { } from "react";
import { , } from "@monarcode/session-kit/tanstack-router";
/** The guarded route's component: `component: Dashboard`. */
export function () {
// From state, not route context: this stays mounted through a sign-out.
const = (() => .);
const = (() => .);
return (
< ="dashboard">
<>{ ? `Signed in as ${.}` : null}</>
{/* Keyed by session: one account's choices never show for the next. */}
< ={} />
<>
< ={<>Checking session…</>} />
</>
</>
);
}
function () {
const [, ] = (false);
return (
<>
< ={() => (!)}>
{ ? "Unpin" : "Pin"}
</>
</>
);
}In the guarded route's component, SessionOutlet reads the session that
route's guard accepted. Three things follow from where it sits:
- It protects only what it renders. After a sign-out or an account switch,
the pages are swapped for
pendingand remounted, but the layout around them stays mounted until the guard redirects. - Read the user from state there. In the layout, use
useAuth((state) => state.user)and handlenull. Route context'ssession.useris the session the guard accepted, which for that moment is the previous one. Inside the pages, route context's session is always the signed-in one. - Key what belongs to an account. Layout UI that holds state for one
account, such as a draft or an open panel, takes the session as its
key, so the next account starts fresh.
TanStack Start in SPA mode
TanStack Start's SPA mode is TanStack Router with an HTML shell that the build
prerenders. Start renders the whole document from the root route, and the
browser takes over from there. Steps 2 and 3 apply as they are. In place of
Installation and steps 1, 4 and 5, follow these steps. Complete apps are in
examples/tanstack-start-spa
and, written with Effect and effetch, in
examples/tanstack-start-spa-effetch.
1. Install Start
Install Session kit, the Router and Zod, and Start in place of the Router's Vite plugin:
npm install @monarcode/session-kit @tanstack/react-router zod
npm install @tanstack/react-start2. Use Start's Vite plugin
In vite.config.ts, use Start's plugin with SPA mode on, in place of the
Router plugin:
import { } from "@tanstack/react-start/plugin/vite";
import from "@vitejs/plugin-react";
import { } from "vite";
export default ({
: [({ : { : true } }), ()],
});3. Render the document from the root route
Give the root route a shellComponent that renders the document, with
<HeadContent /> and <Scripts />. Start renders the app from it, so delete
src/main.tsx and index.html:
import type { } from "react";
import { } from "@monarcode/session-kit/tanstack-router";
import {
,
,
,
,
} from "@tanstack/react-router";
import type { } from "../auth.js";
export const = <{ : }>()({
: ,
: ,
});
function ({ }: { : }) {
return (
< ="en">
<>
< />
</>
<>
{}
< />
</>
</>
);
}
function () {
// Shows failures that outlive the page that caused them.
const = (() => .);
return (
<>
{ && < ="alert">{.}</>}
< />
</>
);
}4. Create the Router in getRouter
Start creates the Router itself, by calling getRouter() from
src/router.tsx. Create the Router and connect auth there:
import { } from "@monarcode/session-kit/tanstack-router";
import { } from "@tanstack/react-router";
import { } from "./auth.js";
import { } from "./routeTree.gen.js";
export function () {
const = ({
,
: { },
: () => <>Loading…</>,
});
// Does nothing while the build prerenders the shell.
();
return ;
}
declare module "@tanstack/react-router" {
interface Register {
: <typeof >;
}
}connectAuth does nothing while the Router renders on a server, so the shell
that the build prerenders shows your pending component. getRouter() doesn't
keep the function that connectAuth returns, because the Router lasts as
long as the page.
5. Turn off server rendering for routes
Start's own server still answers requests in SPA mode, and it has no saved
session to check. Turn server rendering off for routes in src/start.ts, so
the guards run in the browser:
import { } from "@tanstack/react-start";
// The session is in browser storage, so guards must run in the browser.
export const = (() => ({
: false,
}));Things to know
- Another sign-in page. If sign-in isn't at
/login, pass the sameloginPathtorequireSession,redirectIfSignedInandsafeReturnTo. - The first render. The guards wait for the saved session, so a signed-in user never sees the sign-in page. With synchronous storage and a synchronous schema, the session is restored before the first paint.
- Stopping. Call
disconnectAuthon app teardown or hot-module disposal. It stops background work without signing out. - Locked sessions. Locking is for native apps, so the guards treat a locked session as signed out.
- Cached data.
connectAuthclears the Router's own cache. Scope your other private caches, such as TanStack Query results, tostate.sessionId, which is new on every sign-in. See State.
Next steps
- Call your API with
authFetch, as in Getting started, or with ky, axios or openapi-fetch. It works unchanged with the Router. - Using the client: update the user, sign out, and use the client's other methods.
- Effect and effetch: use the same client as an Effect service.
- TanStack Router reference: every option
of the guards,
SessionOutletandconnectAuth.