React Quickstart
Use this guide to build a React application for a business-to-business (B2B) product with @thunderid/react.
What You Will Learn
- Create a new React app using Vite
- Install the
@thunderid/reactpackage - Build with Choreo Identity & Access Management prebuilt components
- Let companies register as organizations with an organization sign-up flow
- Switch between organizations
- Let each company bring its own enterprise identity provider
Prerequisites
- About 15 minutes
- Node.js 20.19+ or 22.12+
- npm
- Your preferred code editor
Set Up the Application in Choreo Identity & Access Management
The sample ships the application's configuration as one file: an account type, two roles, the sign-up and sign-in flows, and the application. They go into the Default organization unit, and every company that signs up becomes its child.
-
Copy the resources:
npx degit thunder-id/samples/quickstarts/react-b2b/thunderid-config thunderid-config -
Point the resources at the Data Plane resource server. The file names that resource server by ID, and in Choreo Identity & Access Management its ID is
01a1864b-ef42-7c41-b0a2-97f53fd3b1e4. Replace the ID the file ships with:perl -pi -e 's/01900000-0000-7000-8000-000000000020/01a1864b-ef42-7c41-b0a2-97f53fd3b1e4/g' thunderid-config/thunderid-config.yaml -
Sign in to the Console at https://console.cloud.choreolabs.com/iam/. Select the Default project in the project switcher in the header.
-
Import the resources:
- Choose Import / Export, then Import.
- Upload
thunderid-config.yamlas the configuration file. - Upload
thunderid.envas the environment variables file. - Choose Continue, then Import configuration.
-
Clear the project selection, choose Configurations in the sidebar, then CORS. Choose Add origin, enter
http://localhost:5173, and choose Save changes, so the browser lets the application call Choreo Identity & Access Management.
Saving a change does not make it live. You author in the control plane, and your users sign in on a separate data plane, so a change takes effect in an environment only after you deploy it. Go to Deploy, deploy the latest version to your first environment, then promote it to the next environment when you are ready.
Auto-sync deploys saved changes to your first environment within seconds. Turning it on is your choice, per project. See Deploy a Version, or learn why you deploy and how auto-sync works.
| Resource | Name | What it does |
|---|---|---|
| User type | React B2B User | The account schema, usable in every company |
| Server config | defaultResourceServer | Makes the Data Plane resource server the default for authorization requests that name no resource. |
| Role | React B2B Admin | Grants the org permission, which manages the organization a token names. The role is shared with every company. |
| Role | React B2B Member | Grants no permission. The role is shared with every company. |
| Flow | React B2B Quickstart Company Sign-up | Creates the company and its first admin, with the account inside the company or shared into it |
| Flow | React B2B Quickstart Sign-in | Password, enterprise single sign-on (SSO), or company sign-up. Keeps an SSO session, and lets each company set its own enterpriseIdp. |
| Application | React B2B Quickstart | Client ID REACT_B2B_QUICKSTART, redirecting to http://localhost:5173. Has the token exchange grant, so a switch can exchange the device secret. The application is shared with every company. |
Create a React App
Create the app with Vite, and add the SDK:
npm create vite@latest react-b2b -- --template react
cd react-b2b
npm install
npm install @thunderid/react
Add ThunderIDProvider
Create a .env file with the values the import set up:
Code in this guide uses https://<DATA_PLANE_URL> for your environment's data plane URL, where users sign in and tokens are issued. Replace it with the URL on the environment's Endpoints page. To open it, select your project, go to Deployment pipeline, and click Open environment on the environment's card. See Control Plane and Data Plane URLs.
VITE_THUNDERID_BASE_URL=https://<DATA_PLANE_URL>
VITE_THUNDERID_CLIENT_ID=REACT_B2B_QUICKSTART
VITE_THUNDERID_RESOURCE=https://<DATA_PLANE_URL>
VITE_THUNDERID_SIGN_IN_FLOW_ID=019f0b10-0000-7000-8000-000000000021
Then wrap the app in <ThunderIDProvider />:
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { ThunderIDProvider } from '@thunderid/react'
import App from "./App.jsx"
import './index.css'
createRoot(document.getElementById('root')).render(
<StrictMode>
<ThunderIDProvider
clientId={import.meta.env.VITE_THUNDERID_CLIENT_ID}
baseUrl={import.meta.env.VITE_THUNDERID_BASE_URL}
scopes={['openid', 'profile', 'email', 'roles', 'ou', 'org', 'device_sso']}
signInOptions={{ resource: import.meta.env.VITE_THUNDERID_RESOURCE }}
preferences={{ user: { fetchUserProfile: false } }}
>
<App />
</ThunderIDProvider>
</StrictMode>
)
| Parameter | Description |
|---|---|
scopes | ou and roles put the company and the roles held there into the tokens. org asks for the permission a company admin needs. device_sso returns a device secret, which a switch exchanges for another company's tokens without leaving the page. |
signInOptions.resource | org is a permission of the Data Plane resource server, so a sign-in names that resource server. |
preferences.user.fetchUserProfile | false reads the signed-in user from the ID token, which names the company the session signed in to. |
Show the Token
Show the organization claims, roles, and scopes of the access token. They change with every switch, because a switch signs the user in to another company and replaces the tokens:
import { useEffect, useState } from 'react'
import { useThunderID } from '@thunderid/react'
const decodePayload = (token) => {
const payload = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
const bytes = Uint8Array.from(atob(payload), (char) => char.charCodeAt(0))
return JSON.parse(new TextDecoder().decode(bytes))
}
export default function TokenClaims() {
const { currentOrganizationUnit, getAccessToken } = useThunderID()
const [claims, setClaims] = useState(null)
useEffect(() => {
getAccessToken()
.then((token) => setClaims(decodePayload(token)))
.catch(() => setClaims(null))
}, [getAccessToken, currentOrganizationUnit?.id])
if (!claims) {
return null
}
return (
<section>
<h2>Access token</h2>
<p>ouName <code>{claims.ouName}</code></p>
<p>ouHandle <code>{claims.ouHandle}</code></p>
<p>roles <code>{(claims.roles ?? []).join(', ') || 'none'}</code></p>
<p>scope <code>{claims.scope}</code></p>
</section>
)
}
Let Admins Plug In Their Identity Provider
A company admin adds an OpenID Connect connection owned by the company with createConnection, then picks it as the
company's value of the sign-in flow's enterpriseIdp variable with FlowVariablesForm. Both calls carry the admin's
own token, so Choreo Identity & Access Management applies them to the company the token names:
import { useState } from 'react'
import { FlowVariablesForm, createConnection, useManagementRequestConfig, useThunderID } from '@thunderid/react'
const FIELDS = [
'name',
'clientId',
'clientSecret',
'authorizationEndpoint',
'tokenEndpoint',
'userInfoEndpoint',
'jwksEndpoint',
'issuer',
]
export default function EnterpriseSso({ flowId, ouId, ouName }) {
const { baseUrl } = useThunderID()
const requestConfig = useManagementRequestConfig('connections')
const [isAdding, setIsAdding] = useState(false)
const [error, setError] = useState(null)
const [version, setVersion] = useState(0)
const callbackUrl = `${baseUrl}/gate/callback`
const addConnection = async (event) => {
event.preventDefault()
setError(null)
try {
await createConnection({
...requestConfig,
type: 'oidc',
payload: {
...Object.fromEntries(new FormData(event.currentTarget)),
ouId,
redirectUri: callbackUrl,
scopes: ['openid', 'profile', 'email'],
},
})
setIsAdding(false)
setVersion((current) => current + 1)
} catch (err) {
setError(err.message ?? 'Could not add the identity provider.')
}
}
return (
<section>
<h2>Enterprise SSO</h2>
<p>Callback URL for your identity provider: {callbackUrl}</p>
{isAdding ? (
<form onSubmit={addConnection}>
{error && <p>{error}</p>}
{FIELDS.map((name) => (
<input key={name} name={name} placeholder={name} required />
))}
<button type="submit">Add identity provider</button>
</form>
) : (
<FlowVariablesForm
key={version}
flowId={flowId}
ouId={ouId}
ouName={ouName}
showScopeNotice
title="Enterprise SSO connection"
onCreateConnection={() => setIsAdding(true)}
/>
)}
</section>
)
}
Put It Together
Replace src/App.jsx. <OrganizationUnitSwitcher /> lists the companies the user belongs to and switches the session
to the one picked. Only a token that carries org shows the Enterprise SSO section:
import {
OrganizationUnitSwitcher,
SignInButton,
SignOutButton,
SignedIn,
SignedOut,
useGrantedPermissions,
useThunderID,
} from '@thunderid/react'
import EnterpriseSso from "./components/EnterpriseSso.jsx"
import TokenClaims from "./components/TokenClaims.jsx"
import './App.css'
const resource = import.meta.env.VITE_THUNDERID_RESOURCE
function Workspace() {
const { currentOrganizationUnit, user } = useThunderID()
const { can } = useGrantedPermissions()
const roles = Array.isArray(user?.roles) ? user.roles : []
return (
<>
<h1>{currentOrganizationUnit?.name}</h1>
<p>
Signed in as {user?.username} to <code>{currentOrganizationUnit?.handle}</code>. Your roles here:{' '}
{roles.join(', ') || 'none'}
</p>
<TokenClaims />
{can('org') && (
<EnterpriseSso
flowId={import.meta.env.VITE_THUNDERID_SIGN_IN_FLOW_ID}
ouId={currentOrganizationUnit?.id}
ouName={currentOrganizationUnit?.name}
/>
)}
</>
)
}
export default function App() {
const { currentOrganizationUnit } = useThunderID()
return (
<section id="center">
<SignedOut>
<h1>Sign in to your company</h1>
<p>New here? Choose Register your company on the sign-in page.</p>
<SignInButton>Sign in</SignInButton>
</SignedOut>
<SignedIn>
<OrganizationUnitSwitcher scope="siblings" switchOptions={{ resource }} />
<Workspace key={currentOrganizationUnit?.id} />
<SignOutButton>Sign out</SignOutButton>
</SignedIn>
</section>
)
}
currentOrganizationUnitholds theid,handle, andnameof the company the session signed in to, read from the ID token. Treat it as display data. Your APIs read the organization from the access token they receive.scope="siblings"lists the current company and the other companies beneath the same parent organization unit.- A switch exchanges the device secret at the other company's token endpoint, so the page stays where it is. When the
exchange needs the user, the SDK falls back to a redirect, which is a new sign-in, so
switchOptionsnames the same resource server as the first one. useGrantedPermissionsreads the permissions once per session. KeyingWorkspaceby the company loads them again after a switch.
Run and Try It
Start the development server:
npm run dev
Open http://localhost:5173.
A company with its own accounts.
- Choose Sign in, then Register your company.
- Choose My account belongs to this company.
- Enter an account, then
Northstar Labswith the handlenorthstar.
You land in the app as Northstar Labs' React B2B Admin. The token's ouHandle is northstar.
Its scope carries org, so the Enterprise SSO section shows.
Plug in the company's identity provider.
- In your identity provider, register an OpenID Connect application with the callback URL the app shows.
- In Enterprise SSO, choose Create a connection and enter the application's details.
- Select the connection and save.
- Sign out, choose Sign in with enterprise SSO, and enter
northstar.
Choreo Identity & Access Management sends you to Northstar's identity provider.
A first-time employee joins Northstar as a React B2B Member.
One account across several companies. Someone who works with several companies signs up with an account at the platform level:
- Sign out, choose Sign in, then Register your company.
- Choose I work with several companies.
- Enter an account, then
Initechwith the handleinitech.
The sign-up flow creates the account at the platform level, in the Default organization unit, and creates Initech.
It then associates the account with Initech as its React B2B Admin, so you land in the app signed in to Initech.
Until the sample can invite a platform-level account into another company, create one in the Console and affiliate it with the companies, to try switching between them:
- In the Console, open Users and choose Add user.
- Select the user type React B2B User. It places the account in the Default organization unit.
- Enter a username, such as
react-consultant, an email and a password. Choose Create user. - Open the account and select the Affiliations tab.
- Choose Default and chosen organization units, keep All child organization units, and choose Save.
Saving a change does not make it live. You author in the control plane, and your users sign in on a separate data plane, so a change takes effect in an environment only after you deploy it. Go to Deploy, deploy the latest version to your first environment, then promote it to the next environment when you are ready.
Auto-sync deploys saved changes to your first environment within seconds. Turning it on is your choice, per project. See Deploy a Version, or learn why you deploy and how auto-sync works.
Sign out of the app and sign in with the account. Choreo Identity & Access Management asks which company to sign in to, by handle.
Pick northstar, then pick Initech in the organization menu.
The page switches to Initech without leaving the app or asking for the password.
The account holds no role in either company, so the token's roles is empty.
org with careA company admin's token carries org, which manages everything in their company. Grant it only to people you trust
with the whole company, or route management calls through a backend that holds the permission and checks each call.
See Let Organization Admins Manage Teams.
Need single logout or safer storage for tokens and the device secret?
This quickstart runs entirely in the browser, so the SDK keeps your tokens and the device secret in browser storage, where any script on the page can read them. The device secret is the bigger risk. Until the single sign-on session ends, whoever holds it can get tokens for every company the user belongs to, without the user. The app also can't support single logout: if users sign in to this app and another app through single sign-on, signing out of the other app leaves them signed in here until their tokens stop working. If either matters for your app, pick one of these setups.
Build with Next.js (Recommended)
Still React, with a server side. The Next.js SDK signs users in on the server and receives back-channel logout.
- Tokens in an HttpOnly cookie that scripts cannot read
- Single logout through back-channel logout
Add a Backend for Frontend (BFF) (Can't migrate?)
Keep this React app and add a small server that signs users in and holds the tokens. The refresh token and the device secret stay on the server, and the browser gets an HttpOnly session cookie.
- No rewrite of your React code
- Single logout through the BFF
React and Express BFF sample · How to set up a BFF
What's Next
- Secure B2B SaaS Applications: The organization model behind this quickstart, and each B2B journey in depth.
- See It in a Sample App: Run Wayfinder Enterprise, a full B2B app with team management and travel policies.
Was this page helpful?