TryMellon
Navigation

API Reference

Condensed reference for the public SDK API and types.

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

NameTypeDescription
appIdstring (required)Application ID from the TryMellon dashboard.
publishableKeystring (required)Client ID (safe for the browser). Starts with cli_.
apiBaseUrlstringOverride the API base URL. Default: 'https://api.trymellonauth.com'.
timeoutMsnumberHTTP request timeout (ms). Range 1000–300000. Default: 30000.
maxRetriesnumberRetries for transient errors. Range 0–10. Default: 3.
retryDelayMsnumberDelay between retries (ms). Range 100–10000. Default: 1000.
loggerLoggerCustom logger. Default: console.
sandboxbooleanIf true, register/authenticate return immediately with a fixed token. See Sandbox mode.
sandboxTokenstringCustom token in sandbox mode. Default: the exported SANDBOX_SESSION_TOKEN constant.
enableTelemetrybooleanOpt-in anonymous event tracking. Default: false.

Static methods

MethodReturnsDescription
TryMellon.create(config)Result<TryMellon, TryMellonError>Factory — validates config and returns a client. Preferred over the constructor.
TryMellon.isSupported()booleantrue if the browser supports WebAuthn.

Deprecated: new TryMellon(config) — throws on invalid config instead of returning a Result. Use TryMellon.create(config) instead.

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

NameTypeDescription
externalUserIdstringYour external user identifier. Optional for anonymous registration; backend returns external_user_id in init/validation.
authenticatorType'platform' | 'cross-platform'Authenticator preference.
successUrlstringRedirect URL after success (must be in allowlist).
signalAbortSignalCancel the operation.

RegisterResult

NameTypeDescription
successtrueAlways true on success.
credentialIdstringThe new passkey credential ID.
sessionTokenstringSession token — send to your backend.
userobject{ userId, externalUserId?, email?, metadata? }
redirectUrlstring?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

NameTypeDescription
externalUserIdstringYour external user identifier.
hintstringCredential hint for the browser.
successUrlstringRedirect URL after success.
signalAbortSignalCancel the operation.
mediation'optional' | 'conditional' | 'required'WebAuthn mediation preference.

AuthenticateResult

NameTypeDescription
authenticatedbooleantrue on success.
sessionTokenstringSession token — send to your backend.
userobject{ userId, externalUserId?, email?, metadata? }
signalsobject?{ userVerification?, backupEligible?, backupStatus? }
redirectUrlstring?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

Fields are camelCase in the SDK response. The raw REST API returns snake_case fields nested in a data envelope — see Backend validation for the raw HTTP contract.

NameTypeDescription
validbooleanWhether the session is valid.
userIdstringTryMellon user ID.
externalUserIdstringYour external user ID.
tenantIdstringTenant ID.
appIdstringApplication 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

NameTypeDescription
isPasskeySupportedbooleanWhether the browser supports WebAuthn.
platformAuthenticatorAvailablebooleanWhether 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.

MethodReturnsDescription
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.

MethodReturnsDescription
auth.crossDevice.init()Promise<Result<CrossDeviceInitResult>>Creates a cross-device session. Returns { session_id, qr_url, expires_at, polling_token }.
auth.crossDevice.initRegistration(options?)Promise<Result<...>>Creates a cross-device registration session. options.externalUserId is optional — omit for anonymous registration.
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.

enroll(options)

Enrolls a device or entity using a single-use ticket issued by your backend. Used for the Entity Enrollment (Keys & Padlock) flow.

const result = await client.enroll({ ticketId: 'ticket_xxx' });
if (result.ok) {
  console.log('Session token:', result.value.sessionToken);
}
NameTypeDescription
ticketIdstring (required)Enrollment ticket ID issued by your backend via POST /v1/enrollment/tickets.
signalAbortSignalCancel the operation.

Returns Result<{ sessionToken: string }, TryMellonError>. See Entity Enrollment.

getContextHash()

Returns the context hash bound to the current browser session. This hash ties an enrollment ticket to a specific client context — pass it when issuing a ticket from your backend so replay on a different origin fails.

const contextHash = client.getContextHash();
// Send to your backend when requesting a ticket

Returns string (64-char hex, SHA-256). Persisted in sessionStorage for the duration of the session.

bridge

Bridge flows for QR-based enrollment and authentication from a second device (e.g. mobile scanning a desktop QR).

MethodReturnsDescription
bridge.getContext(sessionId, kind)Promise<Result<BridgeContextResponse>>Gets the bridge session context. kind: 'enrollment' or 'auth'.
bridge.verifyPin(sessionId, pin, kind)Promise<Result<BridgeChallengeResponse>>Verifies the presence PIN and returns WebAuthn options.
bridge.complete(sessionId, options?)Promise<Result<BridgeResult>>Completes the ceremony (enrollment or auth). options.kind is required.
bridge.waitForResult(sessionId, options?)Promise<Result<BridgeStatusSnapshot>>Polls or listens via SSE until the bridge session reaches a terminal state.

See Cross-device auth and Entity Enrollment.

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',
});
NameTypeDescription
externalUserIdstring (required)The external user ID.
otpstring (required)The 6-digit OTP from the recovery email.

Returns Result<RecoverAccountResult, TryMellonError>. See Account Recovery.

version()

Returns the SDK version string.

console.log(client.version()); // e.g. '2.3.6'

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';

Utility exports

Helper functions exported from @trymellon/js:

ExportDescription
ok(value) / err(error)Construct a Result — useful when wrapping TryMellon calls in your own functions.
isTryMellonError(e)Type guard — returns true if e is a TryMellonError.
ConsoleLoggerDefault logger implementation. Pass a custom object matching the Logger interface to suppress or redirect SDK logs.
resolveCredentialName(aaguid)Resolves a human-readable authenticator name from an AAGUID (e.g. 'Touch ID', 'YubiKey 5').
getDeviceName()Returns a human-readable name for the current device/authenticator context.

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>:

NameTypeDescription
result.okbooleantrue if success, false if error.
result.valueTThe success value when result.ok is true.
result.errorEThe error when result.ok is false.

Check result.ok before accessing result.value; use !result.ok and result.error for error handling.

TryMellonError

NameTypeDescription
codeTryMellonErrorCodeError code for programmatic handling.
messagestringHuman-readable error message.
detailsunknown?Additional error context.
isTryMellonErrortrueAlways 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.