Mobile & Web SDKs · v1.0.1

Web SDK

@quick-auth/web-sdk — send and verify a phone OTP over SMS or WhatsApp from any website, read the code automatically on Android Chrome, and confirm the login on your own backend. Headless: you bring the UI, the SDK sends every outcome to one typed event handler. Zero runtime dependencies; ESM, CommonJS and a script-tag build.

Install

npm install @quick-auth/web-sdk

With a bundler, import the named export: import { QuickAuth } from '@quick-auth/web-sdk'. The script-tag build defines a global window.QuickAuth with the same API. Pin the version in the URL, as above, so a new release never changes your page without you.

Initialize

Call QuickAuth.init() once when your page loads, with exactly one way to authenticate. Passing none, or combining publishableKey with another mode, throws straight away.

OptionWhat ships in the pageBackend neededUse for
publishableKeypk_live_… — safe to shipOnly to confirm loginsMost sites. Recommended.
onTokenExpiryA short-lived session token your backend mintsYes — mints tokensSites that want to decide per user who may request a code

Publishable key (recommended)

Copy the key from the dashboard (Settings → Publishable key). It only allows the SDK’s own calls — send and verify a code, attribution — and is rate-limited (300 requests an hour from browsers). The SDK sends it as an X-QuickAuth-Key header. To stop other sites using your key, turn on app restriction for it in the dashboard and register your website’s origin.

import { QuickAuth } from '@quick-auth/web-sdk'

QuickAuth.init({
  publishableKey: 'pk_live_…',
  onAuthEvent: handleAuthEvent,
})

Session token (onTokenExpiry)

Your backend calls POST /v1/sdk/session with your client id and secret and passes the sessionToken (valid 1 hour) to the page. The SDK sends it as Authorization: Bearer …, calls onTokenExpiry again when fewer than 30 seconds remain, and on a 401 fetches a fresh token and retries once. If you already have a token when the page renders, pass it as initialToken too.

import { QuickAuth } from '@quick-auth/web-sdk'

QuickAuth.init({
  onTokenExpiry: async () =>
    (await fetch('/api/quickauth-token').then((r) => r.json())).sessionToken,
  onAuthEvent: handleAuthEvent,
})

Never put your client secret in a web page

The SDK also accepts an unsafe option that takes your client id and secret and mints tokens itself. Anyone can read a secret out of a JavaScript bundle and use your account with it. Do not use unsafe in anything that runs in a browser — use publishableKey or onTokenExpiry.

Other options

OptionDefaultWhat it does
onAuthEvent—Receives every auth event. Attach or replace it later with QuickAuth.setAuthEventHandler(fn) (null detaches).
consentfalseInitial attribution consent. A choice saved with consent.set() wins on later page loads.
apiBaseUrlhttps://api.quickauth.inAPI host.
maxRetries3Retries on 5xx, network errors and timeouts, with exponential backoff and the same Idempotency-Key.
requestTimeoutMs15000Per-request timeout, including reading the body. 0 disables it.
storagePrefixqa_Prefix for the SDK’s localStorage keys.
debugfalseLogs requests, responses, retries and events to the console with codes and secrets masked. Leave it off in production.
silentfalseHides the SDK’s own console warnings and errors.
fetchglobal fetchCustom fetch implementation (tests, SSR).

Handle events

Every outcome arrives on onAuthEvent. The methods’ promises resolve when the network call is done; render from the events, not from return values.

typePayloadWhat to do
OTP_SENTsessionId, channel, expiresIn (seconds)Show the code input and a countdown.
OTP_AUTO_READcodePrefill the input. Already being verified if you passed autoSubmit: true.
VERIFIEDrequestId, message?Send requestId to your backend and confirm it there.
OTP_FAILEDmessageWrong code. The attempt stays open — let the user try again.
ERRORcode, message, errorCode?, status?, retryAfter?, requestId?The attempt is over. See Errors.
javascript
function handleAuthEvent(event) {
  switch (event.type) {
    case 'OTP_SENT':      showOtpInput(event.expiresIn); break
    case 'OTP_AUTO_READ': prefill(event.code); break
    case 'VERIFIED':      confirmOnServer(event.requestId); break
    case 'OTP_FAILED':    showError(event.message); break
    case 'ERROR':         showError(event.message); break
  }
}

