OTP verification in React Native, with SMS autofill and the SMS Retriever API

Written and reviewed by the DiOTP team Published 30 November 2026Last updated 30 November 2026

8 min read

This guide covers OTP verification in React Native from the screen to the server. The app never calls DiOTP directly. It talks to your own backend, which holds the API key. You will build a two-step screen, switch on the code autofill that iOS and Android keyboards already offer, and then look closely at the SMS Retriever API on Android: what it does, what the SMS must contain for it to work, and why that means registering your own DLT template first.

Why the app talks to your backend, not to DiOTP

A mobile app is a file anyone can download and unpack. Strings inside it, including API keys, can be pulled out with free tools in minutes. Obfuscation slows this down but does not stop it. If your DiOTP key shipped in the app, a stranger could use it to send codes to any number and spend your wallet balance.

So the app posts to two routes on your server: one to send a code and one to check it. Only the server knows the key. It also decides which phone number was verified, so a tampered app cannot claim a number it never proved. This is the same split the web guides use, and it means one backend can serve your website and your app.

Do not put the DiOTP key in a .env file bundled with the app, in app config, or in a remote config service that the app downloads. All of these end up on the device.

The quick way: a backend on the official Node.js SDK

The app never calls DiOTP. Your backend does, and the easiest backend uses the official Node.js SDK, installed with npm install @diorbit/diotp. These two routes are all the app needs:

server.js (with diotp)

import express from 'express'
import { DiOTP, DiOTPError, ExpiredError, InvalidCodeError, RateLimitError } from '@diorbit/diotp'

const app = express()
app.use(express.json())
const diotp = new DiOTP() // reads DIOTP_API_KEY

app.post('/api/otp/send', async (req, res) => {
  try {
    const { requestId, expiresAt } = await diotp.send({ to: req.body.phone, purpose: 'login' })
    res.json({ requestId, expiresAt })
  } catch (err) {
    if (err instanceof RateLimitError) return res.status(429).json({ error: err.code })
    if (err instanceof DiOTPError) return res.status(err.status ?? 502).json({ error: err.code })
    throw err
  }
})

app.post('/api/otp/verify', async (req, res) => {
  try {
    await diotp.verify({ requestId: req.body.requestId, code: String(req.body.code) })
    res.json({ verified: true }) // sign the user in here
  } catch (err) {
    if (err instanceof InvalidCodeError || err instanceof ExpiredError) return res.status(400).json({ error: err.code })
    if (err instanceof DiOTPError) return res.status(err.status ?? 502).json({ error: err.code })
    throw err
  }
})

app.listen(3000)

The next section shows the same backend with plain REST calls, if you prefer no dependency.

The backend the app calls

Mobile apps usually sign users in with a token rather than a browser cookie, so this version of the backend returns a request id to the app and keeps its own record of which phone it belongs to. It reuses the sendOtp and verifyOtp helpers from our Node.js OTP verification guide, which also explains the Idempotency-Key, error mapping and per-IP limits in detail.

mobile-routes.js (Express)

import express from "express";
import crypto from "node:crypto";
import { sendOtp, verifyOtp } from "./diotp.js"; // from the Node.js guide

export const mobile = express.Router();
mobile.use(express.json());

// Use Redis or your database in production. A Map is lost on restart.
const pending = new Map(); // requestId -> { phone, expires }

mobile.post("/otp/send", async (req, res) => {
  const phone = String(req.body.phone ?? "").replace(/\D/g, "").slice(-10);
  if (!/^[6-9]\d{9}$/.test(phone)) return res.status(400).json({ error: "invalid_phone" });

  const r = await sendOtp(phone, crypto.randomUUID());
  if (!r.ok) return res.status(r.status).json({ error: r.code });

  pending.set(r.data.request_id, { phone, expires: Date.now() + 5 * 60 * 1000 });
  res.json({ requestId: r.data.request_id });
});

mobile.post("/otp/verify", async (req, res) => {
  const { requestId, code } = req.body ?? {};
  const entry = pending.get(requestId);
  if (!entry || entry.expires < Date.now()) return res.status(410).json({ error: "expired" });

  const r = await verifyOtp(requestId, String(code ?? ""));
  if (!r.ok) return res.status(r.status).json({ error: r.code });

  pending.delete(requestId);
  const token = await issueToken(entry.phone); // your own auth: JWT, session table, etc.
  res.json({ verified: true, token });
});

async function issueToken(phone) {
  // Replace with your real sign-in. This placeholder only shows the shape.
  return crypto.createHash("sha256").update(phone + crypto.randomUUID()).digest("hex");
}

