@fusionauth/react-sdk

中文文档
2.7.0发布于 2026/08/06ApacheTypeScriptES Module构建来源已验证近 30 天下载 6.1万

FusionAuth solves the problem of building essential security without adding risk or distracting from your primary application

原始使用文档
文档目录14 节
  1. Getting Started
  2. Quickstart
  3. Installation
  4. Configuration
  5. Usage
  6. useFusionAuth
  7. Protecting Content
  8. UI Components
  9. DPoP Mode
  10. Known Issues
  11. Documentation
  12. Formatting
  13. Releases
  14. Upgrade Policy

An SDK for using FusionAuth in React applications.

Table of Contents

Overview

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

  • app.rt - a 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.
  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.

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 for a full tutorial on using FusionAuth and React.

Installation

NPM:

npm install @fusionauth/react-sdk

Yarn:

yarn add @fusionauth/react-sdk

Configuration

Wrap your app with FusionAuthProvider.

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.
  // useDpop: true, // Opt-in to DPoP mode. See "DPoP Mode" below. Defaults to false.
};

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

Configuration with NextJS

To configure the SDK with Next, install next-client-cookies and pass useCookies into the config object as nextCookieAdapter.

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

Usage

useFusionAuth

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

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.

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.

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

DPoP Mode

By default, the SDK calls a Hosted Backend that stores tokens in HttpOnly cookies (useDpop: false, the default). In DPoP mode, the SDK instead calls FusionAuth endpoints directly and binds tokens to a private key generated in the browser, per RFC 9449. Enable it by setting useDpop: true on FusionAuthProviderConfig:

const config: FusionAuthProviderConfig = {
  clientId: "",
  redirectUri: "",
  serverUrl: "",
  useDpop: true, // Opt-in to DPoP mode.
  dpopTokenStorage: 'localStorage', // 'localStorage' (default, persists across reloads) or 'memory'.
};

When useDpop: true, useFusionAuth() additionally returns dpopFetch, generateProof, and getAccessToken. These are undefined when useDpop is false or not set.

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

// Recommended — handles attaching DPoP headers (and nonce retries) automatically.
const response = await dpopFetch('https://api.example.com/data', { method: 'GET' });

// Advanced — for axios or other HTTP libraries that can't use dpopFetch.
const accessToken = getAccessToken();
const proof = await generateProof('https://api.example.com/data', 'GET', accessToken);
// axios.get('https://api.example.com/data', {
//   headers: { Authorization: `DPoP ${accessToken}`, DPoP: proof }
// });

Known Issues

None.

Documentation

Full library documentation

These docs are generated with typedoc and configured with typedoc-plugin-markdown.

Formatting

There are several linting packages run when you push to a branch. One is prettier. If this fails, you can fix the files from the command line:

  • npm run install
  • npm run prettier -- -w /path/to/file

Doing this will overwrite your file, but fix prettier's objections.

Releases

This package is released via GitHub actions.

Upgrade Policy

This library 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 dependency (e.g. language, framework, or operating system) is deprecated by its maintainer, this library will also be deprecated by us, and may eventually be updated to use a newer version.

版本与发布记录

@fusionauth/react-sdk 共发布 25 个版本,首次发布于 2023/01/19;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.7.0latest2026/08/063 个月前
2.6.02026/06/244 个月前
2.5.22026/05/166 个月前
2.5.12025/04/041.6 年前
2.5.02025/04/031.6 年前
2.4.32024/09/202 年前

关于 @fusionauth/react-sdk 的常见问题

@fusionauth/react-sdk 是什么?

FusionAuth solves the problem of building essential security without adding risk or distracting from your primary application

如何安装 @fusionauth/react-sdk?

在项目目录运行 npm install @fusionauth/react-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18.2.0)、react-dom(>=18.2.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@fusionauth/react-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fusionauth/react-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@fusionauth/react-sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@fusionauth/react-sdk 可以商用吗?

@fusionauth/react-sdk 使用 Apache 许可。声明的许可为 Apache,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@fusionauth/react-sdk 的下载量有多少?

根据 npm 官方下载统计,@fusionauth/react-sdk 在 2026/10/16 – 2026/11/14 这 30 天内被下载 61,276 次,日均约 2,043 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fusionauth/react-sdk 还在维护吗?

最新版本 2.7.0 发布于 2026/08/06(3 个月前);至今共发布 25 个版本,其中过去 12 个月发布了 3 个;首次发布于 2023/01/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。