Send a code

phone must be in E.164 format with a leading +, such as +919876543210 — no spaces or dashes. The SDK throws before any network call if it is not. channel is 'auto' (default — your dashboard’s primary channel), 'sms' or 'whatsapp'.

javascript
await QuickAuth.auth.initiate({
  phone:      '+919876543210',
  channel:    'auto',
  autoSubmit: true,
})

If initiate() is called again before the first finishes, the latest call wins and the older one’s late responses are ignored.

Verify the code

javascript
// After OTP_SENT, with what the user typed (4–8 digits).
await QuickAuth.auth.submitOtp('123456')

submitOtp() throws if it is called before OTP_SENT or with something that is not 4–8 digits. Your account allows 3 wrong codes per attempt by default; after that the attempt ends with an ERROR and you need a new initiate().

Resend

javascript
await QuickAuth.auth.resendOtp()

resendOtp() repeats the current attempt — same number, same channel, same autoSubmit. It deliberately takes no phone number, so a re-typed number cannot start a second attempt. While the code is still valid, QuickAuth resends the same code and extends its expiry. It rejects when there is no attempt, so only show a resend button after OTP_SENT.

To abandon an attempt (the user edits their number, say), call QuickAuth.auth.reset().

SMS auto-read (WebOTP)

initiate() arms the browser’s WebOTP API for you. On Android Chrome, Edge and Samsung Internet the browser offers the code from the SMS, the SDK emits OTP_AUTO_READ, and with autoSubmit: true verifies it — at most once per attempt.

The SMS must end with your domain and the code

Browsers ignore an SMS without a last line like @shop.example.com #123456 — your page’s host, then the code. Set this up in your OTP SMS template. WebOTP also needs HTTPS (or localhost).

Safari, Firefox and desktop browsers have no WebOTP. There, give your input autocomplete="one-time-code" so the keyboard offers the code, and call submitOtp() from your input handler. observeOTP sets those attributes on your input and passes codes to a callback; publishAutoReadCode feeds in a code from anywhere else (a paste handler, say) as if it had been auto-read.

javascript
const stop = QuickAuth.auth.observeOTP({
  input:  '#otp',
  onCode: (code) => { document.querySelector('#otp').value = code },
})

QuickAuth.auth.publishAutoReadCode('123456')

Errors

A failed call emits ERROR and its promise rejects with a QuickAuthError (exported, and on QuickAuth.QuickAuthError) that carries the same fields. A wrong code is not an error — it is OTP_FAILED.

codeMeaningRetried by the SDK
CLIENT_ERROR4xx — the request was refused. errorCode says why, e.g. INVALID_REQUEST, OTP_EXPIRED, MAX_ATTEMPTS_EXCEEDED, INVALID_CLIENT_CREDENTIALS.No
RATE_LIMITED429 — too many codes for this number, or too many requests on this key. Wait before trying again.No
SERVER_ERROR5xx, or a response that was not from the QuickAuth API (errorCode: 'INVALID_RESPONSE' — a Wi-Fi login page or a wrong apiBaseUrl).5xx yes; INVALID_RESPONSE no
NETWORK_ERROROffline, DNS failure, or the connection dropped.Yes
TIMEOUTNo complete response within requestTimeoutMs.Yes
TOKEN_ERRORonTokenExpiry threw or returned nothing.No
UNKNOWN_ERRORAnything else.No
javascript
// Example ERROR event
{
  type:      'ERROR',
  code:      'CLIENT_ERROR',
  message:   '[QuickAuth] HTTP 400: phone: phone must be E.164',
  errorCode: 'INVALID_REQUEST',
  status:    400,
  requestId: '9b2f0c7e…',
}

