FusionAuth QuickStart for React Router

On this page

This QuickStart explains how to add a login page and authentication to a website built with React Router in framework mode. You'll begin with a simple React Router app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.

If you have a Remix 2 app, use this QuickStart. Remix 2 is now part of React Router.

This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.

Prerequisites#

This QuickStart requires:

If you use macOS or Windows, you need one of the following container management tools:

  • Docker Desktop
  • OrbStack (to use OrbStack for docker compose commands after installation, run docker context use orbstack)
  • Podman (in the commands below, replace docker with podman)

Create a Simple React Router App#

For this QuickStart, we'll use a React Router app that reads and writes data to a text file:

  1. Create a React Router app named react-router-quickstart:

    $ npx create-react-router@8.5.3 react-router-quickstart --yes
    

    If npx asks to install the create-react-router package, enter y. The --yes flag accepts the default answers, so the command installs the app's dependencies without asking.

    This creates a react-router-quickstart folder with an app folder that contains the app's routes and pages.

  2. Navigate into the app folder:

    $ cd react-router-quickstart
    
  3. Delete the starter welcome page, which we'll replace with our own page:

    $ rm -r app/welcome
    
  4. Replace the contents of app/routes/home.tsx with the following code:

    import { existsSync, readFileSync, writeFileSync } from "node:fs";
    import { Form } from "react-router";
    import type { Route } from "./+types/home";
    
    const NOTE_FILE = "note.txt";
    
    export function meta() {
      return [{ title: "Notes" }];
    }
    
    export function loader() {
      return { note: existsSync(NOTE_FILE) ? readFileSync(NOTE_FILE, "utf8") : "" };
    }
    
    export async function action({ request }: Route.ActionArgs) {
      const formData = await request.formData();
      writeFileSync(NOTE_FILE, String(formData.get("content") ?? ""));
      return null;
    }
    
    export default function Home({ loaderData }: Route.ComponentProps) {
      return (
        <main className="p-4">
          <h1 className="text-2xl">Notes</h1>
          <Form method="post">
            <label htmlFor="content">Your note</label>
            <br />
            <textarea id="content" name="content" rows={8} cols={40} defaultValue={loaderData.note} className="border p-2" />
            <br />
            <button type="submit" className="border px-3 py-1">Save Changes</button>
          </Form>
        </main>
      );
    }

    React Router runs the loader function on the server before it shows the page. The loader reads the note from note.txt. When you submit the form, React Router runs the action function on the server, which writes the submitted text to note.txt, then loads the page data again. The className values use Tailwind CSS, which the template includes.

  5. Run the app:

    $ npm run dev -- --port 3000
    
  6. Open the app at http://localhost:3000.

  7. Type "Hello React Router" in the text area, then click Save Changes .

  8. In a file browser or terminal, look in the react-router-quickstart folder. You should see a new file named note.txt, with text content "Hello React Router".

  9. Press Ctrl+C on your keyboard to stop the app.

Install and Run FusionAuth#

Before we can add authentication to our React Router app, we need a local FusionAuth instance:

  1. Open your container management tool (listed in the prerequisites above).

  2. From the react-router-quickstart folder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:

    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    
  3. Navigate into the cloned directory:

    $ cd fusionauth-quickstart-app
    
  4. To start a local instance of FusionAuth, run the following command (omit the -d flag to see all Docker logs):

    $ docker compose up -d
    
  5. Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.

  6. Open http://localhost:9011/admin to access the FusionAuth Admin UI.

  7. Log in with these credentials:

    • Login: admin@example.com
    • Password: password
  8. Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the OAuth tab. On this page, you can find your client Id and client secret, and set redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our React Router app with FusionAuth.

  9. Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our React Router app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.

Add FusionAuth to the React Router App#

