fusionauth logo
search-interface-symbol
Downloads
Quickstarts
API Docs
SDK
search-interface-symbol
talk to an expert
Log In
talk to an expert
Navigate to...
  • Welcome
  • Getting Started
    • Getting Started
    • 5-minute Setup Guide
      • Overview
      • Docker
      • Fast Path
      • Sandbox
    • Setup Wizard & First Login
    • Register a User and Login
    • Self-service Registration
    • Start and Stop FusionAuth
    • Core Concepts
      • Overview
      • Users
      • Roles
      • Groups
      • Registrations
      • Applications
      • Tenants
      • Identity Providers
      • Authentication/Authorization
      • Integration Points
    • Example Apps
      • Overview
      • Dart
      • Go
      • Java
      • JavaScript
      • .NET Core
      • PHP
      • Python
      • Ruby
    • Tutorials
      • Overview
      • Express.js
      • Java Spring
      • Python Django
      • Python Flask
      • React
      • Ruby on Rails
      • Ruby on Rails API
  • Installation Guide
    • Overview
    • System Requirements
    • Server Layout
    • Cloud
    • Cluster
    • Docker
    • Fast Path
    • Kubernetes
      • Overview
      • Deployment Guide
      • Minikube Setup
      • Amazon EKS Setup
      • Google GKE Setup
      • Microsoft AKS Setup
    • Kickstart™
    • Homebrew
    • Marketplaces
    • Packages
    • Database
    • FusionAuth App
    • FusionAuth Search
    • Common Configuration
  • Migration Guide
    • Overview
    • General
    • Auth0
    • Keycloak
    • Amazon Cognito
    • Firebase
    • Microsoft Azure AD B2C
    • Tutorial
  • Admin Guide
    • Overview
    • Account Portal
    • Config Management
    • Editions and Features
    • Key Rotation
    • Licensing
    • Monitoring
    • Prometheus Setup
    • Proxy Setup
    • Reference
      • Overview
      • Configuration
      • CORS
      • Data Types
      • Hosted Login Pages Cookies
      • Known Limitations
      • Password Hashes
    • Releases
    • Roadmap
    • Search And FusionAuth
    • Securing
    • Switch Search Engines
    • Technical Support
    • Troubleshooting
    • Upgrading
    • WebAuthn
  • Login Methods
    • Identity Providers
      • Overview
      • Apple
      • Epic Games
      • External JWT
        • Overview
        • Example
      • Facebook
      • Google
      • HYPR
      • LinkedIn
      • Nintendo
      • OpenID Connect
        • Overview
        • Amazon Cognito
        • Azure AD
        • Discord
        • Github
        • Okta
      • Sony PlayStation Network
      • Steam
      • Twitch
      • Twitter
      • SAML v2
        • Overview
        • ADFS
        • Azure AD
        • Okta
      • SAML v2 IdP Initiated
        • Overview
        • Okta
      • Xbox
    • OIDC & OAuth 2.0
      • Overview
      • Endpoints
      • Tokens
      • OAuth Modes
      • URL Validation
      • Integrations
        • CockroachDB
        • Salesforce
    • Passwordless
      • Overview
      • Magic Links
      • WebAuthn & Passkeys
    • SAML v2 IdP
      • Overview
      • Google
      • PagerDuty
      • SendGrid
      • Tableau Cloud
      • Zendesk
  • Developer Guide
    • Overview
    • API Gateways
      • Overview
      • Amazon API Gateway
      • Kong Gateway
      • ngrok Cloud Edge
    • Client Libraries & SDKs
      • Overview
      • Dart
      • Go
      • Java
      • JavaScript
      • .NET Core
      • Node
      • OpenAPI
      • PHP
      • Python
      • React
      • Ruby
      • Typescript
    • Events & Webhooks
      • Overview
      • Writing a Webhook
      • Securing Webhooks
      • Events
        • Overview
        • Audit Log Create
        • Event Log Create
        • JWT Public Key Update
        • JWT Refresh
        • JWT Refresh Token Revoke
        • Kickstart Success
        • Group Create
        • Group Create Complete
        • Group Delete
        • Group Delete Complete
        • Group Update
        • Group Update Complete
        • Group Member Add
        • Group Member Add Complete
        • Group Member Remove
        • Group Member Remove Complete
        • Group Member Update
        • Group Member Update Complete
        • User Action
        • User Bulk Create
        • User Create
        • User Create Complete
        • User Deactivate
        • User Delete
        • User Delete Complete
        • User Email Update
        • User Email Verified
        • User IdP Link
        • User IdP Unlink
        • User Login Failed
        • User Login Id Dup. Create
        • User Login Id Dup. Update
        • User Login New Device
        • User Login Success
        • User Login Suspicious
        • User Password Breach
        • User Password Reset Send
        • User Password Reset Start
        • User Password Reset Success
        • User Password Update
        • User Reactivate
        • User Reg. Create
        • User Reg. Create Complete
        • User Reg. Delete
        • User Reg. Delete Complete
        • User Registration Update
        • User Reg. Update Complete
        • User Reg. Verified
        • User 2FA Method Add
        • User 2FA Method Remove
        • User Update
        • User Update Complete
    • Guides
      • Overview
      • Application Specific Email Templates
      • Authentication Tokens
      • Exposing A Local Instance
      • JSON Web Tokens
      • Key Master
      • Localization and Internationalization
      • Multi-Factor Authentication
      • Multi-Tenant
      • Passwordless
      • Registration-based Email Verification
      • Searching With Elasticsearch
      • Securing Your APIs
      • Silent Mode
      • Single Sign-on
      • Two Factor (pre 1.26)
    • Integrations
      • Overview
      • CleanSpeak
      • Kafka
      • Twilio
    • Plugins
      • Overview
      • Writing a Plugin
      • Custom Password Hashing
    • User Control & Gating
      • Overview
      • Gate Unverified Users
      • Gate Unverified Registrations
      • User Account Lockout
  • Customization
    • Email & Templates
      • Overview
      • Configure Email
      • Email Templates
      • Email Variables
      • Message Templates
    • Lambdas
      • Overview
      • Apple Reconcile
      • Client Cred. JWT Populate
      • Epic Games Reconcile
      • External JWT Reconcile
      • Facebook Reconcile
      • Google Reconcile
      • HYPR Reconcile
      • JWT Populate
      • LDAP Connector Reconcile
      • LinkedIn Reconcile
      • Nintendo Reconcile
      • OpenID Connect Reconcile
      • SAML v2 Populate
      • SAML v2 Reconcile
      • SCIM Group Req. Converter
      • SCIM Group Resp. Convtr.
      • SCIM User Req. Converter
      • SCIM User Resp. Converter
      • Self-Service Registration
      • Sony PSN Reconcile
      • Steam Reconcile
      • Twitch Reconcile
      • Twitter Reconcile
      • Xbox Reconcile
    • Messengers
      • Overview
      • Generic Messenger
      • Twilio Messenger
    • Themes
      • Overview
      • Examples
      • Helpers
      • Localization
      • Template Variables
      • Kickstart Custom Theme
  • Premium Features
    • Overview
    • Advanced Registration Forms
    • Advanced Threat Detection
    • Application Specific Themes
    • Breached Password Detection
    • Connectors
      • Overview
      • Generic Connector
      • LDAP Connector
      • FusionAuth Connector
    • Entity Management
    • SCIM
      • Overview
      • Azure AD Client
      • Okta Client
      • SCIM-SDK
    • Self Service Account Mgmt
      • Overview
      • Updating User Data & Password
      • Add Two-Factor Authenticator
      • Add Two-Factor Email
      • Add Two-Factor SMS
      • Add WebAuthn Passkey
      • Customizing
      • Bootstrapping Login
      • Troubleshooting
    • WebAuthn
  • APIs
    • Overview
    • Authentication
    • Errors
    • API Explorer
    • Actioning Users
    • API Keys
    • Applications
    • Audit Logs
    • Connectors
      • Overview
      • Generic
      • LDAP
    • Consents
    • Emails
    • Entity Management
      • Overview
      • Entities
      • Entity Types
      • Grants
    • Event Logs
    • Families
    • Forms
    • Form Fields
    • Groups
    • Hosted Backend
    • Identity Providers
      • Overview
      • Links
      • Apple
      • External JWT
      • Epic Games
      • Facebook
      • Google
      • HYPR
      • LinkedIn
      • Nintendo
      • OpenID Connect
      • SAML v2
      • SAML v2 IdP Initiated
      • Sony PlayStation Network
      • Steam
      • Twitch
      • Twitter
      • Xbox
    • Integrations
    • IP Access Control Lists
    • JWT
    • Keys
    • Lambdas
    • Login
    • Message Templates
    • Messengers
      • Overview
      • Generic
      • Twilio
    • Multi-Factor/Two Factor
    • Passwordless
    • Reactor
    • Registrations
    • Reports
    • SCIM
      • Overview
      • SCIM User
      • SCIM Group
      • SCIM EnterpriseUser
      • SCIM Service Provider Config.
    • System
    • Tenants
    • Themes
    • Users
    • User Actions
    • User Action Reasons
    • User Comments
    • WebAuthn
    • Webhooks
  • Release Notes

    Integrate Your React Application With FusionAuth

    Integrate Your React Application With FusionAuth

    In this article, you are going to learn how to integrate a React application with FusionAuth.

    Here’s a typical application login flow before integrating FusionAuth into your React application.

    Login before FusionAuth.
    Login before FusionAuth.

    Here’s the same application login flow when FusionAuth is introduced.

    Login with FusionAuth.
    Login with FusionAuth.

    Prerequisites

    For this tutorial, you’ll need to have nodejs installed.

    You’ll also need Docker, since that is how you’ll install FusionAuth.

    The commands below are for macOS, but are limited to mkdir and cd, which have equivalents in Windows and Linux.

    Download and Install FusionAuth

    First, make a project directory:

    mkdir integrate-fusionauth && cd integrate-fusionauth

    Then, install FusionAuth:

    curl -o docker-compose.yml https://raw.githubusercontent.com/FusionAuth/fusionauth-containers/master/docker/fusionauth/docker-compose.yml curl -o .env https://raw.githubusercontent.com/FusionAuth/fusionauth-containers/master/docker/fusionauth/.env docker-compose up -d

    Create a User and an API Key

    Next, log into your FusionAuth instance. You’ll need to set up a user and a password, as well as accept the terms and conditions.

    Then, you’re at the FusionAuth admin UI. This lets you configure FusionAuth manually. But for this tutorial, you’re going to create an API key and then you’ll configure FusionAuth using our JavaScript client library.

    Navigate to Settings -> API Keys. Click the + button to add a new API Key. Copy the value of the Key field and then save the key. It might be a value like CY1EUq2oAQrCgE7azl3A2xwG-OEwGPqLryDRBCoz-13IqyFYMn1_Udjt.

    Doing so creates an API key that can be used for any FusionAuth API call. Save that key value off as you’ll be using it later.

    Configure FusionAuth

    Next, you need to set up FusionAuth. This can be done in different ways, but we’re going to use the Typescript client library. The below instructions use npm on the command line, but you can use the client library with an IDE of your preference as well.

    First, make a directory:

    mkdir setup-fusionauth && cd setup-fusionauth

    Now, copy and paste the following file into package.json.

    { "name": "fusionauth-example-typescript-client", "version": "1.0.0", "description": "Example of setting up an application with typescript.", "scripts": { "setup": "node setup.js" }, "author": "Dan Moore", "license": "Apache-2.0", "dependencies": { "@fusionauth/typescript-client": "^1.45.0" } }

    Now you need to install the dependencies in package.json.

    npm install

    Then copy and paste the following file into setup-react.js. This file uses the FusionAuth API to configure an Application, CORS and more to allow for easy integration.

    404: Not Found

    Then, you can run the setup script.

    The setup script is designed to run on a newly installed FusionAuth instance with only one user and no tenants other than Default. To follow this guide on a FusionAuth instance that does not meet these criteria, you may need to modify the above script.

    Refer to the Typescript client library documentation for more information.

    fusionauth_api_key=YOUR_API_KEY_FROM_ABOVE npm run setup-react

    If you are using PowerShell, you will need to set the environment variable in a separate command before executing the script.

    $env:fusionauth_api_key='YOUR_API_KEY_FROM_ABOVE' npm run setup-react

    If you want, you can log into your instance and examine the new Application the script created for you.

    Create Your React Application

    Now you are going to create a React application. While this section uses a simple React application, you can use the same steps to integrate any React application with FusionAuth.

    First, make a directory:

    mkdir ../setup-react && cd ../setup-react

    Next, create a simple React template using vite. Using this lets you easily integrate FusionAuth. For a production application you’ll probably use something like NextJS or Remix.

    npm create vite@latest react-app -- --template react

    Now, change into the react-app directory and install the needed packages.

    cd react-app && npm install

    You can start up the server and visit the URL displayed to ensure the default application works.

    npm run dev

    You’ll want to open another terminal window to continue. Edit src/App.jsx to make changes to the view to test out the automatic reloading.

    If you are using a different port than 5173 for your React app, update the redirect URL in the setup script, or modify it manually. It needs to match.

    Now, let’s install the FusionAuth React SDK.

    npm install @fusionauth/react-sdk

    Update src/main.jsx to wrap your app with FusionAuthProvider. This file should look similar to this, but make sure you update the attributes of the provider if you modify the port:

    import React from 'react' import ReactDOM from 'react-dom/client' import { FusionAuthProvider } from '@fusionauth/react-sdk'; import App from './App.jsx' import './index.css' ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <FusionAuthProvider clientID="e9fdb985-9173-4e01-9d73-ac2d60d1dc8e" serverUrl="http://localhost:9011" redirectUri="http://localhost:5173" > <App /> </FusionAuthProvider> </React.StrictMode> )

    Now, let’s add a login and logout button to your React application. Open up src/App.jsx and replace the content with the following:

    import { useState } from 'react' import reactLogo from './assets/react.svg' import viteLogo from '/vite.svg' import './App.css' import { FusionAuthLoginButton, FusionAuthLogoutButton, RequireAuth, useFusionAuth } from '@fusionauth/react-sdk'; function App() { const { isAuthenticated, user } = useFusionAuth(); return ( <> <h1>Vite + React + FusionAuth</h1> <div className="card"> <p> {isAuthenticated ? <FusionAuthLogoutButton />:<FusionAuthLoginButton />} <RequireAuth> Welcome {user.name} </RequireAuth> </p> </div> </> ) } export default App

    In this code, you are adding in the FusionAuth login and logout buttons, as well as a welcome message which will only show up if the user is logged in.

    Testing the Authentication Flow

    You can now open up an incognito window and visit the React app. View the page and log in with the user you configured. If you used the setup script, it will be richard@example.com.

    The sample React application.
    The sample React application.

    You’ve successfully added login and logout to a React application.

    You now have an access token safely stored as a cookie. Any requests you make to an API on the same domain will receive the access token. The API can then validate the token and return data or otherwise offer functionality.

    Feedback

    How helpful was this page?

    See a problem?

    File an issue in our docs repo

    Have a question or comment to share?

    Visit the FusionAuth community forum.

    © 2023 FusionAuth
    How-to
    Blog
    Expert Advice
    Download
    Release Notes
    Subscribe for developer updates