# TanStack Router (https://session-kit.pages.dev/docs/setups/tanstack-router)

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`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-router).

For TanStack Start in SPA mode, follow this guide with
[the changes for Start](#tanstack-start-in-spa-mode). For TanStack Start with
server rendering, follow [TanStack Start](https://session-kit.pages.dev/docs/setups/tanstack-start)
instead.

## Before you begin

- A Vite app with React, using `@vitejs/plugin-react`. Installation adds a
  plugin to its `vite.config.ts`.
- The app from [Getting started](https://session-kit.pages.dev/docs/getting-started), through step 3. This
  guide uses its client in `src/auth.ts` and its form in `src/sign-in.tsx`.

## Installation

Install Session kit, the Router and Zod, and the Router's Vite plugin as a
dev dependency:

```npm
npm install @monarcode/session-kit @tanstack/react-router zod
npm install -D @tanstack/router-plugin
```

This 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:

```ts title="vite.config.ts"
import { tanstackRouter } from "@tanstack/router-plugin/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    tanstackRouter({ target: "react", autoCodeSplitting: true }),
    react(),
  ],
});
```

## 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:

```tsx title="src/routes/__root.tsx"
import { useAuth } from "@monarcode/session-kit/tanstack-router";
import { createRootRouteWithContext, Outlet } from "@tanstack/react-router";

import type { AppAuth } from "../auth.js";

export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({
  component: Root,
});

function Root() {
  // Shows failures that outlive the page that caused them, such as a sign-out
  // that couldn't clear storage.
  const error = useAuth((state) => state.error);
  return (
    <>
      {error && <p role="alert">{error.message}</p>}
      <Outlet />
    </>
  );
}
```

`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:

