Add Login to a React App with the FusionAuth React SDK

On this page

The React SDK adds login, registration, and logout to a React application, and tracks whether the user is logged in. To build a complete application step by step, see the React QuickStart.

The SDK sends users to the FusionAuth hosted login pages, which you can style with a theme. After login, FusionAuth sends users back to your React application.

By default, the SDK uses the hosted backend on your FusionAuth instance, so your application needs no server code. The hosted backend exchanges the authorization code for tokens and stores the tokens in HttpOnly cookiesA cookie that the browser sends with requests but hides from JavaScript, so a cross-site scripting attack can't read the cookie.:

  • app.at holds the access token. Your APIs read the access token to authorize requests.
  • app.rt holds the refresh token. The SDK uses the refresh token to get a new access token.

To run the token exchange on your own server instead, see Use Your Own Backend. To keep tokens in the browser and bind the tokens to a key, use DPoP mode.

Prerequisites#

  • FusionAuth 1.45.0 or later, which adds the hosted backend.
  • A FusionAuth ApplicationA software program that your users log in to through FusionAuth.. On the OAuth tab of the Application, add the URL that FusionAuth returns users to after login to Authorized redirect URLs. The SDK calls this URL redirectUri.
  • CORSA browser security mechanism that lets a web page request restricted resources from another domain when the server allows the request. that accepts requests from your application. Under Settings -> System -> CORS , enable Include credentials in CORS requests, add the origin of your application to Allowed origins, and allow the GET and POST methods. The SDK sends the token cookies with each request to FusionAuth, so FusionAuth must accept credentials from your origin.
  • React 18.2.0 or later.
FusionAuth Cloud blocks cross-site hosted backend requests

When developing against a FusionAuth Cloud instance with a hostname ending in fusionauth.io, requests from applications outside the fusionauth.io domain fail with a 403 status code.

These endpoints do not work correctly for cross-site requests. A cross-site request comes from an application on a different registrable domain than FusionAuth. For example, requests from app.acme.com to acme.fusionauth.io are cross-site.

If possible, have FusionAuth and your application served by the same domain, using a proxy if needed. For example, serve your app from app.acme.com and FusionAuth from auth.acme.com.

If this configuration is not possible, use one of these alternative methods:

Modifying FusionAuth CORS configuration options does not fix this issue because the cookies that FusionAuth writes will not be accessible cross domain.

Add Login to Your Application#

  1. Install the SDK:

    $ npm install @fusionauth/react-sdk
    
  2. Wrap your application in FusionAuthProvider. Set clientId to the client Id of your FusionAuth Application, serverUrl to the URL of your FusionAuth instance, and redirectUri to the URL you added to Authorized redirect URLs:

    import ReactDOM from 'react-dom/client';
    import { FusionAuthProvider, FusionAuthProviderConfig } from '@fusionauth/react-sdk';
    
    const config: FusionAuthProviderConfig = {
      clientId: 'e9fdb985-9173-4e01-9d73-ac2d60d1dc8e',
      serverUrl: 'http://localhost:9011',
      redirectUri: 'http://localhost:3000',
      shouldAutoFetchUserInfo: true,
      shouldAutoRefresh: true,
    };
    
    ReactDOM.createRoot(document.getElementById('root')!).render(
      <FusionAuthProvider {...config}>
        <App />
      </FusionAuthProvider>
    );
    

    shouldAutoFetchUserInfo loads the user's profile after login, and shouldAutoRefresh refreshes the access token before the token expires. For every option, see Web SDK Configuration.

  3. Call the useFusionAuth hook in a component to add login, registration, and logout buttons:

    import { useFusionAuth } from '@fusionauth/react-sdk';
    
    export function AuthButtons() {
      const {
        isLoggedIn,
        isFetchingUserInfo,
        startLogin,
        startLogout,
        startRegister,
        userInfo,
      } = useFusionAuth();
    
      if (isFetchingUserInfo) {
        return <p>Loading...</p>;
      }
    
      if (!isLoggedIn) {
        return (
          <div>
            <button onClick={() => startLogin()}>Log In</button>
            <button onClick={() => startRegister()}>Register</button>
          </div>
        );
      }
    
      return (
        <div>
          {userInfo?.given_name && <p>Welcome {userInfo.given_name}!</p>}
          <button onClick={() => startLogout()}>Log Out</button>
        </div>
      );
    }
    

    startLogin and startRegister send the browser to the FusionAuth login and registration pages. startLogout ends the session and returns the browser to redirectUri. To return users to a different page after logout, set postLogoutRedirectUri and add the URL to Authorized redirect URLs.

  4. Start your application and click Log In . The browser opens the FusionAuth login page. After you log in, FusionAuth returns you to your application, and the component shows Log Out .