The requestId on an error identifies the HTTP request for support; it is not the verification’s requestId from VERIFIED. Every server errorCode is listed in Error codes.

Confirm on your server

VERIFIED in the browser is not proof for your backend — anyone can call your API with a made-up result. Send the event’s requestId to your backend, and have your backend call POST /v1/auth/verify-code with your client id and secret before it creates a session. QuickAuth only verifies the number; your backend owns the user and the session.

async function confirmOnServer(requestId) {
  const r = await fetch('/api/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ requestId, phone: '+919876543210' }),
  })
  if (r.ok) location.assign('/home')
}

OneTap

OneTap silent re-login is for mobile apps. QuickAuth does not apply it to requests from a browser, so on the web initiate() always sends a code. QuickAuth.auth.reset({ forgetDevice: true }) still clears any device token the SDK has stored — call it on sign-out.

Consent & attribution

Attribution calls and the deviceInfo audit block are gated by consent, which is off by default. Calls made before consent are queued and sent when it is granted; revoking drops the queue and the stored click id. Sending and verifying codes never wait for consent.

javascript
// After the user accepts your privacy notice:
await QuickAuth.consent.set(true)
QuickAuth.consent.get()
QuickAuth.consent.pendingCount()
const off = QuickAuth.consent.onChange((granted) => { /* … */ })

const r = await QuickAuth.attribution.captureLaunch()

await QuickAuth.attribution.trackConversion({
  event: 'signup', value: 0, currency: 'INR', metadata: { plan: 'free' },
})

QuickAuth.attribution.qaClid()
QuickAuth.attribution.getStored()

API reference

MemberDescription
QuickAuth.init(options)Configure the SDK. Throws on invalid options; returns a promise that never rejects.
QuickAuth.isInitializedWhether init() has run.
QuickAuth.versionThe SDK version, e.g. 1.0.1.
QuickAuth.setAuthEventHandler(fn | null)Attach or replace the event handler after init().
QuickAuth.reset()Tear the whole SDK down; call init() again afterwards.
auth.initiate({ phone, channel?, autoSubmit? })Send a code. Emits OTP_SENT or ERROR.
auth.submitOtp(code)Verify a code. Emits VERIFIED, OTP_FAILED or ERROR.
auth.resendOtp()Resend for the current attempt. No arguments.
auth.reset({ forgetDevice? })End the attempt; forgetDevice also clears the stored device token.
auth.observeOTP({ onCode, input?, onError?, signal? })Codes in a callback and input attributes set for autofill. Returns an unsubscribe function.
auth.publishAutoReadCode(code)Feed in a code as if it had been auto-read.
auth.startWhatsAppLogin({ businessNumber, message?, returnUrl? }) / whatsapp.open(…)Navigate to a wa.me chat with your business number and a prefilled message. This only opens the chat — it does not verify the user.
consent.set / get / onChange / pendingCountConsent gate for attribution.
attribution.captureLaunch / trackConversion / qaClid / getStoredCampaign attribution and conversions.
QuickAuth.tokenManagergetToken() / invalidate() for the session-token cache.

TypeScript types ship with the package: AuthEvent, InitOptions, InitiateOptions, OTPChannel, QuickAuthErrorCode, AttributionResult and more. Under the hood the SDK calls the SDK endpoints.

Browser support

BrowserSend / verifyWebOTP auto-read
Chrome, Edge, Samsung Internet (Android)YesYes
Safari (iOS)YesKeyboard suggestion via autocomplete="one-time-code"
FirefoxYesKeyboard suggestion only
Desktop Chrome / EdgeYesNo

Source & changelog

Source: github.com/quickauthin/quickauth-sdk-web. Package: @quick-auth/web-sdk on npm. The changelog ships in the package as CHANGELOG.md. MIT licensed.

Chat with us