@tekkna/hyrox-api-react
v2.0.0
Published
HYROX user API operations and OAuth sessions for React frontends
Readme
HYROX API for React
Typed HYROX user operations and OAuth sessions for React frontends.
The package signs the user in, keeps their access token fresh, and gives your components one typed method per HYROX user operation. Every response is checked against the public contract before your code sees it. It holds no secrets and makes no authorization decisions; the HYROX API checks the user and client on every request.
- React:
^18.3.1or^19.0.0(peer dependency) - Runtime: browser, ES modules, TypeScript declarations included
- Sign-in: OAuth 2.0 Authorization Code + PKCE, via
oidc-client-ts
Availability. HYROX enables the user API per environment and sends you its configuration values when it is ready. Until then you can install the package and build against its types, but requests will not succeed.
Install
npm install @tekkna/hyrox-api-reactQuick start
Create the session and client once, at app start, outside any component:
import {
createHyroxClient,
createHyroxSession,
HyroxApiProvider,
useHyroxSession,
useOwnProfile,
} from '@tekkna/hyrox-api-react'
// `config` holds the values HYROX gave you for this environment.
const session = createHyroxSession({
authority: config.issuer,
clientId: config.clientId,
resource: config.resource,
scope: config.scope,
metadata: config.metadata,
redirectUri: 'https://app.example.com/callback',
postLogoutRedirectUri: 'https://app.example.com/logout',
})
const client = createHyroxClient({ apiBaseUrl: config.apiBaseUrl, session })
export function App() {
return (
<HyroxApiProvider client={client}>
<Profile />
</HyroxApiProvider>
)
}
function Profile() {
const { status, signIn } = useHyroxSession()
const { data, loading, error, refetch } = useOwnProfile()
if (status === 'unauthenticated' || status === 'error')
return <button onClick={() => void signIn()}>Sign in</button>
if (loading) return <p>Loading…</p>
if (error) return <button onClick={refetch}>Try again</button>
return <p>Hello {data?.data.firstName}</p>
}Every other operation is a method on the client. In components, get it with
useHyroxApi(), for example useHyroxApi().users.getOwnConnections().
Configuration
HYROX provides these values per environment. Never mix values from two environments.
| Setting | Value from HYROX |
| ------------ | -------------------------------------------------------------------------------------------------------- |
| authority | Issuer URL |
| clientId | Public client ID (there is no client secret) |
| resource | Exact API audience. It is not derived from any other value. |
| scope | Space-separated scopes, including openid |
| metadata | Complete provider metadata: issuer and every endpoint, including logout. When set, discovery is skipped. |
| apiBaseUrl | API origin plus optional stage path; the client adds v2/users/me |
For Cognito resource-bound login, each custom scope must belong to the exact
resource URL: the user scope is ${resource}/self. The public apiBaseUrl can
differ from that resource. A friendly-name scope paired with a different URL
resource fails before login with invalid_target; use HYROX's corrected matching
configuration rather than removing the resource or scope.
redirectUri and postLogoutRedirectUri must match the URLs registered with
HYROX. All URLs must use https: (http: only for localhost, 127.0.0.1 and
[::1]) and contain no credentials, query or fragment. Invalid settings throw a HyroxSessionError with
code invalid_configuration.
createHyroxClientalso acceptstimeoutMs(1–120000, default 15000) and a customfetch.- To reuse an existing
oidc-client-tsUserManager, usecreateHyroxSessionFromUserManager(manager). Itsresourcemust be set before sign-in, and the adapter then owns token refresh. Do not run your own silent renew.
Short scopes and environment selection
Pass the OAuth settings HYROX supplied for each enabled environment. The helper adds the requested short custom scopes to that environment's configured base scope list and removes duplicates.
import {
createHyroxSession,
resolveHyroxOAuthSettings,
} from '@tekkna/hyrox-api-react'
import type {
HyroxOAuthEnvironment,
HyroxOAuthSettings,
} from '@tekkna/hyrox-api-react'
const environments: Partial<Record<HyroxOAuthEnvironment, HyroxOAuthSettings>> =
{
sandbox: sandboxOAuth,
staging: stagingOAuth,
production: productionOAuth,
}
const oauth = resolveHyroxOAuthSettings({
environment: selectedEnvironment,
environments,
scopes: ['entity.manage', 'data.read', 'staff.manage', 'legal.manage'],
})
const session = createHyroxSession(oauth)Use the selected environment's API base URL for the API client. Keep the same
environment when handling the OAuth callback. When switching environments,
dispose the old session and create a session and API client for the new one.
Omit any environment HYROX hasn't configured yet. Selecting it throws
HyroxSessionError with code invalid_configuration. Request only the scopes
enabled for that environment's OAuth client.
Sign-in and registration
signIn()redirects to the provider's login page.- On your callback page, call
session.completeSignIn(window.location.href). - Call
client.users.completeOwnRegistration()before showing user pages. Enter the app whendata.statusis'succeeded'. Otherwise show the returned progress (pending,running,failedorunknown);retryablesays whether a deliberate retry can help.
await session.completeSignIn(window.location.href)
window.history.replaceState({}, document.title, window.location.pathname)
const { data: registration } = await client.users.completeOwnRegistration()First and last names are optional at sign-up. If the sign-in account has none,
registration rejects with 409 registration_profile_incomplete. Collect both
names in your onboarding and call it again with them:
await client.users.completeOwnRegistration({
profile: { firstName: 'Ada', lastName: 'Lovelace' },
})Both names are required, at most 200 characters, with no leading or trailing
spaces. They only fill a new profile and never overwrite an existing one; later
changes go through updateOwnPersonalProfile.
Operations
Paths are relative to /v2/users/me (/ is /v2/users/me itself) and act on
the signed-in user only. Every method also accepts an optional signal.
| Method | HTTP | Needs |
| ------------------------------------------------- | ------------------------------------------- | --------- |
| Registration | | |
| completeOwnRegistration(options?) | POST /registration | |
| getOwnRegistration() | GET /registration | |
| Profile | | |
| getOwnProfile() | GET / | |
| getOwnProfileReferences() | GET /references | |
| updateOwnPersonalProfile(input, write) | PUT /personal-profile | ETag, key |
| getOwnUserOperation(operationId) | GET /operations/{operationId} | |
| updateOwnCoachProfile(input, write) | PUT /coach-profile | ETag, key |
| updateOwnCoachImage(input, write) | PUT /coach-image | ETag, key |
| Connections, rights and Academy | | |
| getOwnConnections(query?) | GET /connections | |
| getOwnProductAccess(query) | GET /product-access | |
| getOwnEffectiveAccess() | GET /effective-access | |
| getOwnAcademyAccess() | GET /academy-access | |
| getOwnAcademyProgress() | GET /academy-progress | |
| getOwnAcademyContinuation() | GET /academy-continuation | |
| Invitations | | |
| getOwnInvitation(invitationId) | GET /invitations/{invitationId} | |
| getOwnInvitationOffer(invitationId) | GET /invitations/{invitationId}/offer | |
| acceptOwnInvitation(invitationId, input, write) | POST /invitations/{invitationId}/accept | ETag, key |
| getOwnInvitationAcceptance(operationId) | GET /invitation-acceptances/{operationId} | |
| declineOwnInvitation(invitationId, write) | POST /invitations/{invitationId}/decline | key |
| getOwnInvitationDecline(operationId) | GET /invitation-declines/{operationId} | |
| Account deletion | | |
| requestOwnDeletionChallenge(write) | POST /deletion-challenges | key |
| getOwnDeletionChallenge(challengeId) | GET /deletion-challenges/{challengeId} | |
| requestOwnDeletion(input, write) | POST /deletions | key |
| getOwnDeletion(operationId) | GET /deletions/{operationId} | |
The package also exports a static product catalogue (productCatalogue,
productComponents, ProductKind) that needs no request.
Rules every operation follows
- Results are
{ data, requestId, etag }. QuoterequestIdto support. - Reads refresh the token once and retry once after a
401. - Writes are never retried automatically. Input is validated locally before anything is sent.
- Edits send the
versionandetagfrom a fresh read. A read withetag: nullcannot be used for an edit.412 version_mismatchmeans read again and let the user review. - Idempotency keys: every write except registration takes one. Create one
per user action (
crypto.randomUUID()). After a timeout or any error withretryable: true, repeat the same call with the same input, ETag and key to recover. A new key means a new action. - Long-running work returns an operation with
statusandsteps. Onlysucceededmeans done. Status reads only observe; repeat the original write with its original key to resume. - Pages: pass
data.cursorback unchanged until it isnull. On400 invalid_cursor, start again. nullmeans unknown, never "no".- Cancellation: pass a
signal. Timeouts (default 15 s) reject with aDOMExceptionnamedTimeoutError. A sign-out or account switch during a request rejects withHyroxSessionErrorcodesession_changed.
Errors
HyroxApiErrorhasstatus(0for network errors), a stablecode,requestId,retryable(truefor429,5xxand network errors) anddetails(field-levelValidationDetail[]for caller validation and missing preconditions). Displaymessageas text and usecodefor programmatic handling or localization. Gateway errors with an unknown code arrive asrequest_failedwith a generic message.HyroxSessionErrorhascode:authentication_required,session_unavailable,session_changedorinvalid_configuration. It also provides a message suitable for display.
Session and security
- Only the access token is sent to the API. ID and refresh tokens never are, and hooks never expose tokens.
- Sessions from
createHyroxSessionare stored insessionStorage(one browser tab). The package refreshes the access token shortly before it expires, using the refresh token (no iframes). All requests share one refresh. - If sign-in fails or the provider is temporarily unreachable, the session
statusis'error'. Offer sign-in again. After recovery, one request may reject withsession_changed; just repeat it. signIn()andsignOut()reject withsession_unavailablewhen the provider cannot be reached.signOut()still clears local data in that case.- Importing the package is SSR-safe, but sessions and clients exist only in the
browser. Render
HyroxApiProvideron the client only, and never share a session or client between users.
Sandbox
Sign-in, data storage and validation are real. Partner systems (linked account setup, Academy, partner callbacks, inviter messages) are simulated, and test gyms have to be configured by HYROX. Deletion codes go as real emails to the user's verified login email, and a completed account deletion really disables that sandbox login. Use dedicated test accounts.
Versioning
1.0.0 is the first stable release. From there the package follows semantic
versioning: new operations and new optional response fields are minor
versions; any enum change (for example a new status or error code), new
required inputs, removed fields, narrowed inputs or changed meaning are major
versions; documentation and packaging fixes are patches. Each version depends on one exact @tekkna/public-api-contracts
version.
Coach-profile additions in 1.2.0
Global self-declared certifications use country: null; national entries use an
uppercase two-letter code. familiarity accepts Not familiar, Somewhat familiar,
Experienced, Expert; employmentType accepts self-employed, employed.
Both fields are nullable on reads. On updates, omission preserves the baseline
value and explicit null clears it. Original replacement keys remain required.
Upgrade strict 1.1.x readers before the new API response is activated.
Coach images use client.users.updateOwnCoachImage(...) with the current profile
version, ETag and an idempotency key. The API performs storage server-side; the
browser client is not granted direct S3/bucket credentials. JPEG/PNG only.
