Web SDK API Reference
Complete API reference for Hawcx Web SDK
Web SDK API Reference
Factory
createHawcxClient(config)
Creates a Hawcx client instance.
import { createHawcxClient } from '@hawcx/core';
const client = createHawcxClient({
configId: 'your_config_id',
apiBase: 'https://your-tenant.hawcx.com/v1'
});Config:
| Property | Type | Required | Description |
|---|---|---|---|
configId | string | Yes | Your Hawcx Config ID |
apiBase | string | Yes | Your tenant API URL |
Returns: HawcxClient
State Machine
The client maintains a FlowState that drives your UI. Subscribe to changes:
client.onStateChange((state) => {
// Render UI based on state.status
});
// Or get current state
const state = client.getState();Flow States
| Status | Shape | Description |
|---|---|---|
idle | { status: 'idle' } | Ready to start |
loading | { status: 'loading' } | Processing request |
prompt | { status: 'prompt', prompt: Prompt } | Server needs user input |
completed | { status: 'completed', authCode, codeVerifier, expiresAt } | Auth successful |
error | { status: 'error', error: FlowError } | Something failed |
Completed State
interface FlowStateCompleted {
status: 'completed';
authCode: string; // Send to backend
codeVerifier: string; // Send to backend (PKCE)
expiresAt: string; // ISO timestamp
}FlowError
interface FlowError {
code: string; // Error code
message: string; // Human-readable message
category: FlowErrorCategory; // Recovery hint
details?: Record<string, unknown>;
}
type FlowErrorCategory = 'retryable' | 'user_action' | 'fatal';| Category | Meaning | Recovery |
|---|---|---|
retryable | Transient error (network, rate limit) | Retry the same action |
user_action | User error (wrong code, invalid input) | Show error, let user retry |
fatal | Unrecoverable (session expired) | Call reset() and start over |
Prompts
When state.status === 'prompt', the server is asking for user input.
select_method
User chooses an authentication method.
interface SelectMethodPrompt {
type: 'select_method';
methods: Array<{
name: string; // Method ID to pass to selectMethod()
label: string; // Display label
}>;
}Action: Call selectMethod(method.name)
enter_code
User enters an OTP code sent via email or SMS.
interface EnterCodePrompt {
type: 'enter_code';
destination: string; // Masked email/phone
codeLength: number; // Expected code length
}Action: Call submitCode(code)
enter_totp
User enters a code from their authenticator app.
interface EnterTotpPrompt {
type: 'enter_totp';
}Action: Call submitTotp(code)
setup_totp
User sets up TOTP for the first time.
interface SetupTotpPrompt {
type: 'setup_totp';
secret: string; // Manual entry key
otpauthUrl: string; // QR code URL
}UI: Show QR code from otpauthUrl, display secret for manual entry.
Action: Call submitTotp(code) after user enters code from authenticator app.
setup_sms
User enrolls their phone number.
interface SetupSmsPrompt {
type: 'setup_sms';
}Action: Call submitPhone(phoneNumber)
await_approval
Waiting for external approval (QR scan, push notification).
interface AwaitApprovalPrompt {
type: 'await_approval';
qrData?: string; // QR code data (if applicable)
}UI: Show QR code if qrData provided, otherwise show "Waiting for approval..."
Action: None — SDK polls automatically and transitions when approved.
redirect
Redirect to external OAuth provider.
interface RedirectPrompt {
type: 'redirect';
url: string;
}Action: window.location.href = prompt.url
Methods
start(identifier, flowType?)
Begin an authentication flow.
client.start('[email protected]');| Parameter | Type | Description |
|---|---|---|
identifier | string | User email |
flowType | 'signup' | 'account_manage' | Optional flow override |
If flowType is omitted, the SDK will try login first and fall back to signup if the user does not exist.
selectMethod(methodId)
Select an authentication method after select_method prompt.
client.selectMethod('email_otp');| Parameter | Type | Description |
|---|---|---|
methodId | string | Method name from prompt |
submitCode(code)
Submit OTP code after enter_code prompt.
client.submitCode('123456');| Parameter | Type | Description |
|---|---|---|
code | string | OTP code |
submitTotp(code)
Submit TOTP code after enter_totp or setup_totp prompt.
client.submitTotp('123456');| Parameter | Type | Description |
|---|---|---|
code | string | Authenticator code |
submitPhone(phoneNumber)
Submit phone number after setup_sms prompt.
client.submitPhone('+15551234567');| Parameter | Type | Description |
|---|---|---|
phoneNumber | string | Phone number (E.164 format) |
resend()
Resend OTP code. Valid after enter_code prompt.
client.resend();reset()
Clear state and return to idle. Use to start over or recover from fatal errors.
client.reset();cancel()
Cancel the current flow.
client.cancel();getState()
Get the current flow state.
const state = client.getState();onStateChange(callback)
Subscribe to state changes.
const unsubscribe = client.onStateChange((state) => {
console.log('State changed:', state.status);
});
// Later: unsubscribe();React Hooks
HawcxProvider
Wrap your app to provide the client context.
import { HawcxProvider } from '@hawcx/react';
<HawcxProvider config={{ configId: '...', apiBase: '...' }}>
<App />
</HawcxProvider>useFlowState()
Get the current flow state. Re-renders on state changes.
const state = useFlowState();useFlowActions()
Get action methods.
const {
start,
selectMethod,
submitCode,
submitTotp,
submitPhone,
resend,
reset,
cancel
} = useFlowActions();useFlowClient()
Get the underlying client instance.
const client = useFlowClient();Backend API
HawcxOAuth
Exchange authorization codes for verified user claims.
import { HawcxOAuth } from '@hawcx/oauth-client';
const oauth = new HawcxOAuth({
configId: process.env.HAWCX_API_KEY!,
baseUrl: process.env.HAWCX_BASE_URL // optional
});Config:
| Property | Type | Required | Description |
|---|---|---|---|
configId | string | Yes | Your Hawcx Config ID (public identifier) |
baseUrl | string | No | Hawcx base URL |
from hawcx_oauth_client import HawcxOAuth
import os
oauth = HawcxOAuth(
config_id=os.getenv('HAWCX_API_KEY'),
base_url=os.getenv('HAWCX_BASE_URL') # optional
)exchangeCode(authCode, codeVerifier)
Exchange authorization code for verified claims.
const { idToken, claims } = await oauth.exchangeCode(authCode, codeVerifier);
// claims.sub = user ID
// claims.email = verified emailresult = oauth.exchange_code(auth_code, code_verifier)
# result.claims['sub'] = user ID
# result.claims['email'] = verified emailReturns:
| Property | Type | Description |
|---|---|---|
idToken | string | Raw JWT (don't use as access token) |
claims | object | Verified claims (sub, email, etc.) |
Error Types
import { TokenExchangeError, TokenVerificationError } from '@hawcx/oauth-client';
try {
const { claims } = await oauth.exchangeCode(authCode, codeVerifier);
} catch (error) {
if (error instanceof TokenExchangeError) {
// Code exchange failed (invalid/expired code)
console.error(error.message, error.statusCode);
}
if (error instanceof TokenVerificationError) {
// JWT verification failed
console.error(error.message);
}
}| Error | When | Recovery |
|---|---|---|
TokenExchangeError | Code invalid, expired, or already used | Ask user to re-authenticate |
TokenVerificationError | JWT signature/claims failed | Log incident, re-authenticate |
Flow Types
Most apps can omit the flow type — start(email) auto-detects new vs returning users.
| Type | When to Use |
|---|---|
signup | New user registration |
account_manage | Step-up auth for sensitive actions |