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 compose commands after installation, run docker context use orbstack)
  • Podman (in the commands below, replace docker with podman)

Create a Simple Remix App#

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

  1. Create a Remix app named remix-quickstart:

    $ npx remix@3.3.0 new remix-quickstart
    

    If npx asks to install the remix package, enter y.

    This creates a remix-quickstart folder with a server.ts file and an app folder with the app's routes and pages.

  2. Navigate into the app folder:

    $ cd remix-quickstart
    
  3. Install dependencies:

    $ npm install remix@3.3.0 --save-exact
    
  4. 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
    
  5. Replace the contents of app/routes.ts with 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('/'),
    })
  6. Replace the contents of app/router.ts with the following code, which adds the formData middleware 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)
  7. Replace the contents of app/actions/controller.tsx with 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 home action reads the note and shows it in a form, inside the Document component that Remix created in app/actions/document.tsx. The save action writes the submitted text to note.txt, then redirects back to the home page.

  8. Run the app:

    $ PORT=3000 npm run dev
    
  9. Open the app at http://localhost:3000.

  10. Type "Hello Remix" in the text area, then click Save Changes .

  11. In a file browser or terminal, look in the remix-quickstart folder. You should see a new file named note.txt, with text content "Hello Remix".

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

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

  2. From the remix-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 Remix 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 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:

  1. Navigate out of the fusionauth-quickstart-app folder, back to the remix-quickstart folder that contains server.ts and note.txt:

    $ cd ..
    
  2. 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
  3. In the app folder, create a file named auth.ts with 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 .env file.
    • createOIDCAuthProvider tells 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.
    • sessionCookie and sessionStorage keep the session in a cookie, signed with the SESSION_SECRET from the .env file.
    • sessionAuth reads the logged-in user from the session on each request.
  4. Replace the contents of app/routes.ts with 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-callback path matches the redirect URL that the QuickStart configuration set for the application in FusionAuth.

  5. Replace the contents of app/router.ts with 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:

    • session loads the session from the cookie and saves any changes to it.
    • csrf rejects form submissions that don't include the session's CSRF token in a _csrf field. The csrf middleware runs after formData and session, because csrf reads the token from the form and compares the token with the one in the session.
    • auth uses sessionAuth to find the logged-in user.
  6. Replace the contents of app/actions/controller.tsx with 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:

    • requireLogin sends users who aren't logged in to /login. The home and save actions both use it.
    • Both forms include the CSRF token from getCsrfToken in a hidden _csrf field.
    • The loginStart action calls startExternalAuth, which saves a PKCE code verifier in the session and sends the user to the FusionAuth login page.
    • The callback action calls finishExternalAuth, which exchanges the authorization code from FusionAuth for tokens and loads the user's profile. completeAuth gives the session a new Id, then the app stores the user's Id in it.
    • The logout action 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.
    • Remix loads links and forms on the same site without a full page load. The data-rmx-document attribute turns that off for the login link and the Logout button, because they redirect the browser to FusionAuth.
  7. Run the app, which now uses FusionAuth login:

    $ PORT=3000 npm run dev
    
  8. Open the app at http://localhost:3000 and click Log in with FusionAuth .

  9. 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.

  10. Edit and save the note in the authenticated Remix app.

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

  12. 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 Remix app.

  8. Replace the contents of app/auth.ts with the following code, which adds the profile scope so FusionAuth returns the user's first and last name, and adds the name to the User type:

    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'),
    })
  9. Replace the contents of app/actions/controller.tsx with 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)
        },
      },
    })

    finishExternalAuth loads the user's profile from FusionAuth, so the callback action reads sub, given_name, and family_name from result.profile.

  10. Run the app:

    $ PORT=3000 npm run dev
    
  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 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 requireLogin middleware kept logged-out users away from the notes page and the save action.
  • 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.