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-sdkWith 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.
| Option | What ships in the page | Backend needed | Use for |
|---|---|---|---|
publishableKey | pk_live_… — safe to ship | Only to confirm logins | Most sites. Recommended. |
onTokenExpiry | A short-lived session token your backend mints | Yes — mints tokens | Sites 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
| Option | Default | What it does |
|---|---|---|
onAuthEvent | — | Receives every auth event. Attach or replace it later with QuickAuth.setAuthEventHandler(fn) (null detaches). |
consent | false | Initial attribution consent. A choice saved with consent.set() wins on later page loads. |
apiBaseUrl | https://api.quickauth.in | API host. |
maxRetries | 3 | Retries on 5xx, network errors and timeouts, with exponential backoff and the same Idempotency-Key. |
requestTimeoutMs | 15000 | Per-request timeout, including reading the body. 0 disables it. |
storagePrefix | qa_ | Prefix for the SDK’s localStorage keys. |
debug | false | Logs requests, responses, retries and events to the console with codes and secrets masked. Leave it off in production. |
silent | false | Hides the SDK’s own console warnings and errors. |
fetch | global fetch | Custom 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.
type | Payload | What to do |
|---|---|---|
OTP_SENT | sessionId, channel, expiresIn (seconds) | Show the code input and a countdown. |
OTP_AUTO_READ | code | Prefill the input. Already being verified if you passed autoSubmit: true. |
VERIFIED | requestId, message? | Send requestId to your backend and confirm it there. |
OTP_FAILED | message | Wrong code. The attempt stays open — let the user try again. |
ERROR | code, message, errorCode?, status?, retryAfter?, requestId? | The attempt is over. See Errors. |
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'.
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
// 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
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.
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.
code | Meaning | Retried by the SDK |
|---|---|---|
CLIENT_ERROR | 4xx — the request was refused. errorCode says why, e.g. INVALID_REQUEST, OTP_EXPIRED, MAX_ATTEMPTS_EXCEEDED, INVALID_CLIENT_CREDENTIALS. | No |
RATE_LIMITED | 429 — too many codes for this number, or too many requests on this key. Wait before trying again. | No |
SERVER_ERROR | 5xx, 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_ERROR | Offline, DNS failure, or the connection dropped. | Yes |
TIMEOUT | No complete response within requestTimeoutMs. | Yes |
TOKEN_ERROR | onTokenExpiry threw or returned nothing. | No |
UNKNOWN_ERROR | Anything else. | No |
// 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.
// 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
| Member | Description |
|---|---|
QuickAuth.init(options) | Configure the SDK. Throws on invalid options; returns a promise that never rejects. |
QuickAuth.isInitialized | Whether init() has run. |
QuickAuth.version | The 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 / pendingCount | Consent gate for attribution. |
attribution.captureLaunch / trackConversion / qaClid / getStored | Campaign attribution and conversions. |
QuickAuth.tokenManager | getToken() / 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
| Browser | Send / verify | WebOTP auto-read |
|---|---|---|
| Chrome, Edge, Samsung Internet (Android) | Yes | Yes |
| Safari (iOS) | Yes | Keyboard suggestion via autocomplete="one-time-code" |
| Firefox | Yes | Keyboard suggestion only |
| Desktop Chrome / Edge | Yes | No |
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.