FusionAuth developer image
FusionAuth developer logo
  • Back to site
  • Expert Advice
  • Blog
  • Developers
  • Downloads
  • Account
  • Contact sales
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
  • 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
      • Sony PlayStation Network
      • Steam
      • Twitch
      • Twitter
      • SAML v2
        • Overview
        • ADFS
        • Azure AD
      • SAML v2 IdP Initiated
        • Overview
        • Okta
      • Xbox
    • OIDC & OAuth 2.0
      • Overview
      • Endpoints
      • Tokens
      • OAuth Modes
    • Passwordless
      • Overview
      • Magic Links
      • WebAuthn & Passkeys
    • SAML v2 IdP
      • Overview
      • Google
      • Zendesk
  • Developer Guide
    • Overview
    • API Gateways
      • Overview
      • 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
      • 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
      • Sony PSN Reconcile
      • Steam Reconcile
      • Twitch Reconcile
      • Twitter Reconcile
      • Xbox Reconcile
    • Messengers
      • Overview
      • Generic Messenger
      • Twilio Messenger
    • Themes
      • Overview
      • Examples
      • Helpers
      • Localization
      • Template Variables
  • 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
      • 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
    • 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

    FusionAuth React SDK

    This is in beta testing. Please file issues to let us know how we can improve this SDK.

    You can track the progress towards release in this GitHub issue.

    Overview

    This SDK allows you to add login, logout, and registration buttons to your React application. You can do this via pre-built buttons, hooks, or higher-order components.

    Your users will be sent to FusionAuth’s themeable hosted login pages and then log in. After that, they are sent back to your React application.

    Once authentication succeeds, the following secure, HTTP-only cookies will be set:

    • access_token - an OAuth Access Token

    • refresh_token - a Refresh Token used to obtain a new access_token. This cookie will only be set if refresh tokens are enabled on your FusionAuth instance.

    The access token can be presented to APIs to authorize the request and the refresh token can be used to get a new access token.

    Note that this SDK requires you to have a server that performs the OAuth token exchange. See Server Code Requirements for more details.

    You can use this library against any version of FusionAuth or any OIDC compliant identity server.

    Getting Started

    Installation

    NPM:

    
    npm install @fusionauth/react-sdk

    Yarn:

    
    yarn add @fusionauth/react-sdk

    Configuring Provider

    To configure the SDK, wrap your app with FusionAuthProvider:

    
    import React from 'react';
    import { createRoot } from 'react-dom/client';
    import { FusionAuthProvider } from '@fusionauth/react-sdk';
    import App from './App';
    
    const container = document.getElementById('root');
    const root = createRoot(container!);
    
    root.render(
      <FusionAuthProvider
        baseUrl=""      // The base URL of your FusionAuth instance
        clientID=""     // Your FusionAuth client ID
        serverUrl=""    // The base URL of your server for the token exchange
        redirectUri=""  // The URI that the user is directed to after the login/register/logout action
      >
        <App />
      </FusionAuthProvider>
    );

    Server Code Requirements

    Authenticating with FusionAuth requires you to set up a server that will be used to perform the OAuth token exchange. This server must have the following endpoints:

    POST /token-exchange

    This endpoint must:

    1. Call /oauth2/token to complete the Authorization Code Grant request. The code and code_verifier parameters should come from the request body, while the rest of the parameters should be set/configured on the server side.

    2. Once the token exchange succeeds, read the access_token from the response body and set it as a secure, HTTP-only cookie with the same name.

    3. If you wish to support refresh tokens, repeat step 2 for the refresh_token cookie.

    4. Call /oauth2/userinfo to retrieve the user info object and respond back to the client with this object.

    Example implementation

    GET /logout

    This endpoint must:

    1. Clear the access_token and refresh_token secure, HTTP-only cookies.

    Example implementation

    POST /jwt-refresh (optional)

    This endpoint is necessary if you wish to use refresh tokens. This endpoint must:

    1. Call /api/jwt/refresh to get a new access_token and refresh_token.

    2. Update the access_token and refresh_token cookies from the response.

    Example implementation

    Usage

    Pre-built buttons

    There are three pre-styled buttons that are configured to perform login/logout/registration. They can be placed anywhere in your app as is.

    
    import {
      FusionAuthLoginButton,
      FusionAuthLogoutButton,
      FusionAuthRegisterButton
    } from '@fusionauth/react-sdk';
    
    export const LoginPage = () => (
      <>
        <h1>Welcome, please log in or register</h1>
        <FusionAuthLoginButton />
        <FusionAuthRegisterButton />
      </>
    );
    
    export const AccountPage = () => (
      <>
        <h1>Hello, user!</h1>
        <FusionAuthLogoutButton />
      </>
    );

    Programmatic usage

    Alternatively, you may interact with the SDK programmatically using the useFusionAuth hook or withFusionAuth HOC.

    useFusionAuth

    Use the useFusionAuth hook with your functional components to get access to the properties exposed by FusionAuthContext:

    
    import React from 'react';
    import { useFusionAuth } from '@fusionauth/react-sdk';
    
    const App = () => {
      const { login, logout, register, isAuthenticated } = useFusionAuth();
    
      return isAuthenticated ? (
        <div>
          <span>Hello, user!</span>
          <button onClick={() => logout()}>Logout</button>
        </div>
      ) : (
        <div>
          <button onClick={() => login()}>Log in</button>
          <button onClick={() => register()}>Register</button>
        </div>
      );
    };

    See useFusionAuth for more details.

    withFusionAuth

    The withFusionAuth higher-order component can be used to wrap your components and give them access to a fusionAuth prop which contains all the properties exposed by the FusionAuthContext. This works with both functional and class components:

    Functional Component
    
    import React from 'react';
    import { withFusionAuth, WithFusionAuthProps } from '@fusionauth/react-sdk';
    
    const LogoutButton: React.FC<WithFusionAuthProps> = props => {
      const { logout } = props.fusionAuth;
    
      return <button onClick={() => logout()}>Logout</button>;
    }
    
    export default withFusionAuth(LogoutButton);
    Class Component
    
    import React, { Component } from 'react';
    import { withFusionAuth, WithFusionAuthProps } from '@fusionauth/react-sdk';
    
    class LogoutButton extends Component<WithFusionAuthProps> {
      render() {
        const { logout } = this.props.fusionAuth;
        return <button onClick={() => logout()}>Logout</button>;
      }
    }
    
    export default withFusionAuth(LogoutButton);

    See withFusionAuth for more details.

    State parameter

    The login and register functions both accept an optional string parameter called state. The state that is passed in to the function call will be passed back to the onRedirectSuccess handler on your FusionAuthProvider. Though you may pass any value you would like for the state parameter, it is often used to indicate which page the user was on before redirecting to login or registration, so that the user can be returned to that location after a successful authentication.

    Protecting Content

    The RequireAuth component can be used to protect information from unauthorized users. It takes an optional prop withRole that can be used to ensure the user has a specific role.

    
    import { RequireAuth, useFusionAuth } from '@fusionauth/react-sdk';
    
    const UserNameDisplay = () => {
      const { user } = useFusionAuth();
    
      return (
        <RequireAuth>
          <p>User: {user.name}</p> // Only displays if user is authenticated
        </RequireAuth>
      );
    };
    
    const AdminPanel = () => (
      <RequireAuth withRole="admin">
        <button>Delete User</button> // Only displays if user is authenticated and has 'admin' role
      </RequireAuth>
    );

    Known Issues

    Token exchange endpoint being called repeatedly

    If you see the token exchange endpoint being called multiple times, this is due to a dev time setting in React 18. When running using StrictMode in development mode, React 18 will mount, unmount, and remount all components in this mode, which results in the network call running twice.

    This will not happen in a production build or if StrictMode is disabled.

    If you remove the React.StrictMode tags in index.tsx of the example app, the call is only made once.

    Example App

    See the FusionAuth React SDK Example for functional example of a React client that utilizes the SDK as well as an Express server that performs the token exchange.

    Documentation

    Full library documentation

    Source Code

    The source code is available here: https://github.com/FusionAuth/fusionauth-react-sdk/

    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
    Subscribe for developer updates