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 composecommands after installation, rundocker context use orbstack) - Podman (in the commands below, replace
dockerwithpodman)
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:
-
Create a React Router app named
react-router-quickstart:$ npx create-react-router@8.5.3 react-router-quickstart --yesIf
npxasks to install thecreate-react-routerpackage, entery. The--yesflag accepts the default answers, so the command installs the app's dependencies without asking.This creates a
react-router-quickstartfolder with anappfolder that contains the app's routes and pages. -
Navigate into the app folder:
$ cd react-router-quickstart -
Delete the starter welcome page, which we'll replace with our own page:
$ rm -r app/welcome -
Replace the contents of
app/routes/home.tsxwith 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
loaderfunction on the server before it shows the page. The loader reads the note fromnote.txt. When you submit the form, React Router runs theactionfunction on the server, which writes the submitted text tonote.txt, then loads the page data again. TheclassNamevalues use Tailwind CSS, which the template includes. -
Run the app:
$ npm run dev -- --port 3000 -
Open the app at http://localhost:3000.
-
Type "Hello React Router" in the text area, then click Save Changes .
-
In a file browser or terminal, look in the
react-router-quickstartfolder. You should see a new file namednote.txt, with text content "Hello React Router". -
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:
-
Open your container management tool (listed in the prerequisites above).
-
From the
react-router-quickstartfolder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:$ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git -
Navigate into the cloned directory:
$ cd fusionauth-quickstart-app -
To start a local instance of FusionAuth, run the following command (omit the
-dflag to see all Docker logs):$ docker compose up -d -
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.
-
Open http://localhost:9011/admin to access the FusionAuth Admin UI.
-
Log in with these credentials:
- Login:
admin@example.com - Password:
password
- Login:
-
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.
-
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:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to thereact-router-quickstartfolder that containspackage.jsonandnote.txt:$ cd .. -
Install openid-client, which handles the OpenID Connect login with FusionAuth:
$ npm install openid-client@6.9.1 --save-exact -
Create a file named
.envwith 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 -
In the
appfolder, create a file namedauth.server.tswith 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
.serverin 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.envfile.createCookieSessionStoragekeeps the session in a cookie, signed with theSESSION_SECRETfrom the.envfile. The cookie usessameSite: "lax", so browsers don't send it with form submissions from other sites.getConfigusesclient.discoveryto 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, soallowInsecureRequestslets openid-client connect to it. Remove that option when FusionAuth uses HTTPS.requireUserIdsends users who aren't logged in to/login.startLoginsaves 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.finishLoginchecks 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.logoutclears the session, then sends the user to FusionAuth's/oauth2/logoutendpoint so the FusionAuth session ends too. FusionAuth then sends the user back to the login page.
-
Replace the contents of
app/routes.tswith 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-callbackpath matches the redirect URL that the QuickStart configuration set for the application in FusionAuth. -
In the
app/routesfolder, create a file namedlogin.tsxwith 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
reloadDocumentprop turns that off for this form, because theactionredirects the browser to FusionAuth. -
In the
app/routesfolder, create a file namedoauth-callback.tswith the following contents:import type { Route } from "./+types/oauth-callback"; import { finishLogin } from "../auth.server"; export function loader({ request }: Route.LoaderArgs) { return finishLogin(request); } -
In the
app/routesfolder, create a file namedlogout.tswith 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
loaderoractionand redirect. -
Replace the contents of
app/routes/home.tsxwith 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
loaderandactionboth callrequireUserId, so only logged-in users can read or save the note. The new Logout form posts to the/logoutroute. -
Run the app, which now uses FusionAuth login:
$ npm run dev -- --port 3000 -
Open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Log in with the following credentials:
- Login:
richard@example.com - Password:
password
- Login:
-
Edit and save the note in the authenticated React Router app.
-
Click Logout . FusionAuth ends your session and sends you back to the login page.
-
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:
-
Open the FusionAuth Admin UI at http://localhost:9011/admin.
-
Log in with the following credentials:
- Login:
admin@example.com - Password:
password
- Login:
-
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
-
Click Save in the top right of the page to save your changes to self-service registration.
-
Navigate to Users . In the Richard Hendricks row, click Select -> Manage .
-
In the Source tab, look for the
firstNameandlastNamefields. That's what we'll use to personalize the UI for each user. We'll use the user'sidfield to generate a unique name for each user's note. -
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.
-
Replace the contents of
app/auth.server.tswith 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) } }); }startLoginadds theprofilescope, so the ID token from FusionAuth includes the user's first and last name in thegiven_nameandfamily_nameclaims.finishLoginstores the user's Id and name in the session.requireUserIdis nowrequireUser, which returns the user's Id and name.
-
Replace the contents of
app/routes/home.tsxwith 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> ); } -
Run the app:
$ npm run dev -- --port 3000 -
Open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Log in with the following credentials:
- Login:
richard@example.com - Password:
password
- Login:
-
In a separate private or incognito window, open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.
-
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
requireUserfunction kept logged-out users away from the notes page and theactionthat 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.