Mobile & Web SDKs · v1.0.1

React Native SDK

@quick-auth/react-native-sdk — send and verify an OTP over SMS or WhatsApp, read it automatically on Android and iOS, and confirm the login on your own backend. Headless API or drop-in components; one typed event stream either way.

What you get

  • Send and verify an OTP over SMS or WhatsApp, or let your account’s primary channel decide (auto)
  • Android SMS auto-read through Google Play SMS Retriever — no SMS permission, no prompt
  • Android WhatsApp zero-tap / one-tap auto-read, with nothing to configure in your app
  • iOS OTP autofill through the oneTimeCode keyboard suggestion
  • Optional auto-submit, guarded so one code is never submitted twice
  • OneTap silent re-login on devices that verified before
  • Campaign attribution from the launch link’s qa_clid, consent-gated (DPDP / GDPR)

Requirements

  • React Native 0.72+, React 18+
  • @react-native-async-storage/async-storage 1.17+ (required peer dependency — see below)
  • iOS 12.0+, installed with CocoaPods
  • Android minSdk 21. The SDK brings its own Google Play services dependencies for SMS Retriever.
  • The SDK has native code, so it is autolinked into your app. With Expo, use a development build — Expo Go cannot load it.

Install

npm install @quick-auth/react-native-sdk @react-native-async-storage/async-storage
cd ios && pod install

iOS: run pod install after every install or upgrade; it adds the QuickAuthRnSdk pod. Android: autolinking registers the native module — there is nothing to add to MainApplication and no permission to declare. The SDK’s manifest only adds the receiver and <queries> entries WhatsApp zero-tap needs.

AsyncStorage is required because the SDK stores the OneTap device token in it so silent re-login survives app restarts; init() throws if no storage is available. To use MMKV, Keychain or anything else with async getItem / setItem / removeItem, pass it as storage. For tests, createMemoryStorage() works too (OneTap will not survive a restart).

Initialize

Call QuickAuth.init() once near your app’s entry point, with exactly one way to authenticate. Passing none, or more than one, throws.

OptionCredential in the appBackend neededUse for
publishableKeypk_live_… — safe to shipOnly to confirm loginsMost apps. Recommended.
onTokenExpiryA short-lived session token your backend mintsYes — mints tokensApps 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 and is rate-limited. The SDK sends it as X-QuickAuth-Key, together with your app’s identity — X-QuickAuth-Package on Android, X-QuickAuth-Bundle on iOS. Turn on app restriction for the key in the dashboard and register your package name and bundle id so only your app can use it.

App.tsx
// App.tsx — once, near the entry point
import QuickAuth from '@quick-auth/react-native-sdk'

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

Session token (onTokenExpiry)

Your backend calls POST /v1/sdk/session with your client id and secret and returns the sessionToken (valid 1 hour). The SDK sends it as Authorization: Bearer …, calls onTokenExpiry again about 30 seconds before it expires (one call even when several requests need it), and on a 401 fetches a fresh token and retries once. Pass a token you already have as initialToken to skip the first fetch.

await QuickAuth.init({
  onTokenExpiry: async () => {
    const res = await fetch('https://my-app.com/api/quickauth-token', {
      headers: { Authorization: `Bearer ${myUserToken}` },
    })
    return (await res.json()).sessionToken
  },
  onAuthEvent: handleAuthEvent,
})

Never put your client secret in an app

The SDK also accepts an unsafe option that takes your client id and secret and mints tokens itself. Anything in an app binary can be extracted, and your secret gives full access to your account. Do not use unsafe in a build that leaves your organisation — 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).
storageAsyncStorageWhere the device token and attribution data are kept.
consentfalseInitial attribution consent. A choice saved with consent.set() wins.
apiBaseUrlhttps://api.quickauth.inAPI host.
maxRetries2Retries on network errors, 5xx, 408 and 429, with 1 s, 2 s, 4 s backoff and the same Idempotency-Key.
requestTimeoutMs15000Per-request timeout.
silentfalseHides the SDK’s console warnings.

Handle events

Every outcome arrives on one typed onAuthEvent handler. The async methods resolve when the network call is done; the events are the source of truth for what to render.

typePayloadWhat to do
OTP_SENTsessionId, channel, expiresIn (seconds)Show the OTP input and a countdown.
OTP_AUTO_READcodePrefill the input. Already being verified if autoSubmit is on.
VERIFIEDrequestId, message?Send requestId to your backend and confirm it there. Also fires straight after initiate() for a OneTap login — no code was sent.
OTP_FAILEDmessageWrong code. Let the user try again.
ERRORcode, message, errorCode?, status?The attempt is over. See Errors.
typescript
import QuickAuth, { type AuthEvent } from '@quick-auth/react-native-sdk'

