> For the complete documentation index, see [llms.txt](https://fusionauth.io/docs/llms.txt)

# React SDK | FusionAuth Docs

The FusionAuth React SDK allows you to add login, logout and registration functionality to your React application.

# React SDK

[Edit on GitHub](https://github.com/FusionAuth/fusionauth-site/blob/main/astro/src/content/docs/sdks/react-sdk.mdx)

[View Markdown](https://fusionauth.io/docs/sdks/react-sdk.md)

This SDK manages authentication state for your React app and provides functionality to login, register, and logout users. It can be easily configured to automatically manage your refresh token and fetch user info.

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:

*   `app.at` - an OAuth [Access Token](https://fusionauth.io/docs/v1/tech/oauth/tokens.md#access-token)
    
*   `app.rt` - a [Refresh Token](https://fusionauth.io/docs/v1/tech/oauth/tokens.md#refresh-token) used to obtain a new `app.at`. 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.

There are 2 ways to interact with this SDK:

1.  By hosting your own server that performs the OAuth token exchange and meets the [server code requirements for FusionAuth Web SDKs](https://github.com/FusionAuth/fusionauth-javascript-sdk-express#server-code-requirements).
2.  By using the server hosted on your FusionAuth instance, i.e., not writing your own server code.

If you are hosting your own server, see [server code requirements](https://github.com/FusionAuth/fusionauth-javascript-sdk-express#server-code-requirements).

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

## Getting Started

If you are new to React development, you may want to start with the Quickstart guide. If you are already familiar with React development, skip to the Installation section.

### Quickstart

See the [FusionAuth React Quickstart](https://fusionauth.io/docs/quickstarts/quickstart-javascript-react-web.md) for a full tutorial on using FusionAuth and React.

### Installation

NPM:

```bash
npm install @fusionauth/react-sdk
```

Yarn:

```bash
yarn add @fusionauth/react-sdk
```

### Configuration

Wrap your app with `FusionAuthProvider`.

```jsx
import ReactDOM from 'react-dom/client';
import { FusionAuthProviderConfig, FusionAuthProvider } from '@fusionauth/react-sdk';

const config: FusionAuthProviderConfig = {
  clientId: "", // Your app's FusionAuth client id
  redirectUri: "", // The URI that the user is directed to after the login/register/logout action
  serverUrl: "", // The url of the server that performs the token exchange
  shouldAutoFetchUserInfo: true, // Automatically fetch userInfo when logged in. Defaults to false.
  shouldAutoRefresh: true, // Enables automatic token refresh. Defaults to false.
  onRedirect: (state?: string) => { }, // Optional callback invoked upon redirect back from login or register.
};

ReactDOM.createRoot(document.getElementById("my-app")).render(
  <FusionAuthProvider {...config}>
    <App />
  </FusionAuthProvider>
)
```

#### Configuration with [NextJS](https://nextjs.org/)

To configure the SDK with Next, install [next-client-cookies](https://github.com/moshest/next-client-cookies?tab=readme-ov-file#install) and pass `useCookies` into the config object as `nextCookieAdapter`.

```jsx
'use client'

import { useCookies } from 'next-client-cookies';

export default function Providers({ children }) {
  return (
    <FusionAuthProvider {...config} nextCookieAdapter={useCookies}>
      {children}
    </FusionAuthProvider>
  );
}
```

Remember to wrap your layout in the `<CookiesProvider/>` from `next-client-cookies/server`.

Vercel has published a guide for [rendering third party context providers in server components](https://vercel.com/guides/react-context-state-management-nextjs#rendering-third-party-context-providers-in-server-components).

## Usage

### useFusionAuth

Once your app is wrapped in `FusionAuthProvider`, you can use `useFusionAuth`.

```jsx
import { useFusionAuth } from '@fusionauth/react-sdk';

function MyComponent() {
  const {
    isLoggedIn,
    isFetchingUserInfo,
    startLogin,
    startRegister,
    userInfo
  } = useFusionAuth()

  if (isFetchingUserInfo) {
    return <p>Loading...</p>
  }

  if (!isLoggedIn) {
    return (
      <div>
        <button onClick={startLogin}>Login</button>
        <p>or</p>
        <button onClick={startRegister}>Register</button>
      </div>
    );
  }

  if (userInfo?.given_name) {
    return <p>Welcome {userInfo.given_name}!</p>
  }
}
```

Alternatively, you may interact with the SDK using the `withFusionAuth` higher-order component.

#### State Parameter

The `startLogin` and `startRegister` functions accept an optional string parameter: `state`. The value passed in will be passed to the `onRedirect` callback on your `FusionAuthProviderConfig`. 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. If an array of roles is passed, the user must have at least one of the roles to be authorized. The `Unauthenticated` component provides the inverse functionality.

```jsx
import { RequireAuth, useFusionAuth } from '@fusionauth/react-sdk';

const UserNameDisplay = () => {
  const { userInfo } = useFusionAuth();

  return (
    <>
      <RequireAuth>
        <p>User: {userInfo.given_name}</p> // Only displays if user is authenticated
      </RequireAuth>
      
      <Unauthenticated>
        <p>Please log in to view this page</p>
      </Unauthenticated>
    </>
  );
};

const AdminPanel = () => (
  <RequireAuth withRole="admin">
    <button>Delete User</button> // Only displays if user is authenticated and has 'admin' role
  </RequireAuth>
);
```

### UI Components

This SDK offers 3 pre-built UI components.

```jsx
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 />
  </>
);
```

### Known Issues

None.

## Documentation

[Full library documentation](https://github.com/FusionAuth/fusionauth-javascript-sdk/tree/main/packages/sdk-react/docs)

These docs are generated with [typedoc](https://typedoc.org/) and configured with [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown).

## Usage With FusionAuth Cloud

When developing against a FusionAuth Cloud instance with a hostname ending in `fusionauth.io`, unless your application shares the same domain of `fusionauth.io` attempts to use these endpoints will fail with a `403` status code.

These endpoints do not work correctly for cross origin requests. Cross origin requests occur when the application making the request to FusionAuth is using a separate domain. For example, if your application URL is `app.acme.com` and the FusionAuth URL is `acme.fusionauth.io` requests from your application to FusionAuth will be considered cross origin.

If possible, have FusionAuth and your application served by the same domain, using a [proxy if needed](https://fusionauth.io/docs/operate/deploy/proxy-setup.md). 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:

*   Develop using a local FusionAuth instance, so both your webapp and FusionAuth are running on `localhost`.
*   Do not use the FusionAuth hosted backend, and instead write your own backend with a cross origin cookie policy: [here’s an example](https://github.com/FusionAuth/fusionauth-javascript-sdk-express/tree/main).
*   Configure a [custom domain name for the FusionAuth Cloud instance](https://fusionauth.io/docs/get-started/run-in-the-cloud/cloud.md#updating-with-existing-custom-domains).

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

## Source Code

The source code is available here: [https://github.com/FusionAuth/fusionauth-javascript-sdk/tree/main/packages/sdk-react/](https://github.com/FusionAuth/fusionauth-javascript-sdk/tree/main/packages/sdk-react/)

## Upgrade Policy

Besides the releases made to keep track of the FusionAuth API as mentioned above, SDKs and Client Libraries may periodically receive updates with bug fixes, security patches, tests, code samples, or documentation changes.

These releases may also update dependencies, language engines, and operating systems, as we'll follow the deprecation and sunsetting policies of the underlying technologies that the libraries use.

This means that after a language, framework, or operating system is deprecated by their own maintainer, our SDKs and Client Libraries that depend on it will also be deprecated by us, and will eventually be updated to use a newer version.

For more information about upgrades, see our [Upgrade guide](https://fusionauth.io/docs/operate/deploy/upgrade.md#upgrade-a-client-library).