TryMellon

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.
TryMellon.isSupported()booleantrue 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

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

NameTypeDescription
validbooleanWhether the session is valid.
user_idstringTryMellon user ID.
external_user_idstringYour external user ID.
tenant_idstringTenant ID.
app_idstringApplication 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({ 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',
});
NameTypeDescription
externalUserIdstring (required)The external user ID.
otpstring (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>:

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.