Mount it with app.use("/api/mobile", mobile) on the server from the Node.js guide. The phone number is taken from the server's own record, never from the app at verify time. The verify OTP reference lists every error the route can pass back.

A React Native OTP screen

The screen has a phone step and a code step, a 30-second resend timer to match DiOTP's resend cooldown, and the two props that turn on keyboard autofill. Replace BASE_URL with your server's address. On a real phone, localhost points at the phone itself, so use your computer's network address or a deployed test server.

OtpScreen.tsx

import { useEffect, useRef, useState } from "react";
import { Button, Text, TextInput, View } from "react-native";

const BASE_URL = "https://api.example.com/api/mobile";

const MESSAGES: Record<string, string> = {
  invalid_phone: "Enter a 10-digit mobile number.",
  invalid_code: "That code is not right. Try again.",
  expired: "This code has expired. Send a new one.",
  too_many_attempts: "Too many wrong tries. Send a new code.",
  resend_cooldown: "Please wait 30 seconds before asking again.",
  phone_hourly_limit: "Too many codes for this number. Try again later.",
  phone_daily_limit: "Too many codes for this number today.",
  trial_restricted: "Test mode only sends to your own verified number.",
};

async function post(path: string, body: object) {
  try {
    const res = await fetch(BASE_URL + path, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    return { ok: res.ok, data: await res.json().catch(() => ({})) };
  } catch {
    return { ok: false, data: { error: "network" } };
  }
}

export default function OtpScreen({ onSignedIn }: { onSignedIn: (token: string) => void }) {
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [requestId, setRequestId] = useState<string | null>(null);
  const [wait, setWait] = useState(0);
  const [error, setError] = useState("");
  const codeInput = useRef<TextInput>(null);

  useEffect(() => {
    if (wait <= 0) return;
    const t = setTimeout(() => setWait((w) => w - 1), 1000);
    return () => clearTimeout(t);
  }, [wait]);

  async function send() {
    setError("");
    const { ok, data } = await post("/otp/send", { phone });
    if (!ok) return setError(MESSAGES[data.error] ?? "Could not send the code.");
    setRequestId(data.requestId);
    setCode("");
    setWait(30);
    setTimeout(() => codeInput.current?.focus(), 100);
  }

  async function verify(value = code) {
    const { ok, data } = await post("/otp/verify", { requestId, code: value });
    if (ok) return onSignedIn(data.token);
    setError(MESSAGES[data.error] ?? "Could not check the code.");
  }

  if (!requestId) {
    return (
      <View>
        <Text>Mobile number</Text>
        <TextInput
          value={phone}
          onChangeText={setPhone}
          keyboardType="phone-pad"
          textContentType="telephoneNumber"
          autoComplete="tel"
          accessibilityLabel="Mobile number"
        />
        <Button title="Send code" onPress={send} />
        {error ? <Text accessibilityLiveRegion="polite">{error}</Text> : null}
      </View>
    );
  }

  return (
    <View>
      <Text>Enter the code we sent to {phone}</Text>
      <TextInput
        ref={codeInput}
        value={code}
        onChangeText={(t) => {
          const digits = t.replace(/\D/g, "");
          setCode(digits);
          if (digits.length === 6) verify(digits);
        }}
        keyboardType="number-pad"
        textContentType="oneTimeCode"
        autoComplete="sms-otp"
        maxLength={6}
        accessibilityLabel="Verification code"
      />
      <Button title="Verify" onPress={() => verify()} disabled={code.length < 4} />
      <Button
        title={wait > 0 ? `Resend in ${wait}s` : "Resend code"}
        onPress={send}
        disabled={wait > 0}
      />
      {error ? <Text accessibilityLiveRegion="polite">{error}</Text> : null}
    </View>
  );
}

Store the token the backend returns in secure storage, such as the iOS Keychain or Android Keystore through a library you trust, not in plain AsyncStorage. The screen submits automatically when six digits arrive. If your codes use a different length, change the check and maxLength to match.

Keyboard autofill on iOS and Android

This route works today, with DiOTP's shared template, and needs no extra library. Both systems can spot a code in an incoming SMS and offer it above the keyboard. The user taps it once and the field fills.

  • iOS: textContentType="oneTimeCode" on the TextInput tells the system this field wants a one-time code. When an SMS with a code arrives, iOS shows it in the suggestion bar.
  • Android: autoComplete="sms-otp" gives the same hint to Android's autofill service. Whether a suggestion appears depends on the device, the keyboard and the Android version, so treat it as a helpful extra, not a guarantee.
  • Keep keyboardType="number-pad" in both cases, so users who type the code by hand get the right keys.

Autofill never reads the message without the user. They still tap the suggestion, and nothing needs SMS permission. For most apps this is enough, and it is where we suggest you start.

How the SMS Retriever API on Android works

The SMS Retriever API is part of Google Play services. It lets an Android app receive one specific SMS without asking for the READ_SMS permission, which Google Play restricts heavily. The flow looks like this:

  1. Your app asks Play services to start listening, just before it requests a code.
  2. Play services waits for up to 5 minutes for a matching message.
  3. A message matches only if it contains your app's 11-character hash. Google's earlier documentation said the hash must end the message, so putting it at the end is the safe choice.
  4. When a matching SMS arrives, the full text is handed to your app. Your code pulls the digits out and can submit them with no tap at all.
  5. If nothing matches within 5 minutes, the listener times out and the user can still type the code.

The hash is an 11-character string computed from your app's package name and its signing certificate. That has practical effects. A debug build and a release build are signed differently, so they have different hashes. If Google Play signs your app for you, the release hash comes from Play's certificate, not your upload key. Most libraries can print the hash at runtime, which is the easiest way to get the right value from the build your users install. Google's SMS Retriever API Android documentation has the current rules for the message format.

Why the SMS Retriever API needs your own DLT template

In India every commercial SMS must match a template registered on DLT, word for word apart from the {#var#} parts. DiOTP's default shared template lets you send OTPs the same day without your own registration, but its wording is fixed and shared by many senders. It cannot carry your app's hash, so the SMS Retriever API on Android will not match those messages.

To use it, register your own DLT entity, header and an OTP template that includes the hash as fixed text. For example: "{#var#} is your login code for YourApp. It is valid for 5 minutes. Do not share it. AbCdEfGhIjK", where the last part is your release hash. Once it is approved, add your Entity ID, header and template under Senders in the DiOTP dashboard. Sends then use it with no code change on your server. Our DLT registration guide walks through the steps, and DiOTP offers help with registration for a one-time fee quoted before starting.

Because the hash is fixed text in the template, it must be the hash of the build your users install. If you ever change your signing key, the hash changes and you will need a new template.

SMS Retriever API React Native setup with a community library

React Native does not include the SMS Retriever API, so you need a native module. Community libraries such as react-native-otp-verify wrap it, and several others exist. We do not maintain or endorse any of them. Check the library's documentation for its current API, its supported React Native versions and whether it works with your build setup. The sketch below follows the method names that library documents at the time of writing, and only runs when you have your own template.

useSmsRetriever.ts (Android only)

import { useEffect } from "react";
import { Platform } from "react-native";
import OtpVerify from "react-native-otp-verify";

// Turn this on only after your own DLT template with the app hash is live.
const USE_SMS_RETRIEVER = false;

export function useSmsRetriever(active: boolean, onCode: (code: string) => void) {
  useEffect(() => {
    if (!USE_SMS_RETRIEVER || !active || Platform.OS !== "android") return;
    OtpVerify.getOtp()
      .then(() =>
        OtpVerify.addListener((message: string) => {
          const match = /\b(\d{4,8})\b/.exec(message ?? "");
          if (match) onCode(match[1]);
        })
      )
      .catch(() => {
        // Play services unavailable: the user types or autofills the code instead.
      });
    return () => OtpVerify.removeListener();
  }, [active, onCode]);
}

// During setup, log the hash from a release-signed build:
// OtpVerify.getHash().then((hashes: string[]) => console.log(hashes));

Start listening just before you call your send route, so the 5-minute window covers the message. In OtpScreen, call the hook with active set to whether a request is pending, and pass a callback that fills the code and calls verify. Keep the autofill props on the TextInput as well, since the listener can time out and iOS has no equivalent of this API.

Testing your OTP verification React Native screen

New DiOTP accounts start in test mode with free test messages, which go only to the mobile number verified at sign-up. Install the app on that phone and test there. Sending to another number returns trial_restricted, which also proves your error messages appear.

  • Check the iOS suggestion bar shows the code when the SMS arrives.
  • Check the Android autofill suggestion on more than one keyboard if you can.
  • Tap resend early and confirm the timer and resend_cooldown message.
  • Turn on airplane mode and confirm the network error is handled.

Building the web side too? The React and Next.js OTP guide shares this flow. The full API reference is in the DiOTP docs.

API documentation Node.js backend guide

Questions people ask

Keep the DiOTP key on your server. The app posts the number and code to your own routes, and those routes call DiOTP. Anything bundled in the app can be extracted.

Start building your customer messaging with DiOTP

Free test credits on sign-up, API keys in a minute, and a team that picks up the phone.