> For the complete documentation index, see [llms.txt](https://docs.humanity.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.humanity.org/developer-guides-and-tutorials/sdk-api-guides/react-sdk/react-sdk-implementation-recipes-and-patterns.md).

# React SDK Implementation Recipes & Patterns

Recipes for the React SDK: HumanityProvider config, HumanityGate patterns, popup vs redirect auth, protected routes, and token storage options.

{% hint style="info" %}
Task-based recipes built on top of [@humanity-org/react-sdk](https://docs.humanity.org/build-with-humanity/build-with-the-sdk-api/humanity-org-react-sdk.md)
{% endhint %}

## Prerequisites

* `@humanity-org/react-sdk` installed
* A Humanity `clientId` and registered `redirectUri` from the [Developer Portal](https://developers.humanity.org)
* `HumanityProvider` at the root of your app (Recipe 1 covers setup)

```bash
npm install @humanity-org/react-sdk
```

## Recipe 1 — Wrap your app with HumanityProvider

Every component and hook in the React SDK must be inside `HumanityProvider`. It goes at the root of your app, before your router, before anything else.

```tsx
import { HumanityProvider } from '@humanity-org/react-sdk';

function App() {
  return (
    <HumanityProvider
      clientId={import.meta.env.VITE_HUMANITY_CLIENT_ID}
      redirectUri={import.meta.env.VITE_HUMANITY_REDIRECT_URI}
      environment="sandbox"
      storage="memory"
    >
      {/* rest of your app */}
    </HumanityProvider>
  );
}
```

**`environment`:** Use `"sandbox"` during development. Switch to `"production"` before going live — this points the SDK at the production Humanity API.

**`storage`:** `"memory"` (the default) keeps tokens in JS memory only — they don't survive a page refresh. See Recipe 12 for when to change this.

Full prop reference: [Components](https://docs.humanity.org/build-with-humanity/build-with-the-sdk-api/humanity-org-react-sdk/components.md#humanityprovider)

## Recipe 2 — Sign out

```tsx
import { useAuth } from '@humanity-org/react-sdk';

function SignOutButton() {
  const { logout } = useAuth();
  return <button onClick={logout}>Sign out</button>;
}
```

To navigate after signing out, call `logout()` then redirect with your router:

```tsx
import { useAuth } from '@humanity-org/react-sdk';
import { useNavigate } from 'react-router-dom';

function SignOutButton() {
  const { logout } = useAuth();
  const navigate = useNavigate();

  const handleSignOut = () => {
    logout();
    navigate('/');
  };

  return <button onClick={handleSignOut}>Sign out</button>;
}
```

Full prop reference [Hooks](https://docs.humanity.org/build-with-humanity/build-with-the-sdk-api/humanity-org-react-sdk/hooks.md#useauth)

## Recipe 3 — Protect a route with React Router

Check `isAuthenticated` from `useAuth` and redirect before rendering protected content.

```tsx
import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '@humanity-org/react-sdk';

function ProtectedRoute() {
  const { isAuthenticated, isLoading } = useAuth();

  if (isLoading) return <div>Loading...</div>;
  if (!isAuthenticated) return <Navigate to="/login" replace />;

  return <Outlet />;
}
```

Wire it into your router:

```tsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';

<BrowserRouter>
  <Routes>
    <Route path="/login" element={<LoginPage />} />
    <Route element={<ProtectedRoute />}>
      <Route path="/dashboard" element={<Dashboard />} />
      <Route path="/profile" element={<Profile />} />
    </Route>
  </Routes>
</BrowserRouter>
```

Any route nested under `<ProtectedRoute />` redirects to `/login` if the user isn't authenticated.

## Recipe 4 — Choose a token storage strategy

Set `storage` on `HumanityProvider`. The choice affects security and session persistence.

```tsx
<HumanityProvider
  clientId="hp_xxx"
  redirectUri="https://app.com/callback"
  storage="memory"
>
  <App />
</HumanityProvider>
```

| Strategy         | Security | Survives refresh | When to use                                                                                         |
| ---------------- | -------- | ---------------- | --------------------------------------------------------------------------------------------------- |
| `memory`         | Highest  | No               | Default. Tokens live in JS memory only. Right for most apps.                                        |
| `sessionStorage` | Medium   | No               | Tokens persist across React re-renders but clear when the tab closes.                               |
| `localStorage`   | Lower    | Yes              | Only when persistence across browser restarts is a hard requirement. Understand the XSS risk first. |

Start with `memory`. Switch to `sessionStorage` if users are losing their session on page reload in a way that disrupts the experience. Use `localStorage` only when persistence across browser restarts is a hard requirement — and not before checking your XSS exposure.

`localStorage` tokens are readable by any JS on the page. If you load third-party scripts (analytics, ads, widgets), that's a real risk.

> ⚠️ **Firefox and Safari:** both browsers clear `sessionStorage` during cross-domain OAuth redirects, which can cause silent auth failures in redirect mode. If you need to support these browsers with redirect mode, test this flow before shipping.

Full prop reference [Components](https://docs.humanity.org/build-with-humanity/build-with-the-sdk-api/humanity-org-react-sdk/components.md#humanityprovider)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.humanity.org/developer-guides-and-tutorials/sdk-api-guides/react-sdk/react-sdk-implementation-recipes-and-patterns.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
