API Reference
Condensed reference for the TryMellon JavaScript SDK public API.
TryMellon
Main entry point. Create a client with your app configuration. Prefer TryMellon.create() so invalid config returns a Result instead of throwing.
import { TryMellon } from '@trymellon/js';
const clientResult = TryMellon.create({
appId: 'YOUR_APP_ID',
publishableKey: 'cli_xxxx',
});
if (!clientResult.ok) throw clientResult.error;
const client = clientResult.value;
TryMellonConfig
| Name | Type | Description |
|---|---|---|
appId | string (required) | Application ID from the TryMellon dashboard. |
publishableKey | string (required) | Client ID (safe for the browser). Starts with cli_. |
apiBaseUrl | string | Override the API base URL. Default: 'https://api.trymellonauth.com'. |
timeoutMs | number | HTTP request timeout (ms). Range 1000–300000. Default: 30000. |
maxRetries | number | Retries for transient errors. Range 0–10. Default: 3. |
retryDelayMs | number | Delay between retries (ms). Range 100–10000. Default: 1000. |
logger | Logger | Custom logger. Default: console. |
sandbox | boolean | If true, register/authenticate return immediately with a fixed token. See Sandbox mode. |
sandboxToken | string | Custom token in sandbox mode. Default: the exported SANDBOX_SESSION_TOKEN constant. |
enableTelemetry | boolean | Opt-in anonymous event tracking. Default: false. |
Static methods
| Method | Returns | Description |
|---|---|---|
TryMellon.create(config) | Result<TryMellon, TryMellonError> | Factory — validates config and returns a client. |
TryMellon.isSupported() | boolean | true if the browser supports WebAuthn. |
register(options?)
Registers a new passkey for the user. Returns a Result with sessionToken on success.
const result = await client.register({ externalUserId: 'user_123' });
RegisterOptions
| Name | Type | Description |
|---|---|---|
externalUserId | string | Your external user identifier. Optional for anonymous registration; backend returns external_user_id in init/validation. |
authenticatorType | 'platform' | 'cross-platform' | Authenticator preference. |
successUrl | string | Redirect URL after success (must be in allowlist). |
signal | AbortSignal | Cancel the operation. |
RegisterResult
| Name | Type | Description |
|---|---|---|
success | true | Always true on success. |
credentialId | string | The new passkey credential ID. |
sessionToken | string | Session token — send to your backend. |
user | object | { userId, externalUserId?, email?, metadata? } |
redirectUrl | string? | Set when successUrl was passed and allowed. |
authenticate(options?)
Authenticates the user with an existing passkey. Returns a Result with sessionToken on success.
const result = await client.authenticate({ externalUserId: 'user_123' });
AuthenticateOptions
| Name | Type | Description |
|---|---|---|
externalUserId | string | Your external user identifier. |
hint | string | Credential hint for the browser. |
successUrl | string | Redirect URL after success. |
signal | AbortSignal | Cancel the operation. |
mediation | 'optional' | 'conditional' | 'required' | WebAuthn mediation preference. |
AuthenticateResult
| Name | Type | Description |
|---|---|---|
authenticated | boolean | true on success. |
sessionToken | string | Session token — send to your backend. |
user | object | { userId, externalUserId?, email?, metadata? } |
signals | object? | { userVerification?, backupEligible?, backupStatus? } |
redirectUrl | string? | Set when successUrl was passed and allowed. |
validateSession(sessionToken)
Client-side check: validates a session token against the API. Returns a Result indicating whether the session is valid. You must pass the token; the SDK does not read cookies. See Session validation.
const result = await client.validateSession(sessionToken);
if (result.ok && result.value.valid) {
// Session is valid
}
SessionValidateResponse
| Name | Type | Description |
|---|---|---|
valid | boolean | Whether the session is valid. |
user_id | string | TryMellon user ID. |
external_user_id | string | Your external user ID. |
tenant_id | string | Tenant ID. |
app_id | string | Application ID. |
getStatus()
Returns the client’s WebAuthn environment status. Use to decide whether to offer passkey or email fallback.
const status = await client.getStatus();
ClientStatus
| Name | Type | Description |
|---|---|---|
isPasskeySupported | boolean | Whether the browser supports WebAuthn. |
platformAuthenticatorAvailable | boolean | Whether a platform authenticator (e.g. Touch ID) is available. |
recommendedFlow | 'passkey' | 'fallback' | Recommended auth flow based on environment. |
on(event, callback)
Subscribe to SDK events (e.g. for loading spinners or analytics). Returns an unsubscribe function.
const unsub = client.on('success', (payload) => {
console.log(payload.operation, payload.token);
});
// later: unsub();
Events: start, success, error, cancelled. See Events & Error handling.
fallback.email
Email OTP fallback when WebAuthn is not available.
| Method | Returns | Description |
|---|---|---|
fallback.email.start({ userId, email }) | Promise<Result<void>> | Sends OTP to the given email. userId is your external user id. |
fallback.email.verify({ userId, code, successUrl? }) | Promise<Result<{ sessionToken, redirectUrl? }>> | Verifies the code and returns a session token. |
See Fallback by email.
auth.crossDevice
Cross-device authentication (QR login). Desktop initiates, mobile approves.
| Method | Returns | Description |
|---|---|---|
auth.crossDevice.init() | Promise<Result<CrossDeviceInitResult>> | Creates a cross-device session. Returns { session_id, qr_url, expires_at, polling_token }. |
auth.crossDevice.initRegistration({ externalUserId }) | Promise<Result<...>> | Creates a cross-device registration session. |
auth.crossDevice.waitForSession(sessionId, signal?, pollingToken?) | Promise<Result<...>> | Polls until the mobile device approves. Returns { status, session_token }. |
auth.crossDevice.getContext(sessionId) | Promise<Result<CrossDeviceContextResult>> | Gets session context (used on the mobile side). |
auth.crossDevice.approve(sessionId) | Promise<Result<...>> | Approves the cross-device session from the mobile device. |
See Cross-device auth.
auth.recoverAccount(options)
Recovers an account using an email OTP and creates a new passkey. Requires server-side initiation first.
const result = await client.auth.recoverAccount({
externalUserId: 'user_123',
otp: '632145',
});
| Name | Type | Description |
|---|---|---|
externalUserId | string (required) | The external user ID. |
otp | string (required) | The 6-digit OTP from the recovery email. |
Returns Result<RecoverAccountResult, TryMellonError>. See Account Recovery.
SANDBOX_SESSION_TOKEN
Exported constant — the fixed token returned in sandbox mode. Use it in your backend to identify sandbox sessions during development.
import { SANDBOX_SESSION_TOKEN } from '@trymellon/js';
Web Components
The SDK ships pre-built Web Components in @trymellon/js/ui. See Web Components for full documentation.
<script type="module">
import '@trymellon/js/ui';
</script>
<trymellon-auth app-id="YOUR_APP_ID" publishable-key="cli_xxxx"></trymellon-auth>
Result type
All async methods that can fail return a Result<T, E>:
| Name | Type | Description |
|---|---|---|
result.ok | boolean | true if success, false if error. |
result.value | T | The success value when result.ok is true. |
result.error | E | The error when result.ok is false. |
Check result.ok before accessing result.value; use !result.ok and result.error for error handling.
TryMellonError
| Name | Type | Description |
|---|---|---|
code | TryMellonErrorCode | Error code for programmatic handling. |
message | string | Human-readable error message. |
details | unknown? | Additional error context. |
isTryMellonError | true | Always true — use for type narrowing. |
Error codes: NOT_SUPPORTED, USER_CANCELLED, PASSKEY_NOT_FOUND, SESSION_EXPIRED, NETWORK_FAILURE, INVALID_ARGUMENT, TIMEOUT, ABORTED, CHALLENGE_MISMATCH, UNKNOWN_ERROR. See Events & Error handling.