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

Your app uses React 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, in
the mode your app uses. React Router has three modes, and Session kit guards
each one the way that mode works:

| Mode                         | The guard                                    | Beside it                              |
| ---------------------------- | -------------------------------------------- | -------------------------------------- |
| Declarative                  | `SessionOutlet`                              | Nothing                                |
| Data                         | `requireSessionLoader` as the `loader`       | `SessionOutlet`, `useAuthRevalidation` |
| Framework, with `ssr: false` | `requireSessionLoader` as the `clientLoader` | `SessionOutlet`, `useAuthRevalidation` |

Each mode has a complete example app. For framework mode with server
rendering, follow
[React Router with server rendering](https://session-kit.pages.dev/docs/setups/react-router-ssr) instead.

## Before you begin

- The app from [Getting started](https://session-kit.pages.dev/docs/getting-started), through step 5. This
  guide uses its client in `src/auth.ts`, its form in `src/sign-in.tsx`, and
  `fetchProfile` from `src/api.ts`.
- React Router 7 or 8. React Router 8 needs React 19.2.7 or newer, so with
  React 18, use React Router 7. [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility)
  lists the versions.

## Installation

Install Session kit, React Router and Zod:

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

## Add a page to protect

Every mode on this page protects the same page. It reads the user and the
client with the hooks from `@monarcode/session-kit/react`:

```tsx title="src/home.tsx"
import { useAuth, useAuthClient } from "@monarcode/session-kit/react";

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

Each mode renders `AuthProvider` and registers the client's type, as step 4
of Getting started does, so these hooks carry your user. A sign-out that
fails shows in an alert that each mode renders outside the private routes, so
the button can ignore the rejection.

`AuthProvider` restores the saved session when it mounts. With `localStorage`
and a synchronous schema, that happens
[before the first paint](https://session-kit.pages.dev/docs#what-it-does).

## Declarative mode

Declarative mode has no loaders, so `SessionOutlet` is the guard. Render it
as a layout route's element, `<Route element={<Private />}>`, and the routes
inside it render only while someone is signed in. `AuthProvider` goes around
the router:

```tsx title="src/main.tsx"
import { StrictMode } from "react";
import {
  BrowserRouter,
  Navigate,
  Route,
  Routes,
  useSearchParams,
} from "react-router";

import { isSignedIn, safeReturnTo } from "@monarcode/session-kit";
import { AuthProvider, useAuth } from "@monarcode/session-kit/react";
import { SessionOutlet } from "@monarcode/session-kit/react-router";
import { createRoot } from "react-dom/client";

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

// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
  interface Register {
    auth: typeof auth;
  }
}

/** The guard: its child routes render only while someone is signed in. */
function Private() {
  return (
    <SessionOutlet
      pending={<p>Checking session…</p>}
      unavailable={({ error, retry }) => (
        <div role="alert">
          <p>{error?.message ?? "Can't reach the server."}</p>
          <button onClick={retry}>Try again</button>
        </div>
      )}
    />
  );
}

/** Signing in changes the state, which renders this again and redirects. */
function Login() {
  const signedIn = useAuth(isSignedIn);
  const [search] = useSearchParams();
  if (signedIn)
    return <Navigate to={safeReturnTo(search.get("redirectTo"))} replace />;
  return <SignIn />;
}

/**
 * Failures that outlive the page that caused them, such as a sign-out that
 * couldn't clear storage.
 */
function AuthErrorMessage() {
  const error = useAuth((state) => state.error);
  return error ? <p role="alert">{error.message}</p> : null;
}

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <AuthProvider client={auth}>
      <AuthErrorMessage />
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route element={<Private />}>
            <Route index element={<Home />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  </StrictMode>,
);
```

`SessionOutlet` shows `pending` while the saved session is restored. 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 there after
signing in. After a failed refresh, it renders `unavailable`. Without
`unavailable`, it throws the error to the nearest error boundary.

`Login` sends a signed-in user on to `redirectTo`, so the form doesn't
navigate after it signs in. `safeReturnTo` turns `redirectTo` 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. The
[`safeReturnTo` reference](https://session-kit.pages.dev/docs/reference/core#safereturnto) lists every
rule.

A complete app is in
[`examples/react-router-declarative`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-declarative).

## Data mode

In data mode, loaders run before a route renders, so the guard goes there. A
signed-out user is redirected before a private route renders. The router
goes in its own file, and `src/main.tsx` renders it.

### 1. Create the router

Guard the private routes with a loader, and keep the guards in step with the
session from the root route:

```tsx title="src/router.tsx" app="data"
import { createBrowserRouter, Outlet, useRouteError } from "react-router";

import { useAuth, useAuthClient } from "@monarcode/session-kit/react";
import {
  redirectIfSignedInLoader,
  requireSessionLoader,
  SessionOutlet,
  useAuthRevalidation,
} from "@monarcode/session-kit/react-router";

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

/** Runs the loaders again when auth changes, and shows auth errors. */
function Root() {
  useAuthRevalidation();
  const error = useAuth((state) => state.error);
  return (
    <>
      {error && <p role="alert">{error.message}</p>}
      <Outlet />
    </>
  );
}

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

export const router = createBrowserRouter([
  {
    element: <Root />,
    HydrateFallback: () => <p>Checking session…</p>,
    children: [
      {
        path: "/login",
        loader: redirectIfSignedInLoader(auth),
        element: <SignIn />,
      },
      {
        loader: requireSessionLoader(auth),
        errorElement: <SessionError />,
        element: <SessionOutlet pending={<p>Checking session…</p>} />,
        children: [{ index: true, element: <Home /> }],
      },
    ],
  },
]);
```

Three pieces work together:

- **`requireSessionLoader(auth)`** is the route's loader. It returns
  `{ session }` as the route's loader data. It sends a signed-out user to
  `/login`, or the `loginPath` you pass, with `redirectTo` set to the path
  and query they asked for: `/orders?tab=2` lands on
  `/login?redirectTo=%2Forders%3Ftab%3D2`. A failed refresh goes to the
  route's error element instead, as
  [Things to know](#things-to-know) explains. A loader that does more calls
  `requireSession`, as [Guards in loaders](#guards-in-loaders) shows.
- **`useAuthRevalidation`** runs the loaders again when the session changes,
  such as after a sign-in, a sign-out or an account switch, so the guards
  check it again. Call it one time, in the root route.
  [Its reference](https://session-kit.pages.dev/docs/reference/react-router#useauthrevalidation) lists
  every change it reacts to.
- **`SessionOutlet`**, as the guarded route's element, renders child routes
  only while the session the loader accepted is still the signed-in one. When
  another account signs in, it shows `pending` until the loader has run for
  the new session, so no page shows the previous account's loader data.

The sign-in route's `redirectIfSignedInLoader` runs again after a sign-in,
and sends the user on to `redirectTo`, so the form doesn't navigate. The root
route's `HydrateFallback` shows until the first loaders finish, such as while
the saved session is restored.

### 2. Render the router

Render the router inside `AuthProvider`, in `src/main.tsx`:

```tsx title="src/main.tsx" app="data"
import { StrictMode } from "react";
import { RouterProvider } from "react-router/dom";

import { AuthProvider } from "@monarcode/session-kit/react";
import { createRoot } from "react-dom/client";

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

// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
  interface Register {
    auth: typeof auth;
  }
}

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

