Skip to Content

React Router with server rendering

Keep the session in an encrypted cookie in React Router's framework mode, where middleware refreshes it and loaders read it.

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 work with it. Server rendering explains how the pieces fit. A complete app is in examples/react-router-framework-ssr.

If your app uses framework mode with ssr: false, follow React Router instead.

Before you begin

  • React Router 8, which needs Node.js 22.22 or newer and React 19.2.7 or newer. See 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 says how to keep and rotate it.
  • The code signs in with DummyJSON's test backend, as Getting started does. Replace its URLs with your backend's.

Installation

To install the packages, run the following command:

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:

app/auth/session.server.ts
import {
  ,
  ,
} from "@monarcode/session-kit/react-router/server";
import {  } from "@monarcode/session-kit/server";
import {  } from "zod";

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

const  = .({ : .(), : .() });
const  = .({ : .(), : .() });

export const  = ({
  : "app",
  : ,
  : ..SESSION_SECRET!,
  : async ({ ,  }) => {
    const  = await (`${}/auth/refresh`, {
      : "POST",
      ,
      : { "Content-Type": "application/json" },
      : .({  }),
    });
    // DummyJSON rejected the refresh token: sign out.
    if (. === 401 || . === 403) return null;
    if (!.) throw new (`Refresh failed (${.})`);
    return .(await .());
  },
});

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

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

/** Signs in with your backend, from the server. */
export async function (: string, : string) {
  const  = await (`${}/auth/login`, {
    : "POST",
    : { "Content-Type": "application/json" },
    : .({ ,  }),
  });
  const : unknown = await .().(() => null);
  if (!.) {
    // The backend says why, such as wrong credentials, in `message`.
    const  = .({ : .() }).();
    throw new (
      .
        ? ..
        : `Sign-in failed (${.})`,
    );
  }
  return { ....(), : .() };
}

auth(context) returns the same session for every call with the same context, which React Router makes per request. 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:

app/auth/client.ts
import { , type  } from "@monarcode/session-kit";

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

export type  = <typeof >;

export function (:  | null) {
  return ({
    : "app",
    ,
    : "/auth/session",
  });
}

export type  = <typeof >;

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

app/root.tsx
import type {  } from "react";
import {
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  type ,
} from "react-router";

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

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

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

export const  = ();

export async function ({  }: ) {
  return { : await ().() };
}

export function ({  }: { :  }) {
  return (
    < ="en">
      <>
        < />
        < />
      </>
      <>
        {}
        < />
      </>
    </>
  );
}

export default function () {
  const {  } = <typeof >();
  const {  } = ();
  const  = ({
    : ,
    ,
    : ,
  });
  return (
    < ={}>
      < />
    </>
  );
}

/** Shown when the session can't be read, such as after a failed refresh. */
export function () {
  const  = ();
  const {  } = ();
  return (
    < ="alert">
      <>{ instanceof  ? . : "Something went wrong"}</>
      < ={() => void ()}>Retry</>
    </>
  );
}

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

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

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

const  = ();

export const  = .;
export const  = .;

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.

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:

app/routes/protected.tsx
import {  } from "react-router";

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

export const  = [];

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

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

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:

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

export default function () {
  const  = (() => .);
  return <>Welcome, {?.}</>;
}

A loader nested in the layout gets the session from signedIn.session(context), which is never null there. 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:

app/routes/login.tsx
import {
  ,
  ,
  ,
  ,
  type ,
} from "react-router";

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

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

export const  = ();

export async function ({ , ,  }: ) {
  const  = await .();
  try {
    const  = await (
      (.("username")),
      (.("password")),
    );
    await ().();
  } catch () {
    return (
      { :  instanceof  ? . : "Sign-in failed" },
      { : 400 },
    );
  }
  throw ((..("redirectTo")));
}

export default function () {
  const  = <typeof >();
  return (
    < ="post">
      <>
        Username
        < ="username" ="username" />
      </>
      <>
        Password
        <
          ="password"
          ="password"
          ="current-password"
        />
      </>
      {?. && < ="alert">{.}</>}
      <>Sign in</>
    </>
  );
}

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.

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

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

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

Without revoke, a copy of the cookie made before sign-out still works: see 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:

app/routes.ts
import {
  ,
  ,
  ,
  type ,
} from "@react-router/dev/routes";

export default [
  ("login", "routes/login.tsx"),
  ("routes/protected.tsx", [("routes/home.tsx")]),
  // The session route the browser's client calls.
  ("auth/session", "routes/auth.session.ts"),
] satisfies ;

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:

app/routes/orders.tsx
import { , type  } from "react-router";

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

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

const  = .({ : .(.({ : .() })) });

export async function ({  }: ) {
  const {  } = .();
  const  = ((), { : `${}/` });
  const  = await (`auth/carts/user/${.}`);
  if (!.) throw new (`Orders failed (${.})`);
  return .(await .()).;
}

export default function () {
  const  = <typeof >();
  return <>{.} orders</>;
}

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

app/routes.ts
import {
  ,
  ,
  ,
  type ,
} from "@react-router/dev/routes";

export default [
  ("login", "routes/login.tsx"),
  ("routes/protected.tsx", [
    ("routes/home.tsx"),
    ("orders", "routes/orders.tsx"),
  ]),
  ("auth/session", "routes/auth.session.ts"),
] satisfies ;

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 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. 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. 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.
  • 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.
  • 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.
  • Deploying. Several server instances, the cookie's size, and plain http during development are covered in Server sessions.

Next steps

On this page