Now that you have a working instance of FusionAuth and a working React Router app, let's use FusionAuth to add login to your React Router app:

  1. Navigate out of the fusionauth-quickstart-app folder, back to the react-router-quickstart folder that contains package.json and note.txt:

    $ cd ..
    
  2. Install openid-client, which handles the OpenID Connect login with FusionAuth:

    $ npm install openid-client@6.9.1 --save-exact
    
  3. Create a file named .env with the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):

    FUSIONAUTH_CLIENT_ID=f0510a74-da7a-4101-a474-05e7f1d5ba7e
    FUSIONAUTH_CLIENT_SECRET=super-secret-secret-that-should-be-regenerated-for-production
    FUSIONAUTH_CALLBACK_URL=http://localhost:3000/oauth-callback
    SESSION_SECRET=a_very_long_random_string_of_at_least_32_characters
  4. In the app folder, create a file named auth.server.ts with the following contents:

    import * as client from "openid-client";
    import { createCookieSessionStorage, redirect } from "react-router";
    
    process.loadEnvFile();
    
    const FUSIONAUTH_URL = "http://localhost:9011";
    const CLIENT_ID = process.env.FUSIONAUTH_CLIENT_ID!;
    const CLIENT_SECRET = process.env.FUSIONAUTH_CLIENT_SECRET!;
    const CALLBACK_URL = process.env.FUSIONAUTH_CALLBACK_URL!;
    
    type SessionData = { userId: string; codeVerifier: string; state: string };
    
    const sessionStorage = createCookieSessionStorage<SessionData>({
      cookie: {
        name: "__session",
        httpOnly: true,
        sameSite: "lax",
        path: "/",
        secrets: [process.env.SESSION_SECRET!],
      },
    });
    
    function getSession(request: Request) {
      return sessionStorage.getSession(request.headers.get("Cookie"));
    }
    
    function getConfig() {
      // The local FusionAuth instance uses HTTP, which openid-client blocks by default.
      return client.discovery(new URL(FUSIONAUTH_URL), CLIENT_ID, CLIENT_SECRET, undefined, {
        execute: [client.allowInsecureRequests],
      });
    }
    
    export async function requireUserId(request: Request) {
      const session = await getSession(request);
      const userId = session.get("userId");
      if (!userId) {
        throw redirect("/login");
      }
      return userId;
    }
    
    export async function startLogin(request: Request) {
      const config = await getConfig();
      const session = await getSession(request);
      const codeVerifier = client.randomPKCECodeVerifier();
      const state = client.randomState();
      session.set("codeVerifier", codeVerifier);
      session.set("state", state);
    
      const url = client.buildAuthorizationUrl(config, {
        redirect_uri: CALLBACK_URL,
        scope: "openid",
        code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
        code_challenge_method: "S256",
        state,
      });
      return redirect(url.href, { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } });
    }
    
    export async function finishLogin(request: Request) {
      const config = await getConfig();
      const session = await getSession(request);
      const tokens = await client.authorizationCodeGrant(config, new URL(request.url), {
        pkceCodeVerifier: session.get("codeVerifier"),
        expectedState: session.get("state"),
      });
    
      session.unset("codeVerifier");
      session.unset("state");
      session.set("userId", tokens.claims()!.sub);
      return redirect("/", { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } });
    }
    
    export async function logout(request: Request) {
      const session = await getSession(request);
      const url = `${FUSIONAUTH_URL}/oauth2/logout?` + new URLSearchParams({ client_id: CLIENT_ID });
      return redirect(url, { headers: { "Set-Cookie": await sessionStorage.destroySession(session) } });
    }

    The .server in the file name tells React Router to keep this file out of the code it sends to the browser, so the client secret stays on the server.

    • process.loadEnvFile() loads the values from the .env file.
    • createCookieSessionStorage keeps the session in a cookie, signed with the SESSION_SECRET from the .env file. The cookie uses sameSite: "lax", so browsers don't send it with form submissions from other sites.
    • getConfig uses client.discovery to find the login, token, and logout endpoints in FusionAuth's OpenID Connect discovery document at /.well-known/openid-configuration. The local FusionAuth instance uses HTTP, so allowInsecureRequests lets openid-client connect to it. Remove that option when FusionAuth uses HTTPS.
    • requireUserId sends users who aren't logged in to /login.
    • startLogin saves a PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges. code verifier and a random state value in the session, then sends the user to the FusionAuth login page.
    • finishLogin checks the state value, exchanges the authorization code from FusionAuth for tokens, and stores the user's Id from the ID tokenA JSON Web Token that contains information about the authenticated user. in the session.
    • logout clears the session, then sends the user to FusionAuth's /oauth2/logout endpoint so the FusionAuth session ends too. FusionAuth then sends the user back to the login page.
  5. Replace the contents of app/routes.ts with the following code, which adds the login, callback, and logout routes:

    import { type RouteConfig, index, route } from "@react-router/dev/routes";
    
    export default [
      index("routes/home.tsx"),
      route("login", "routes/login.tsx"),
      route("oauth-callback", "routes/oauth-callback.ts"),
      route("logout", "routes/logout.ts"),
    ] satisfies RouteConfig;

    The /oauth-callback path matches the redirect URL that the QuickStart configuration set for the application in FusionAuth.

  6. In the app/routes folder, create a file named login.tsx with the following contents:

    import { Form } from "react-router";
    import type { Route } from "./+types/login";
    import { startLogin } from "../auth.server";
    
    export function meta() {
      return [{ title: "Log in" }];
    }
    
    export function action({ request }: Route.ActionArgs) {
      return startLogin(request);
    }
    
    export default function Login() {
      return (
        <main className="p-4">
          <h1 className="text-2xl">Log in to Notes</h1>
          <Form method="post" reloadDocument>
            <button type="submit" className="border px-3 py-1">Log in with FusionAuth</button>
          </Form>
        </main>
      );
    }

    React Router submits forms without a full page load. The reloadDocument prop turns that off for this form, because the action redirects the browser to FusionAuth.

  7. In the app/routes folder, create a file named oauth-callback.ts with the following contents:

    import type { Route } from "./+types/oauth-callback";
    import { finishLogin } from "../auth.server";
    
    export function loader({ request }: Route.LoaderArgs) {
      return finishLogin(request);
    }
  8. In the app/routes folder, create a file named logout.ts with the following contents:

    import type { Route } from "./+types/logout";
    import { logout } from "../auth.server";
    
    export function action({ request }: Route.ActionArgs) {
      return logout(request);
    }

    The callback and logout routes have no page of their own. They only run their loader or action and redirect.

  9. Replace the contents of app/routes/home.tsx with the following code:

    import { existsSync, readFileSync, writeFileSync } from "node:fs";
    import { Form } from "react-router";
    import type { Route } from "./+types/home";
    import { requireUserId } from "../auth.server";
    
    const NOTE_FILE = "note.txt";
    
    export function meta() {
      return [{ title: "Notes" }];
    }
    
    export async function loader({ request }: Route.LoaderArgs) {
      await requireUserId(request);
      return { note: existsSync(NOTE_FILE) ? readFileSync(NOTE_FILE, "utf8") : "" };
    }
    
    export async function action({ request }: Route.ActionArgs) {
      await requireUserId(request);
      const formData = await request.formData();
      writeFileSync(NOTE_FILE, String(formData.get("content") ?? ""));
      return null;
    }
    
    export default function Home({ loaderData }: Route.ComponentProps) {
      return (
        <main className="p-4">
          <h1 className="text-2xl">Notes</h1>
          <Form method="post">
            <label htmlFor="content">Your note</label>
            <br />
            <textarea id="content" name="content" rows={8} cols={40} defaultValue={loaderData.note} className="border p-2" />
            <br />
            <button type="submit" className="border px-3 py-1">Save Changes</button>
          </Form>
          <Form method="post" action="/logout" reloadDocument>
            <button type="submit" className="border px-3 py-1">Logout</button>
          </Form>
        </main>
      );
    }

    The loader and action both call requireUserId, so only logged-in users can read or save the note. The new Logout form posts to the /logout route.

  10. Run the app, which now uses FusionAuth login:

    $ npm run dev -- --port 3000
    
  11. Open the app at http://localhost:3000 and click Log in with FusionAuth .

  12. Log in with the following credentials:

    • Login: richard@example.com
    • Password: password
  13. Edit and save the note in the authenticated React Router app.

  14. Click Logout . FusionAuth ends your session and sends you back to the login page.

  15. Press Ctrl+C on your keyboard to stop the app.