A complete app is in
[`examples/react-router-data`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-data).

## Framework mode with `ssr: false`

Framework mode without a server is data mode with route modules. The guards
are the same, as each route's `clientLoader`. Keep the files from Getting
started, and `home.tsx` from [Add a page to protect](#add-a-page-to-protect),
in `app/`. Framework mode also needs `@react-router/dev`, which a
framework-mode app already has.

### 1. Turn off server rendering

In `react-router.config.ts`, set `ssr` to `false`. The build then prerenders
`index.html` from the root route, and everything else runs in the browser,
where the session is saved:

```ts title="react-router.config.ts"
import type { Config } from "@react-router/dev/config";

export default { ssr: false } satisfies Config;
```

### 2. Provide the client in the root route

In framework mode, `AuthProvider` goes in the root route. The root route also
keeps the guards in step with the session, and shows auth errors:

```tsx title="app/root.tsx"
import type { ReactNode } from "react";
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";

import { AuthProvider, useAuth } from "@monarcode/session-kit/react";
import { useAuthRevalidation } from "@monarcode/session-kit/react-router";

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

// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
  interface Register {
    auth: typeof auth;
  }
}

export function Layout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <Meta />
        <Links />
      </head>
      <body>
        {children}
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}

/** Runs the client loaders again when auth changes, and shows auth errors. */
function Root() {
  useAuthRevalidation();
  const error = useAuth((state) => state.error);
  return (
    <>
      {error && <p role="alert">{error.message}</p>}
      <Outlet />
    </>
  );
}

export default function App() {
  return (
    <AuthProvider client={auth}>
      <Root />
    </AuthProvider>
  );
}

/** Prerendered into index.html, and shown until the client loaders finish. */
export function HydrateFallback() {
  return <p>Checking session…</p>;
}
```

`AuthProvider` mounts the client in an effect, so the build-time prerender of
the root route starts nothing, and the browser restores the session.

### 3. Guard a layout route

Guard a layout route with `requireSessionLoader` as its `clientLoader`. The
private routes go under it in step 5:

```tsx title="app/routes/protected.tsx"
import { useRouteError } from "react-router";

import { useAuthClient } from "@monarcode/session-kit/react";
import {
  requireSessionLoader,
  SessionOutlet,
} from "@monarcode/session-kit/react-router";

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

export const clientLoader = requireSessionLoader(auth);

export default function Protected() {
  return <SessionOutlet pending={<p>Checking session…</p>} />;
}

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

### 4. Add the sign-in route

The sign-in route sends a signed-in user on to `redirectTo`. Its loader runs
again after a sign-in, so the form doesn't navigate:

```tsx title="app/routes/login.tsx"
import { redirectIfSignedInLoader } from "@monarcode/session-kit/react-router";

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

export const clientLoader = redirectIfSignedInLoader(auth);

export default SignIn;
```

### 5. Register the routes

In `app/routes.ts`, nest the private routes under the layout:

```ts title="app/routes.ts"
import {
  index,
  layout,
  route,
  type RouteConfig,
} from "@react-router/dev/routes";

export default [
  route("login", "routes/login.tsx"),
  layout("routes/protected.tsx", [index("routes/home.tsx")]),
] satisfies RouteConfig;
```

`routes/home.tsx` is the page from Add a page to protect, as its default
export: `export { Home as default } from "../home.js";`.

A complete app is in
[`examples/react-router-framework-spa`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-spa).

## Check the app

Whichever mode you chose, check the app:

1. Signed out, open `/`. You land on `/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`.

## Guards in loaders

Two functions guard a loader, in data mode and in framework mode. Both send a
signed-out user to `/login`, with `redirectTo`, and resolve `{ session }`,
typed with your user:

- **`requireSessionLoader(auth)`** is the whole loader. Use it on a route
  that guards and loads nothing else, usually the layout route around your
  private pages, as in [Data mode](#data-mode).
- **`requireSession(auth, { request })`** is a call inside a loader of your
  own. Use it when the loader loads data too: data that only signed-in users
  can load, or data that needs who is signed in.

React Router runs the loaders of nested routes at the same time, so a page's
loader doesn't wait for its layout's guard. A page whose loader calls your
API checks the session itself:

```tsx title="app/routes/profile.tsx"
import { useLoaderData } from "react-router";

import { requireSession } from "@monarcode/session-kit/react-router";

import { fetchProfile } from "../api.js";
import { auth } from "../auth.js";

export async function clientLoader({ request }: { request: Request }) {
  const { session } = await requireSession(auth, { request });
  return { name: session.user.firstName, profile: await fetchProfile() };
}

export default function Profile() {
  const { name, profile } = useLoaderData<typeof clientLoader>();
  return (
    <p>
      {name}, your email is {profile.email}.
    </p>
  );
}
```

In framework mode, add the page beside the index route in `app/routes.ts`:
`route("profile", "routes/profile.tsx")`. A signed-out user is redirected
before your API is called, rather than after a request that fails. Pass
`requireSession` the same `loginPath` and `basename` as the layout's guard.

The sign-in page has the same pair: `redirectIfSignedInLoader(auth)` as its
loader, or `redirectIfSignedIn(auth, { redirectTo })` in a loader that does
more.

## 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 guarded route's element, with `SessionOutlet`
where the pages go:

```tsx title="src/dashboard.tsx"
import { useAuth } from "@monarcode/session-kit/react";
import { SessionOutlet } from "@monarcode/session-kit/react-router";

/** The guarded route's element: `element: <Dashboard />`. */
export function Dashboard() {
  // From state, not loader data: 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. */}
      <nav key={sessionId}>…</nav>
      <main>
        <SessionOutlet pending={<p>Checking session…</p>} />
      </main>
    </div>
  );
}
```

Three things follow from where `SessionOutlet` sits:

- **It protects only what it renders.** After a sign-out it redirects to the
  sign-in page. After an account switch it remounts the pages, and in data
  and framework mode shows `pending` until the guard runs again. The layout
  around it stays mounted meanwhile.
- **Read the user from state there.** In the layout, use
  `useAuth((state) => state.user)` and handle `null`. The loader's `session`
  is the one the guard accepted, which for that moment is the previous 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.

## Things to know

- **Another sign-in page.** If sign-in isn't at `/login`, pass the same
  `loginPath` to `SessionOutlet`, `requireSessionLoader` (or
  `requireSession`), `redirectIfSignedInLoader` and `safeReturnTo`.
- **A router `basename`.** Pass it to `requireSessionLoader` or
  `requireSession` too, so `redirectTo` leaves it out. Redirects add it
  again. `SessionOutlet` needs nothing.
- **A failed refresh is not a redirect.** 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 the guards don't redirect. In declarative mode, `SessionOutlet`
  renders `unavailable`, or throws to the nearest error boundary without it.
  In data and framework mode, the guard rethrows the error for the route's
  error element. If the retry fails too, the new error shows there again.
- **A route's own `shouldRevalidate`.** It decides whether that route's
  loader runs again, even after the session changes. If it returns `false`,
  the guard in that loader doesn't run. Return `defaultShouldRevalidate` for
  the cases it doesn't handle.
- **The fragment.** A loader's request leaves out the URL's `#fragment`, so
  the loader guards' `redirectTo` doesn't keep it. `SessionOutlet` keeps it.
- **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.** Scope private cached data, 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.
- [React Router reference](https://session-kit.pages.dev/docs/reference/react-router): every option of the
  guards, `SessionOutlet` and `useAuthRevalidation`.