function handleAuthEvent(event: AuthEvent) {
  switch (event.type) {
    case 'OTP_SENT':      return showOtpInput(event.expiresIn)
    case 'OTP_AUTO_READ': return prefill(event.code)
    case 'VERIFIED':      return confirmOnServer(event.requestId)
    case 'OTP_FAILED':    return showError(event.message)
    case 'ERROR':         return showError(event.message)
  }
}

QuickAuth.setAuthEventHandler(handleAuthEvent)

Send, verify, resend

typescript
import QuickAuth, { OtpChannel } from '@quick-auth/react-native-sdk'

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

await QuickAuth.auth.submitOtp('483920')

await QuickAuth.auth.resendOtp()

await QuickAuth.auth.reset()

initiate() throws before any network call if phone is not E.164 with a +; submitOtp() throws if it runs before OTP_SENT or the code is not 4–8 digits. While a code is still valid, resendOtp() gets the same code resent with a longer expiry; it rejects when there is no attempt (including after reset()), so only show a resend button after OTP_SENT.

Why autoSubmit is off by default

Submitting for the user spends one of their attempts, and on the auto channel the same code can arrive twice — by SMS and by WhatsApp. With autoSubmit: true the SDK submits at most once per attempt. If you read codes yourself (a paste handler, say), pass them to QuickAuth.auth.publishAutoReadCode(code) and they go through the same guard.

Errors

A failed call emits ERROR and its promise rejects. A wrong code is not an error — it is OTP_FAILED.

codeMeaning
CLIENT_ERROR4xx — the request was refused. errorCode has the server’s reason, e.g. INVALID_REQUEST, OTP_EXPIRED, MAX_ATTEMPTS_EXCEEDED, INVALID_CLIENT_CREDENTIALS.
RATE_LIMITED429 after the SDK’s retries — too many codes for this number or too many requests on this key.
SERVER_ERROR5xx after the SDK’s retries.
UNKNOWN_ERRORNo HTTP response — offline, timed out, or a token callback that threw.

message includes the server’s own message, e.g. [QuickAuth] HTTP 400: phone: phone must be E.164. Every server errorCode is listed in Error codes. init() throws on a bad configuration — no auth mode, more than one, or no storage.

Confirm on your server

VERIFIED on the device is not proof for your server — 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.

Express
const digits = (s) => String(s ?? '').replace(/\D/g, '')

app.post('/api/login', express.json(), async (req, res) => {
  const { requestId, phone } = req.body
  const r = await fetch('https://api.quickauth.in/v1/auth/verify-code', {
    method: 'POST',
    headers: {
      'Content-Type':    'application/json',
      'X-Client-Id':     process.env.QUICKAUTH_CLIENT_ID,
      'X-Client-Secret': process.env.QUICKAUTH_CLIENT_SECRET,
    },
    body: JSON.stringify({ requestId }),
  })
  const result = await r.json()
  if (!r.ok || !result.success || digits(result.phoneNumber) !== digits(phone)) {
    return res.status(401).json({ ok: false })
  }
  res.json({ ok: true })
})

success is false (with every other field null) when the verification did not succeed. phoneNumber is the number exactly as the SDK sent it, so compare digits. Full details: Confirm a verification.

Drop-in components

Neither component returns an outcome — they call the headless methods, and the result arrives on onAuthEvent like everything else.

import { QuickAuthLoginButton, OtpChannel } from '@quick-auth/react-native-sdk'

<QuickAuthLoginButton
  phone="+919876543210"
  channel={OtpChannel.AUTO}
  text="Continue"
  onInitiated={() => setError(null)}
  onError={(err) => setError(err.message)}
/>

<QuickAuthLoginButton phone="+919876543210" code={code} text="Verify" />

<QuickAuthOtpField/> renders one cell per digit over a hidden TextInput with textContentType="oneTimeCode" (iOS) and autoComplete="sms-otp" (Android). On iOS, keyboard autofill is the only auto-read, so the field passes an autofilled code to the SDK — OTP_AUTO_READ and autoSubmit then work the same on both platforms. Typed codes are not forwarded; pass forwardsAutofillToQuickAuth={false} to opt out. Both components take style props, and the SDK exports its colors, radius, spacing and typography tokens.

Android: app hash and WhatsApp zero-tap