Add Independent Notes for Each User#

To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:

  1. Open the FusionAuth Admin UI at http://localhost:9011/admin.

  2. Log in with the following credentials:

    • Login: admin@example.com
    • Password: password
  3. Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the Registration tab.

    • Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
    • In the Registration field list, turn on the Enabled and Required switches for the following rows:
      • Birthdate
      • First name
      • Last name
  4. Click Save in the top right of the page to save your changes to self-service registration.

  5. Navigate to Users . In the Richard Hendricks row, click Select -> Manage .

  6. In the Source tab, look for the firstName and lastName fields. That's what we'll use to personalize the UI for each user. We'll use the user's id field to generate a unique name for each user's note.

  7. Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our React Router app.

  8. Replace the contents of app/auth.server.ts with the following code:

    import * as client from "openid-client";
    import { createCookieSessionStorage, redirect } from "react-router";
    
    process.loadEnvFile();
    
    const FUSIONAUTH_URL = "http://localhost:9011";
    const CLIENT_ID = process.env.FUSIONAUTH_CLIENT_ID!;
    const CLIENT_SECRET = process.env.FUSIONAUTH_CLIENT_SECRET!;
    const CALLBACK_URL = process.env.FUSIONAUTH_CALLBACK_URL!;
    
    export type User = { id: string; name: string };
    
    type SessionData = { user: User; codeVerifier: string; state: string };
    
    const sessionStorage = createCookieSessionStorage<SessionData>({
      cookie: {
        name: "__session",
        httpOnly: true,
        sameSite: "lax",
        path: "/",
        secrets: [process.env.SESSION_SECRET!],
      },
    });
    
    function getSession(request: Request) {
      return sessionStorage.getSession(request.headers.get("Cookie"));
    }
    
    function getConfig() {
      // The local FusionAuth instance uses HTTP, which openid-client blocks by default.
      return client.discovery(new URL(FUSIONAUTH_URL), CLIENT_ID, CLIENT_SECRET, undefined, {
        execute: [client.allowInsecureRequests],
      });
    }
    
    export async function requireUser(request: Request) {
      const session = await getSession(request);
      const user = session.get("user");
      if (!user) {
        throw redirect("/login");
      }
      return user;
    }
    
    export async function startLogin(request: Request) {
      const config = await getConfig();
      const session = await getSession(request);
      const codeVerifier = client.randomPKCECodeVerifier();
      const state = client.randomState();
      session.set("codeVerifier", codeVerifier);
      session.set("state", state);
    
      const url = client.buildAuthorizationUrl(config, {
        redirect_uri: CALLBACK_URL,
        scope: "openid profile",
        code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
        code_challenge_method: "S256",
        state,
      });
      return redirect(url.href, { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } });
    }
    
    export async function finishLogin(request: Request) {
      const config = await getConfig();
      const session = await getSession(request);
      const tokens = await client.authorizationCodeGrant(config, new URL(request.url), {
        pkceCodeVerifier: session.get("codeVerifier"),
        expectedState: session.get("state"),
      });
    
      session.unset("codeVerifier");
      session.unset("state");
      const { sub, given_name, family_name } = tokens.claims()!;
      const name = `${given_name ?? ""} ${family_name ?? ""}`.trim() || "writer";
      session.set("user", { id: sub, name });
      return redirect("/", { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } });
    }
    
    export async function logout(request: Request) {
      const session = await getSession(request);
      const url = `${FUSIONAUTH_URL}/oauth2/logout?` + new URLSearchParams({ client_id: CLIENT_ID });
      return redirect(url, { headers: { "Set-Cookie": await sessionStorage.destroySession(session) } });
    }
    • startLogin adds the profile scope, so the ID token from FusionAuth includes the user's first and last name in the given_name and family_name claims.
    • finishLogin stores the user's Id and name in the session.
    • requireUserId is now requireUser, which returns the user's Id and name.
  9. Replace the contents of app/routes/home.tsx with the following code, which greets the user and stores each user's note in a separate file:

    import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
    import { Form } from "react-router";
    import type { Route } from "./+types/home";
    import { requireUser, type User } from "../auth.server";
    
    const DATA_DIR = "user_data";
    
    function noteFile(user: User) {
      return `${DATA_DIR}/note-${user.id}.txt`;
    }
    
    export function meta() {
      return [{ title: "Notes" }];
    }
    
    export async function loader({ request }: Route.LoaderArgs) {
      const user = await requireUser(request);
      const file = noteFile(user);
      const note = existsSync(file) ? readFileSync(file, "utf8") : `Write a note, ${user.name}.`;
      return { name: user.name, note };
    }
    
    export async function action({ request }: Route.ActionArgs) {
      const user = await requireUser(request);
      const formData = await request.formData();
      mkdirSync(DATA_DIR, { recursive: true });
      writeFileSync(noteFile(user), String(formData.get("content") ?? ""));
      return null;
    }
    
    export default function Home({ loaderData }: Route.ComponentProps) {
      return (
        <main className="p-4">
          <h1 className="text-2xl">Welcome, {loaderData.name}</h1>
          <Form method="post">
            <label htmlFor="content">Your note</label>
            <br />
            <textarea id="content" name="content" rows={8} cols={40} defaultValue={loaderData.note} className="border p-2" />
            <br />
            <button type="submit" className="border px-3 py-1">Save Changes</button>
          </Form>
          <Form method="post" action="/logout" reloadDocument>
            <button type="submit" className="border px-3 py-1">Logout</button>
          </Form>
        </main>
      );
    }
  10. Run the app:

    $ npm run dev -- --port 3000
    
  11. Open the app at http://localhost:3000 and click Log in with FusionAuth .

  12. Log in with the following credentials:

    • Login: richard@example.com
    • Password: password
  13. In a separate private or incognito window, open the app at http://localhost:3000 and click Log in with FusionAuth .

  14. Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.

  15. Edit and save your own note. Your name appears at the top of the page and in the default note text.

Your React Router app now provides unique notes for each user. Each user can independently edit and save their note. When a user saves a note, the app writes the note to a note-<id>.txt file in the user_data directory. To identify which note belongs to which user, compare the id in the file name with the id field in the user's Source tab in the Admin UI. Log out of the app before you open the Admin UI. Otherwise, FusionAuth single sign-on logs you in to the Admin UI as the app user, who doesn't have access to the Admin UI.

Summary#

In this QuickStart, FusionAuth handled login for your React Router app:

  • openid-client sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
  • The requireUser function kept logged-out users away from the notes page and the action that saves notes.
  • FusionAuth gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
  • FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.

Next Steps#

This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.

FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.