FusionAuth QuickStart for Remix
On this page
This QuickStart explains how to add a login page and authentication to a website built with Remix. You'll begin with a simple Remix 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.
This QuickStart uses Remix 3. Remix 2 is now part of React Router. If you have a Remix 2 app, use the React Router QuickStart.
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 Remix App#
For this QuickStart, we'll use a Remix app that reads and writes data to a text file:
-
Create a Remix app named
remix-quickstart:$ npx remix@3.3.0 new remix-quickstartIf
npxasks to install theremixpackage, entery.This creates a
remix-quickstartfolder with aserver.tsfile and anappfolder with the app's routes and pages. -
Navigate into the app folder:
$ cd remix-quickstart -
Install dependencies:
$ npm install remix@3.3.0 --save-exact -
Delete the starter home page and its test, which we'll replace with our own page:
$ rm app/actions/home-page.tsx app/actions/public/prompt-button.tsx app/actions/controller.test.ts -
Replace the contents of
app/routes.tswith the following code, which defines the app's URLs:import { get, post, route } from 'remix/routes' export const routes = route({ assets: get('/assets/*path'), home: get('/'), save: post('/'), }) -
Replace the contents of
app/router.tswith the following code, which adds theformDatamiddleware to parse submitted forms:import { createRouter, type RouterContext } from 'remix/router' import { formData } from 'remix/middleware/form-data' import { render } from 'remix/middleware/render' import { staticFiles } from 'remix/middleware/static' import controller from './actions/controller.tsx' import { assets } from './assets.ts' import { routes } from './routes.ts' export const router = createRouter({ middleware: [staticFiles('./public', { index: false }), formData(), render({ assets })], }) export type AppContext = RouterContext<typeof router> declare module 'remix' { interface RouterTypes { context: AppContext } } router.map(routes, controller) -
Replace the contents of
app/actions/controller.tsxwith the following code:import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { redirect } from 'remix/response/redirect' import { createController } from 'remix/router' import { assets } from '../assets.ts' import { routes } from '../routes.ts' import { Document } from './document.tsx' const NOTE_FILE = 'note.txt' export default createController(routes, { actions: { async assets(context) { return (await assets.fetch(context.request)) ?? new Response('Not Found', { status: 404 }) }, home(context) { let note = existsSync(NOTE_FILE) ? readFileSync(NOTE_FILE, 'utf8') : '' return context.render( <Document title="Notes"> <h1>Notes</h1> <form method="post" action={routes.save.href()}> <label htmlFor="content">Your note</label> <br /> <textarea id="content" name="content" rows={8} cols={40} defaultValue={note} /> <br /> <button type="submit">Save Changes</button> </form> </Document>, ) }, save(context) { writeFileSync(NOTE_FILE, String(context.formData.get('content') ?? '')) return redirect(routes.home.href(), 303) }, }, })The
homeaction reads the note and shows it in a form, inside theDocumentcomponent that Remix created inapp/actions/document.tsx. Thesaveaction writes the submitted text tonote.txt, then redirects back to the home page. -
Run the app:
$ PORT=3000 npm run dev -
Open the app at http://localhost:3000.
-
Type "Hello Remix" in the text area, then click Save Changes .
-
In a file browser or terminal, look in the
remix-quickstartfolder. You should see a new file namednote.txt, with text content "Hello Remix". -
Press Ctrl+C on your keyboard to stop the app.
Install and Run FusionAuth#
Before we can add authentication to our Remix app, we need a local FusionAuth instance:
-
Open your container management tool (listed in the prerequisites above).
-
From the
remix-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 Remix 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 Remix 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 Remix App#
Now that you have a working instance of FusionAuth and a working Remix app, let's use FusionAuth to add login to your Remix app. Remix includes OpenID Connect login, sessions, and CSRFAn attack in which a malicious site makes the user's browser send an unwanted request to a site where the user is logged in. The OAuth 2.0 state parameter protects the authorization flow from CSRF. protection, so you don't need to install any more packages:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to theremix-quickstartfolder that containsserver.tsandnote.txt:$ cd .. -
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.tswith the following contents:import { createOIDCAuthProvider } from 'remix/auth' import { createCookie } from 'remix/cookie' import { createSessionAuthScheme } from 'remix/middleware/auth' import { createCookieSessionStorage } from 'remix/session-storage/cookie' process.loadEnvFile() export const FUSIONAUTH_URL = 'http://localhost:9011' export const CLIENT_ID = process.env.FUSIONAUTH_CLIENT_ID! export const fusionAuth = createOIDCAuthProvider({ name: 'fusionauth', issuer: FUSIONAUTH_URL, clientId: CLIENT_ID, clientSecret: process.env.FUSIONAUTH_CLIENT_SECRET!, redirectUri: process.env.FUSIONAUTH_CALLBACK_URL!, scopes: ['openid'], }) export type User = { id: string } export const sessionCookie = createCookie('session', { secrets: [process.env.SESSION_SECRET!], httpOnly: true, sameSite: 'lax', path: '/', }) export const sessionStorage = createCookieSessionStorage() export const sessionAuth = createSessionAuthScheme<User, User>({ read: (session) => session.get('user') as User | undefined, verify: (user) => user, invalidate: (session) => session.unset('user'), })process.loadEnvFile()loads the values from the.envfile.createOIDCAuthProvidertells Remix how to talk to FusionAuth. The provider finds the login, token, and UserInfo endpoints in FusionAuth's OpenID Connect discovery document at/.well-known/openid-configuration, and uses PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges. for every login.sessionCookieandsessionStoragekeep the session in a cookie, signed with theSESSION_SECRETfrom the.envfile.sessionAuthreads the logged-in user from the session on each request.
-
Replace the contents of
app/routes.tswith the following code, which adds the login, callback, and logout routes:import { get, post, route } from 'remix/routes' export const routes = route({ assets: get('/assets/*path'), home: get('/'), save: post('/'), login: get('/login'), loginStart: get('/login/start'), callback: get('/oauth-callback'), logout: post('/logout'), })The
/oauth-callbackpath matches the redirect URL that the QuickStart configuration set for the application in FusionAuth. -
Replace the contents of
app/router.tswith the following code:import { createRouter, type RouterContext } from 'remix/router' import { auth } from 'remix/middleware/auth' import { csrf } from 'remix/middleware/csrf' import { formData } from 'remix/middleware/form-data' import { render } from 'remix/middleware/render' import { session } from 'remix/middleware/session' import { staticFiles } from 'remix/middleware/static' import controller from './actions/controller.tsx' import { assets } from './assets.ts' import { sessionAuth, sessionCookie, sessionStorage } from './auth.ts' import { routes } from './routes.ts' export const router = createRouter({ middleware: [ staticFiles('./public', { index: false }), formData(), session(sessionCookie, sessionStorage), csrf(), auth({ schemes: [sessionAuth] }), render({ assets }), ], }) export type AppContext = RouterContext<typeof router> declare module 'remix' { interface RouterTypes { context: AppContext } } router.map(routes, controller)The new middleware runs on every request:
sessionloads the session from the cookie and saves any changes to it.csrfrejects form submissions that don't include the session's CSRF token in a_csrffield. Thecsrfmiddleware runs afterformDataandsession, becausecsrfreads the token from the form and compares the token with the one in the session.authusessessionAuthto find the logged-in user.
-
Replace the contents of
app/actions/controller.tsxwith the following code:import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { completeAuth, finishExternalAuth, startExternalAuth } from 'remix/auth' import { requireAuth } from 'remix/middleware/auth' import { getCsrfToken } from 'remix/middleware/csrf' import { redirect } from 'remix/response/redirect' import { createController } from 'remix/router' import { assets } from '../assets.ts' import { CLIENT_ID, FUSIONAUTH_URL, fusionAuth, type User } from '../auth.ts' import { routes } from '../routes.ts' import { Document } from './document.tsx' const NOTE_FILE = 'note.txt' const requireLogin = requireAuth<User>({ onFailure: () => redirect(routes.login.href()), }) export default createController(routes, { actions: { async assets(context) { return (await assets.fetch(context.request)) ?? new Response('Not Found', { status: 404 }) }, home: { middleware: [requireLogin], handler(context) { let note = existsSync(NOTE_FILE) ? readFileSync(NOTE_FILE, 'utf8') : '' let csrfToken = getCsrfToken(context) return context.render( <Document title="Notes"> <h1>Notes</h1> <form method="post" action={routes.save.href()}> <input type="hidden" name="_csrf" value={csrfToken} /> <label htmlFor="content">Your note</label> <br /> <textarea id="content" name="content" rows={8} cols={40} defaultValue={note} /> <br /> <button type="submit">Save Changes</button> </form> <form method="post" action={routes.logout.href()} data-rmx-document> <input type="hidden" name="_csrf" value={csrfToken} /> <button type="submit">Logout</button> </form> </Document>, ) }, }, save: { middleware: [requireLogin], handler(context) { writeFileSync(NOTE_FILE, String(context.formData.get('content') ?? '')) return redirect(routes.home.href(), 303) }, }, login(context) { return context.render( <Document title="Log in"> <h1>Log in to Notes</h1> <a href={routes.loginStart.href()} data-rmx-document>Log in with FusionAuth</a> </Document>, ) }, loginStart(context) { return startExternalAuth(fusionAuth, context) }, async callback(context) { let { result } = await finishExternalAuth(fusionAuth, context) completeAuth(context).set('user', { id: result.profile.sub }) return redirect(routes.home.href()) }, logout(context) { context.session.destroy() return redirect(`${FUSIONAUTH_URL}/oauth2/logout?` + new URLSearchParams({ client_id: CLIENT_ID }), 303) }, }, })The new code adds login and logout to the app:
requireLoginsends users who aren't logged in to/login. Thehomeandsaveactions both use it.- Both forms include the CSRF token from
getCsrfTokenin a hidden_csrffield. - The
loginStartaction callsstartExternalAuth, which saves a PKCE code verifier in the session and sends the user to the FusionAuth login page. - The
callbackaction callsfinishExternalAuth, which exchanges the authorization code from FusionAuth for tokens and loads the user's profile.completeAuthgives the session a new Id, then the app stores the user's Id in it. - The
logoutaction clears 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. - Remix loads links and forms on the same site without a full page load. The
data-rmx-documentattribute turns that off for the login link and the Logout button, because they redirect the browser to FusionAuth.
-
Run the app, which now uses FusionAuth login:
$ PORT=3000 npm run dev -
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
After you log in, the terminal shows a message that the session Id was regenerated but the old session can't be deleted when using cookie storage. The message is expected. The app keeps the session in a cookie, so the server has no old session to delete.
- Login:
-
Edit and save the note in the authenticated Remix 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 Remix app.
-
Replace the contents of
app/auth.tswith the following code, which adds theprofilescope so FusionAuth returns the user's first and last name, and adds the name to theUsertype:import { createOIDCAuthProvider } from 'remix/auth' import { createCookie } from 'remix/cookie' import { createSessionAuthScheme } from 'remix/middleware/auth' import { createCookieSessionStorage } from 'remix/session-storage/cookie' process.loadEnvFile() export const FUSIONAUTH_URL = 'http://localhost:9011' export const CLIENT_ID = process.env.FUSIONAUTH_CLIENT_ID! export const fusionAuth = createOIDCAuthProvider({ name: 'fusionauth', issuer: FUSIONAUTH_URL, clientId: CLIENT_ID, clientSecret: process.env.FUSIONAUTH_CLIENT_SECRET!, redirectUri: process.env.FUSIONAUTH_CALLBACK_URL!, scopes: ['openid', 'profile'], }) export type User = { id: string; name: string } export const sessionCookie = createCookie('session', { secrets: [process.env.SESSION_SECRET!], httpOnly: true, sameSite: 'lax', path: '/', }) export const sessionStorage = createCookieSessionStorage() export const sessionAuth = createSessionAuthScheme<User, User>({ read: (session) => session.get('user') as User | undefined, verify: (user) => user, invalidate: (session) => session.unset('user'), }) -
Replace the contents of
app/actions/controller.tsxwith the following code, which stores the user's name in the session, greets the user, and stores each user's note in a separate file:import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { completeAuth, finishExternalAuth, startExternalAuth } from 'remix/auth' import { requireAuth } from 'remix/middleware/auth' import { getCsrfToken } from 'remix/middleware/csrf' import { redirect } from 'remix/response/redirect' import { createController } from 'remix/router' import { assets } from '../assets.ts' import { CLIENT_ID, FUSIONAUTH_URL, fusionAuth, type User } from '../auth.ts' import { routes } from '../routes.ts' import { Document } from './document.tsx' const DATA_DIR = 'user_data' function noteFile(user: User) { return `${DATA_DIR}/note-${user.id}.txt` } const requireLogin = requireAuth<User>({ onFailure: () => redirect(routes.login.href()), }) export default createController(routes, { actions: { async assets(context) { return (await assets.fetch(context.request)) ?? new Response('Not Found', { status: 404 }) }, home: { middleware: [requireLogin], handler(context) { let user = context.auth.identity let file = noteFile(user) let note = existsSync(file) ? readFileSync(file, 'utf8') : `Write a note, ${user.name}.` let csrfToken = getCsrfToken(context) return context.render( <Document title="Notes"> <h1>Welcome, {user.name}</h1> <form method="post" action={routes.save.href()}> <input type="hidden" name="_csrf" value={csrfToken} /> <label htmlFor="content">Your note</label> <br /> <textarea id="content" name="content" rows={8} cols={40} defaultValue={note} /> <br /> <button type="submit">Save Changes</button> </form> <form method="post" action={routes.logout.href()} data-rmx-document> <input type="hidden" name="_csrf" value={csrfToken} /> <button type="submit">Logout</button> </form> </Document>, ) }, }, save: { middleware: [requireLogin], handler(context) { mkdirSync(DATA_DIR, { recursive: true }) writeFileSync(noteFile(context.auth.identity), String(context.formData.get('content') ?? '')) return redirect(routes.home.href(), 303) }, }, login(context) { return context.render( <Document title="Log in"> <h1>Log in to Notes</h1> <a href={routes.loginStart.href()} data-rmx-document>Log in with FusionAuth</a> </Document>, ) }, loginStart(context) { return startExternalAuth(fusionAuth, context) }, async callback(context) { let { result } = await finishExternalAuth(fusionAuth, context) let { sub, given_name, family_name } = result.profile let name = `${given_name ?? ''} ${family_name ?? ''}`.trim() || 'writer' completeAuth(context).set('user', { id: sub, name }) return redirect(routes.home.href()) }, logout(context) { context.session.destroy() return redirect(`${FUSIONAUTH_URL}/oauth2/logout?` + new URLSearchParams({ client_id: CLIENT_ID }), 303) }, }, })finishExternalAuthloads the user's profile from FusionAuth, so thecallbackaction readssub,given_name, andfamily_namefromresult.profile. -
Run the app:
$ PORT=3000 npm run dev -
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 Remix 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 Remix app:
- Remix's OpenID Connect provider sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
- The
requireLoginmiddleware kept logged-out users away from the notes page and thesaveaction. - 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.