Both Android auto-read paths match on the same 11-character hash of your package name and signing certificate. An OTP SMS must end with it, and a WhatsApp authentication template must list your package name and hash under supported_apps.

typescript
const hash = await QuickAuth.auth.getSmsRetrieverHash()

const all = await QuickAuth.auth.getSmsRetrieverHashes()

Take the hash from the build you ship

A debug build has a different hash from a Play-signed release, and Play App Signing re-signs your upload with Google’s key. Read the release hash from an internal-testing install, not a local build, then add it to your SMS template in the dashboard.

WhatsApp zero-tap needs nothing in your app: initiate() and resendOtp() send WhatsApp the handshake it requires before each request. What is on your side is the template — an approved authentication template with zero-tap enabled. If it is misconfigured the message still arrives, the code just is not filled in, and no error is raised. adb logcat -s QuickAuthWaOtp shows whether the handshake reached WhatsApp.

OneTap

When OneTap is on for your account, a device that has verified before gets VERIFIED straight from initiate(), with no code sent. The SDK stores and sends the device token itself — your event handler is all you need. On sign-out, call QuickAuth.auth.reset({ forgetDevice: true }) so the next login on this device asks for a code.

Consent & attribution

Consent is off by default. Attribution and conversion calls made before consent are queued and sent once consent.set(true) runs; the choice is saved across restarts. Sending and verifying codes always run — they are service actions, not analytics — and carry a deviceInfo block only once consent is granted. Revoking drops the queue and the stored attribution data (not the OneTap token).

typescript
// After your in-app consent dialog:
await QuickAuth.consent.set(true)
QuickAuth.consent.get()
QuickAuth.consent.pendingCount()

const attribution = await QuickAuth.attribution.captureLaunch()

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

The device fingerprint is coarse — a random per-install id, locale, UTC offset and screen size. No IDFA, IDFV, MAC or IMEI.

API reference

typescript
import QuickAuth, {
  OtpChannel, createMemoryStorage, SDK_VERSION,
  QuickAuthLoginButton, QuickAuthOtpField,
} from '@quick-auth/react-native-sdk'

QuickAuth.init({
  publishableKey,
  onTokenExpiry,
  onAuthEvent?, storage?, initialToken?, consent?,
  apiBaseUrl?, maxRetries?, requestTimeoutMs?, silent?,
}): Promise<void>
QuickAuth.isInitialized: boolean
QuickAuth.setAuthEventHandler(handler | null)
QuickAuth.reset(): Promise<void>             // tear down; keeps the device token

QuickAuth.auth.initiate({ phone, channel?, autoSubmit? }): Promise<void>
QuickAuth.auth.submitOtp(code): Promise<void>
QuickAuth.auth.resendOtp(): Promise<void>    // no arguments
QuickAuth.auth.reset({ forgetDevice? }): Promise<void>
QuickAuth.auth.publishAutoReadCode(code): void
QuickAuth.auth.observeOTP((code) => void): { remove() }
QuickAuth.auth.getSmsRetrieverHash(): Promise<string | null>
QuickAuth.auth.getSmsRetrieverHashes(): Promise<string[]>
QuickAuth.auth.startWhatsAppLogin({ businessNumber, message? }): Promise<void>

QuickAuth.whatsapp.open({ businessNumber, message? }): Promise<boolean>
QuickAuth.whatsapp.sendOtpHandshake(): Promise<string | null>
QuickAuth.whatsapp.clearPendingOtp(): Promise<void>
QuickAuth.whatsapp.observeOtp((code) => void): { remove() }

QuickAuth.consent.set(granted): Promise<boolean>
QuickAuth.consent.get(): boolean
QuickAuth.consent.pendingCount(): number

QuickAuth.attribution.captureLaunch(): Promise<AttributionResult>
QuickAuth.attribution.capture(url): Promise<AttributionResult>
QuickAuth.attribution.trackConversion({ event, value?, currency?, metadata? }): Promise<void>
QuickAuth.attribution.qaClid(): Promise<string | null>
QuickAuth.attribution.getLastAttribution(): AttributionResult | null
QuickAuth.attribution.getFingerprint() / getFingerprintHash()

startWhatsAppLogin and whatsapp.open only open a WhatsApp chat with your business number and a prefilled message; they do not verify the user. Under the hood the SDK calls the SDK endpoints.

Source & changelog

Source: github.com/quickauthin/quickauth-sdk-react-native. Package: @quick-auth/react-native-sdk on npm. MIT licensed.

Chat with us