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

Your React Router app runs in framework mode and renders pages on the server,
and you want the first response to show the signed-in page, with no "Checking
session…" state and no flash of signed-out content. To do that, the server
has to hold the session. In this guide, you keep it in an encrypted cookie:
an action signs in, middleware refreshes the tokens, and loaders read the
session.

Components get a small client that mirrors the session the server rendered,
and the [hooks](https://session-kit.pages.dev/docs/getting-started#4-read-the-session-in-react) work with
it. [Server rendering](https://session-kit.pages.dev/docs/server-rendering) explains how the pieces fit. A
complete app is in
[`examples/react-router-framework-ssr`](https://github.com/monarcode/session-kit/tree/main/examples/react-router-framework-ssr).

If your app uses framework mode with `ssr: false`, follow
[React Router](https://session-kit.pages.dev/docs/setups/react-router#framework-mode-with-ssr-false)
instead.

## Before you begin

- React Router 8, which needs Node.js 22.22 or newer and React 19.2.7 or
  newer. See [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) for the other
  versions.
- With React 18, use React Router 7, version 7.9 or later, and turn its
  middleware on with `future: { v8_middleware: true }` in
  `react-router.config.ts`. The code on this page is for React Router 8. On
  7.14 and earlier, read the URL with `new URL(request.url)` where the code
  uses the `url` argument.
- A secret of 32 or more random characters to seal the cookie, such as the
  output of `openssl rand -base64 32`, set as `SESSION_SECRET` on the server.
  `react-router build` doesn't need it.
  [The secret](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-secret) says how to
  keep and rotate it.
- The code signs in with [DummyJSON](https://dummyjson.com/docs/auth)'s test
  backend, as [Getting started](https://session-kit.pages.dev/docs/getting-started) does. Replace its URLs
  with your backend's.

## Installation

To install the packages, run the following command:

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

## 1. Create the server engine

The server engine keeps the session in a cookie sealed with your secret, and
refreshes the tokens with your backend. `createServerAuth` from
`@monarcode/session-kit/server` makes it. From
`@monarcode/session-kit/react-router/server`, `routerAuth` gives you a
request's session by its `context`, and `requireSession` makes the guard
that protects routes in step 4. Create them in a `.server` module, so React
Router refuses to bundle it for the browser:

```ts title="app/auth/session.server.ts"
import {
  requireSession,
  routerAuth,
} from "@monarcode/session-kit/react-router/server";
import { createServerAuth } from "@monarcode/session-kit/server";
import { z } from "zod";

export const API = "https://dummyjson.com";

const userSchema = z.object({ id: z.number(), firstName: z.string() });
const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() });

export const serverAuth = createServerAuth({
  name: "app",
  user: userSchema,
  secret: process.env.SESSION_SECRET!,
  refresh: async ({ refreshToken, signal }) => {
    const response = await fetch(`${API}/auth/refresh`, {
      method: "POST",
      signal,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ refreshToken }),
    });
    // DummyJSON rejected the refresh token: sign out.
    if (response.status === 401 || response.status === 403) return null;
    if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
    return tokens.parse(await response.json());
  },
});

/** The request's session: `auth(context)` in middleware, loaders, actions. */
export const auth = routerAuth(serverAuth);

/** Lets only signed-in users through to the routes it guards. */
export const signedIn = requireSession(serverAuth);

/** Signs in with your backend, from the server. */
export async function login(username: string, password: string) {
  const response = await fetch(`${API}/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, password }),
  });
  const body: unknown = await response.json().catch(() => null);
  if (!response.ok) {
    // The backend says why, such as wrong credentials, in `message`.
    const failure = z.object({ message: z.string() }).safeParse(body);
    throw new Error(
      failure.success
        ? failure.data.message
        : `Sign-in failed (${response.status})`,
    );
  }
  return { ...tokens.parse(body), user: userSchema.parse(body) };
}
```

`auth(context)` returns the same session for every call with the same
`context`, which React Router makes per request. [Server
sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions) covers the engine's other
options, the cookie, and signing out.

## 2. Add the root route

The root route does three jobs: its middleware refreshes the session, its
loader reads it, and its component gives it to the browser's client. First,
the client, which `createMirrorAuth` makes from the session the root loader
read and the session route that step 3 adds:

```ts title="app/auth/client.ts"
import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit";

// Types only: left out of the browser's bundle.
import type { serverAuth } from "./session.server";

export type AppSession = SessionOf<typeof serverAuth>;

export function createAppAuth(session: AppSession | null) {
  return createMirrorAuth({
    name: "app",
    session,
    endpoint: "/auth/session",
  });
}

export type AppAuth = ReturnType<typeof createAppAuth>;
```

Then the root route. Register the client's type here, where you render
`AuthProvider`, so the hooks carry your user:

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

import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react";
import { sessionMiddleware } from "@monarcode/session-kit/react-router/server";

import { createAppAuth, type AppAuth } from "./auth/client";
import { auth, serverAuth } from "./auth/session.server";

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

export const middleware = sessionMiddleware(serverAuth);

export async function loader({ context }: LoaderFunctionArgs) {
  return { session: await auth(context).getSession() };
}

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

export default function App() {
  const { session } = useLoaderData<typeof loader>();
  const { revalidate } = useRevalidator();
  const auth = useMirrorAuth({
    create: createAppAuth,
    session,
    onChange: revalidate,
  });
  return (
    <AuthProvider client={auth}>
      <Outlet />
    </AuthProvider>
  );
}

/** Shown when the session can't be read, such as after a failed refresh. */
export function ErrorBoundary() {
  const error = useRouteError();
  const { revalidate } = useRevalidator();
  return (
    <div role="alert">
      <p>{error instanceof Error ? error.message : "Something went wrong"}</p>
      <button onClick={() => void revalidate()}>Retry</button>
    </div>
  );
}
```

Here's what each part does:

- **`sessionMiddleware(serverAuth)`** reads each request's cookies and sets
  the ones written on the response, redirects included. That's what lets
  `auth(context)` work in middleware, loaders and actions. It then refreshes
  tokens that are about to expire, before any loader reads them, while the
  response can still set the cookie.
- **The loader** returns `getSession()`, which resolves
  `{ sessionId, user }`, never tokens, so it's safe to send to the browser.
- **`useMirrorAuth`** from `@monarcode/session-kit/react` creates the client
  once per request on the server, never at module level, and keeps it in
  step with the server both ways. After an action signs in or out, the loader
  reads the new session and the client takes it. When the session changes in
  the browser, here or in another tab, it calls `onChange`. Here that's
  `revalidate` from `useRevalidator()`, which runs the loaders again, so the
  server's redirects run. The client-side guides add `useAuthRevalidation`
  for this, and here `useMirrorAuth` does it.
- **`ErrorBoundary`** shows a session that can't be read, such as after a
  failed refresh, and its button runs the loaders again.

`sessionMiddleware` refreshes tokens that expire within 60 seconds. For
tokens that live a minute or less, pass a smaller `within`, such as
`sessionMiddleware(serverAuth, { within: 15 })`.
[Refresh before rendering](https://session-kit.pages.dev/docs/server-rendering/server-sessions#refresh-before-rendering)
says what happens when a refresh fails, and how the middleware sets
`Cache-Control`.

## 3. Add the session route

The browser's client reads the session and signs out through a session
route: a resource route in your app that the browser's client calls.
`sessionRoute` from `@monarcode/session-kit/react-router/server` makes its
loader and action:

```ts title="app/routes/auth.session.ts"
import { sessionRoute } from "@monarcode/session-kit/react-router/server";

import { serverAuth } from "../auth/session.server";

const route = sessionRoute(serverAuth);

export const loader = route.loader;
export const action = route.action;
```

Export the loader and action one by one, as this file does. React Router's
build fails on a destructured `export const { loader, action }`.

The session route answers your own site's pages only, so another site can't
sign the user out: see [The session route](https://session-kit.pages.dev/docs/security#the-session-route).

## 4. Protect routes

Guard a layout route with `signedIn`, the middleware `requireSession` made.
It runs on the server before any loader or action nested in it, which
loaders on their own can't promise:

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

import { signedIn } from "../auth/session.server";

export const middleware = [signedIn];

// So navigation in the browser runs the middleware.
export const loader = () => null;

export default function Protected() {
  return <Outlet />;
}
```

A signed-out user who opens a page in the layout, such as `/orders`, lands on
`/login?redirectTo=%2Forders`.
During navigation in the browser, server middleware runs only when a route
has a loader to fetch. The layout has one in case the routes nested in it
don't.

Pages nested in the layout read the user with the hooks, as any component
does:

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

export default function Home() {
  const user = useAuth((state) => state.user);
  return <h1>Welcome, {user?.firstName}</h1>;
}
```

A loader nested in the layout gets the session from
`signedIn.session(context)`, which is never `null` there. [Call your
API](#call-your-api) uses it.

## 5. Sign in

The sign-in route's action signs in with your backend and seals the result
into the cookie. Its loader, `redirectIfSignedIn`, sends a user who is
already signed in on to `redirectTo`. The form works before the page's
scripts load:

```tsx title="app/routes/login.tsx"
import {
  data,
  Form,
  redirect,
  useActionData,
  type ActionFunctionArgs,
} from "react-router";

import { safeReturnTo } from "@monarcode/session-kit";
import { redirectIfSignedIn } from "@monarcode/session-kit/react-router/server";

import { auth, login, serverAuth } from "../auth/session.server";

export const loader = redirectIfSignedIn(serverAuth);

export async function action({ request, context, url }: ActionFunctionArgs) {
  const form = await request.formData();
  try {
    const tokens = await login(
      String(form.get("username")),
      String(form.get("password")),
    );
    await auth(context).signIn(tokens);
  } catch (error) {
    return data(
      { error: error instanceof Error ? error.message : "Sign-in failed" },
      { status: 400 },
    );
  }
  throw redirect(safeReturnTo(url.searchParams.get("redirectTo")));
}

export default function Login() {
  const result = useActionData<typeof action>();
  return (
    <Form method="post">
      <label>
        Username
        <input name="username" autoComplete="username" />
      </label>
      <label>
        Password
        <input
          name="password"
          type="password"
          autoComplete="current-password"
        />
      </label>
      {result?.error && <p role="alert">{result.error}</p>}
      <button>Sign in</button>
    </Form>
  );
}
```

To try it, sign in as `emilys` with the password `emilyspass`. The action
redirects to `redirectTo`, made safe with `safeReturnTo`. A failed sign-in
returns its message with status 400, for the form to show, and React Router
doesn't run the page's loaders again after a 4xx action.

React Router 7.12 and later refuse route actions posted from other sites. On
7.9 to 7.11, refuse them yourself at the start of the action: see
[Check your own routes](https://session-kit.pages.dev/docs/security#check-your-own-routes).

In this guide, the server signs in with your backend, so the user in the
cookie comes from the backend. If the browser has to sign in with the backend
itself, have the action take the tokens instead:
[Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid) shows how.

## 6. Sign out

The client's `signOut()` signs out on the server through the session route,
which clears the cookie and calls your `revoke` option, if `createServerAuth`
has one. It then signs out this tab and tells the others. `useMirrorAuth`
runs the loaders again, so `signedIn` sends the user to the sign-in page.
Put a button like this one on any page under the layout:

```tsx title="app/sign-out-button.tsx"
import { useAuthClient } from "@monarcode/session-kit/react";

export function SignOutButton() {
  const auth = useAuthClient();
  // A failed sign-out keeps the session, and shows in `state.error`.
  return (
    <button onClick={() => void auth.signOut().catch(() => {})}>
      Sign out
    </button>
  );
}
```

Without `revoke`, a copy of the cookie made before sign-out still works: see
[Sign-out](https://session-kit.pages.dev/docs/server-rendering/server-sessions#sign-out).

## 7. Register the routes

Last, add the routes to `app/routes.ts`. The sign-in route sits outside the
layout, and the pages it protects sit inside:

```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")]),
  // The session route the browser's client calls.
  route("auth/session", "routes/auth.session.ts"),
] satisfies RouteConfig;
```

The sign-in route's path matters: `signedIn` sends signed-out users to
`/login`. To use another path, pass `loginPath` to `requireSession`.

## Call your API

Your loaders and actions call your API with `createAuthFetch` from
`@monarcode/session-kit/http`. Given the request's session, it sends the
access token, refreshed first if it has expired. This page sits inside the
layout, so its loader reads the user from `signedIn`:

```tsx title="app/routes/orders.tsx"
import { useLoaderData, type LoaderFunctionArgs } from "react-router";

import { createAuthFetch } from "@monarcode/session-kit/http";
import { z } from "zod";

import { API, auth, signedIn } from "../auth/session.server";

const orders = z.object({ carts: z.array(z.object({ id: z.number() })) });

export async function loader({ context }: LoaderFunctionArgs) {
  const { user } = signedIn.session(context);
  const authFetch = createAuthFetch(auth(context), { baseUrl: `${API}/` });
  const response = await authFetch(`auth/carts/user/${user.id}`);
  if (!response.ok) throw new Error(`Orders failed (${response.status})`);
  return orders.parse(await response.json()).carts;
}

export default function Orders() {
  const carts = useLoaderData<typeof loader>();
  return <p>{carts.length} orders</p>;
}
```

Then add it inside the layout in `app/routes.ts`:

```ts title="app/routes.ts" app="orders"
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"),
    route("orders", "routes/orders.tsx"),
  ]),
  route("auth/session", "routes/auth.session.ts"),
] satisfies RouteConfig;
```

When your API answers 401, `authFetch` gets a new access token and saves it in
the cookie. It sends a `GET` or `HEAD` again with the new token, as
[After a 401](https://session-kit.pages.dev/docs/client/requests#after-a-401) explains.

A loader outside the layout has no `signedIn` to rely on. It can check
`await auth(context).getSession()` itself, and throw
`redirect(loginHref("/login", "/orders"))` when it's `null`. `loginHref` from
`@monarcode/session-kit` builds `/login?redirectTo=%2Forders`, so the user
comes back after signing in.

With an HTTP client of your own, such as ky or axios, see
[Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients). A client without a
`fetch` option reads the token with `auth(context).credentials.get()`.

To call your API from the browser too, turn on `clientCredentials` in
`createServerAuth`: see
[The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser).
The example app does this.

## Things to know

- **Deferred data.** The request's session can set cookies until the
  response leaves `sessionMiddleware`, which first waits for a refresh under
  way. Deferred data that reads the session while the page streams can't
  save anything, so the middleware refreshes before that: see
  [Requests that can't set cookies](https://session-kit.pages.dev/docs/server-rendering/server-sessions#requests-that-cant-set-cookies).
- **Guards with the same names.** `requireSession` and `redirectIfSignedIn`
  on this page come from `@monarcode/session-kit/react-router/server`.
  `@monarcode/session-kit/react-router` exports guards with the same names
  that take the browser's client, for apps without server rendering: see
  [React Router](https://session-kit.pages.dev/docs/setups/react-router).
- **A `basename`.** Pass it to the guard too, as
  `requireSession(serverAuth, { basename: "/app" })`. React Router adds it to
  loaders' and actions' redirects, but not to middleware's, so the guard adds
  it to its own. The client's `endpoint` includes it as well:
  `"/app/auth/session"`.
- **Other tabs.** Signing in or out in one tab reaches the others, which ask
  the server for the session and run their loaders again: see
  [How tabs stay in step](https://session-kit.pages.dev/docs/server-rendering#how-tabs-stay-in-step).
- **Deploying.** Several server instances, the cookie's size, and plain http
  during development are covered in
  [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions).

## Next steps

- [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions): the cookie, the
  secret, signing out, and the limits every server-rendered setup shares.
- [Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid): sign in from the browser
  and call your API there, with the session still on the server.
- [Using the client](https://session-kit.pages.dev/docs/client): what the browser's client can do.
- [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server): run Effects with a
  request's session.