```tsx title="src/routes/login.tsx"
import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/tanstack-router";
import { createFileRoute } from "@tanstack/react-router";

import { SignIn } from "../sign-in.js";

export const Route = createFileRoute("/login")({
  validateSearch: (search: Record<string, unknown>) => ({
    redirectTo: safeReturnTo(search.redirectTo),
  }),
  beforeLoad: ({ context, search }) =>
    redirectIfSignedIn(context.auth, { redirectTo: search.redirectTo }),
  component: SignIn,
});
```

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](https://session-kit.pages.dev/docs/reference/core#safereturnto) 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:

```tsx title="src/routes/_authenticated.tsx"
import {
  requireSession,
  SessionOutlet,
  useAuthClient,
} from "@monarcode/session-kit/tanstack-router";
import {
  createFileRoute,
  type ErrorComponentProps,
} from "@tanstack/react-router";

export const Route = createFileRoute("/_authenticated")({
  beforeLoad: ({ context, location }) =>
    requireSession(context.auth, { location }),
  errorComponent: SessionError,
  component: () => <SessionOutlet pending={<p>Checking session…</p>} />,
});

/** Shown after a failed refresh; a repeated failure shows here again. */
function SessionError({ error }: ErrorComponentProps) {
  const auth = useAuthClient();
  return (
    <div role="alert">
      <p>{error instanceof Error ? error.message : "Something went wrong"}</p>
      <button onClick={() => void auth.retry().catch(() => {})}>Retry</button>
    </div>
  );
}
```

`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`:

```tsx title="src/routes/_authenticated/index.tsx"
import { useAuthClient } from "@monarcode/session-kit/tanstack-router";
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/_authenticated/")({
  component: Home,
});

function Home() {
  const { session } = Route.useRouteContext();
  const auth = useAuthClient();
  return (
    <main>
      <h1>Welcome, {session.user.firstName}</h1>
      <button onClick={() => void auth.signOut().catch(() => {})}>
        Sign out
      </button>
    </main>
  );
}
```

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:

```tsx title="src/router.tsx"
import { connectAuth } from "@monarcode/session-kit/tanstack-router";
import { createRouter } from "@tanstack/react-router";

import { auth } from "./auth.js";
import { routeTree } from "./routeTree.gen.js";

export const router = createRouter({
  routeTree,
  context: { auth },
  defaultPendingComponent: () => <p>Loading…</p>,
});

// Restores the session, runs expiry timers and tab sync, and re-runs guards
// when auth changes. Call it once, beside the Router.
export const disconnectAuth = connectAuth(router);

declare module "@tanstack/react-router" {
  interface Register {
    router: typeof router;
  }
}
```

`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`:

```tsx title="src/main.tsx" app="vite"
import { StrictMode } from "react";

import { RouterProvider } from "@tanstack/react-router";
import { createRoot } from "react-dom/client";

import { router } from "./router.js";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <RouterProvider router={router} />
  </StrictMode>,
);
```

To check the app:

1. Signed out, open `/`. The Router sends you to `/login?redirectTo=%2F`.
2. Sign in. You're back on `/`, with the welcome message.
3. Reload the page. You're still signed in.
4. 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:

```tsx title="src/dashboard.tsx"
import { useState } from "react";

import { SessionOutlet, useAuth } from "@monarcode/session-kit/tanstack-router";

/** The guarded route's component: `component: Dashboard`. */
export function Dashboard() {
  // From state, not route context: this stays mounted through a sign-out.
  const user = useAuth((state) => state.user);
  const sessionId = useAuth((state) => state.sessionId);
  return (
    <div className="dashboard">
      <header>{user ? `Signed in as ${user.firstName}` : null}</header>
      {/* Keyed by session: one account's choices never show for the next. */}
      <Sidebar key={sessionId} />
      <main>
        <SessionOutlet pending={<p>Checking session…</p>} />
      </main>
    </div>
  );
}

function Sidebar() {
  const [pinned, setPinned] = useState(false);
  return (
    <nav>
      <button onClick={() => setPinned(!pinned)}>
        {pinned ? "Unpin" : "Pin"}
      </button>
    </nav>
  );
}
```

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 `pending` and 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 handle `null`. Route context's
  `session.user` is 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`](https://github.com/monarcode/session-kit/tree/main/examples/tanstack-start-spa)
and, written with Effect and effetch, in
[`examples/tanstack-start-spa-effetch`](https://github.com/monarcode/session-kit/tree/main/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
npm install @monarcode/session-kit @tanstack/react-router zod
npm install @tanstack/react-start
```

### 2. Use Start's Vite plugin

In `vite.config.ts`, use Start's plugin with SPA mode on, in place of the
Router plugin:

```ts title="vite.config.ts" app="start"
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [tanstackStart({ spa: { enabled: true } }), react()],
});
```

### 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`:

```tsx title="src/routes/__root.tsx" app="start"
import type { ReactNode } from "react";

import { useAuth } from "@monarcode/session-kit/tanstack-router";
import {
  createRootRouteWithContext,
  HeadContent,
  Outlet,
  Scripts,
} from "@tanstack/react-router";

import type { AppAuth } from "../auth.js";

export const Route = createRootRouteWithContext<{ auth: AppAuth }>()({
  shellComponent: Document,
  component: Root,
});

function Document({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <head>
        <HeadContent />
      </head>
      <body>
        {children}
        <Scripts />
      </body>
    </html>
  );
}

function Root() {
  // Shows failures that outlive the page that caused them.
  const error = useAuth((state) => state.error);
  return (
    <>
      {error && <p role="alert">{error.message}</p>}
      <Outlet />
    </>
  );
}
```

### 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:

```tsx title="src/router.tsx" app="start"
import { connectAuth } from "@monarcode/session-kit/tanstack-router";
import { createRouter } from "@tanstack/react-router";

import { auth } from "./auth.js";
import { routeTree } from "./routeTree.gen.js";

export function getRouter() {
  const router = createRouter({
    routeTree,
    context: { auth },
    defaultPendingComponent: () => <p>Loading…</p>,
  });
  // Does nothing while the build prerenders the shell.
  connectAuth(router);
  return router;
}

declare module "@tanstack/react-router" {
  interface Register {
    router: ReturnType<typeof getRouter>;
  }
}
```

`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:

```ts title="src/start.ts" app="start"
import { createStart } from "@tanstack/react-start";

// The session is in browser storage, so guards must run in the browser.
export const startInstance = createStart(() => ({
  defaultSsr: false,
}));
```

## Things to know

- **Another sign-in page.** If sign-in isn't at `/login`, pass the same
  `loginPath` to `requireSession`, `redirectIfSignedIn` and `safeReturnTo`.
- **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](https://session-kit.pages.dev/docs#what-it-does).
- **Stopping.** Call `disconnectAuth` on app teardown or hot-module disposal.
  It stops background work without signing out.
- **Locked sessions.** [Locking](https://session-kit.pages.dev/docs/client/locking) is for native apps, so
  the guards treat a locked session as signed out.
- **Cached data.** `connectAuth` clears the Router's own cache. Scope your
  other private caches, such as TanStack Query results, to `state.sessionId`,
  which is new on every sign-in. See [State](https://session-kit.pages.dev/docs/client/state).

## Next steps

- [Call your API](https://session-kit.pages.dev/docs/getting-started#5-call-your-api) with `authFetch`, as
  in Getting started, or with
  [ky, axios or openapi-fetch](https://session-kit.pages.dev/docs/client/other-http-clients). It works
  unchanged with the Router.
- [Using the client](https://session-kit.pages.dev/docs/client): update the user, sign out, and use the
  client's other methods.
- [Effect and effetch](https://session-kit.pages.dev/docs/effect): use the same client as an Effect
  service.
- [TanStack Router reference](https://session-kit.pages.dev/docs/reference/tanstack-router): every option
  of the guards, `SessionOutlet` and `connectAuth`.