For every value that useFusionAuth returns, see the FusionAuthProviderContext reference. For class components, wrap the component in the withFusionAuth higher-order component. The component then receives the same values in the fusionAuth prop.

Use the Pre-Built Buttons#

Instead of writing your own buttons, use the styled buttons from the SDK. Each button calls the matching useFusionAuth function:

import {
  FusionAuthLoginButton,
  FusionAuthLogoutButton,
  FusionAuthRegisterButton,
} from '@fusionauth/react-sdk';

export const LoginPage = () => (
  <>
    <FusionAuthLoginButton />
    <FusionAuthRegisterButton />
  </>
);

export const AccountPage = () => <FusionAuthLogoutButton />;

Show Content by Login State and Role#

Wrap content in RequireAuth to show the content only to logged-in users. Set withRole to a role name, or to an array of role names, to require at least one of the roles. Wrap content in Unauthenticated to show the content only to logged-out users:

import { RequireAuth, Unauthenticated } from '@fusionauth/react-sdk';

export const AdminPanel = () => (
  <>
    <RequireAuth withRole={['admin', 'editor']}>
      <button>Delete User</button>
    </RequireAuth>
    <Unauthenticated>
      <p>Log in to manage users.</p>
    </Unauthenticated>
  </>
);

RequireAuth reads the roles from the user's profile. When you set withRole, set shouldAutoFetchUserInfo to true, or call fetchUserInfo from useFusionAuth.

These components only change what the browser shows. Check the access token on your server before you return protected data.

Return Users to a Page After Login#

To return users to the page they started from, pass a string to startLogin or startRegister. The SDK passes the string to the onRedirect function when the browser returns from FusionAuth:

const config: FusionAuthProviderConfig = {
  // ...
  onRedirect: (state?: string) => {
    if (state) window.location.assign(state);
  },
};

startLogin(window.location.pathname);

The pre-built login and register buttons accept the same string in the state prop.

Use the SDK with Next.js#

To read the token cookies during server rendering in Next.js, pass the useCookies function from next-client-cookies as nextCookieAdapter:

  1. Install next-client-cookies:

    $ npm install next-client-cookies
    
  2. Create a client component that wraps your application in FusionAuthProvider:

    'use client';
    
    import { FusionAuthProvider } from '@fusionauth/react-sdk';
    import { useCookies } from 'next-client-cookies';
    
    export default function Providers({ children }: { children: React.ReactNode }) {
      return (
        <FusionAuthProvider {...config} nextCookieAdapter={useCookies}>
          {children}
        </FusionAuthProvider>
      );
    }
    
  3. In your root layout, wrap Providers in the CookiesProvider from next-client-cookies/server. For more information, see the Vercel guide to rendering third-party context providers in server components.

Call APIs in DPoP Mode#

In DPoPAn OAuth 2.0 extension that ties access and refresh tokens to a key pair that the client holds. A stolen token doesn't work without the private key. mode, the SDK calls FusionAuth directly instead of the hosted backend, and binds each token to a key that the browser generates. A stolen DPoP token doesn't work without the key. DPoP mode requires React SDK 2.7.0 and FusionAuth 1.63.0 or later. To configure FusionAuth for DPoP, see Use DPoP in a Browser App.

To enable DPoP mode, set useDpop to true:

const config: FusionAuthProviderConfig = {
  clientId: 'e9fdb985-9173-4e01-9d73-ac2d60d1dc8e',
  serverUrl: 'http://localhost:9011',
  redirectUri: 'http://localhost:3000',
  useDpop: true,
  dpopTokenStorage: 'localStorage',
};

With localStorage, the user stays logged in across page reloads. With memory, a reload logs the user out.

In DPoP mode, useFusionAuth also returns dpopFetch, generateProof, and getAccessToken. Call dpopFetch like fetch. dpopFetch adds the DPoP headers and retries when the server asks for a new nonce:

const { dpopFetch, generateProof, getAccessToken } = useFusionAuth();

const response = await dpopFetch('https://api.example.com/data', { method: 'GET' });

When you use an HTTP library such as axios, build the headers with getAccessToken and generateProof:

const accessToken = getAccessToken();
const proof = await generateProof('https://api.example.com/data', 'GET', accessToken);

await axios.get('https://api.example.com/data', {
  headers: { Authorization: `DPoP ${accessToken}`, DPoP: proof },
});

The three functions are undefined when useDpop is false.