React SDK Implementation Recipes & Patterns
Recipes for the React SDK: HumanityProvider config, HumanityGate patterns, popup vs redirect auth, protected routes, and token storage options.
Prerequisites
@humanity-org/react-sdkinstalledA Humanity
clientIdand registeredredirectUrifrom the Developer PortalHumanityProviderat the root of your app (Recipe 1 covers setup)
npm install @humanity-org/react-sdkRecipe 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.
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: HumanityProvider
Recipe 2 — Sign out
To navigate after signing out, call logout() then redirect with your router:
Full prop reference useAuth()
Recipe 3 — Protect a route with React Router
Check isAuthenticated from useAuth and redirect before rendering protected content.
Wire it into your router:
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.
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
sessionStorageduring 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 HumanityProvider
Last updated