💬 WhatsApp API @ Best Rate | Zero Setup Fee → 99.9% Uptime OTP Delivery — Try FREE Demo! 🏆 10,000+ Registered Businesses — 2,000+ Enterprise Clients Served 🚀 API Integration in Under 5 Minutes 🏅 Verified Business Badge with RCS Messaging 💬 WhatsApp API @ Best Rate | Zero Setup Fee → 99.9% Uptime OTP Delivery — Try FREE Demo! 🏆 10,000+ Registered Businesses — 2,000+ Enterprise Clients Served 🚀 API Integration in Under 5 Minutes 🏅 Verified Business Badge with RCS Messaging
Talk to Sales: India 1800 102 1822
OTP

OTP SMS API with Node.js and React: Express Backend + React OTP Login Screen

SMSGatewayHub 5 views
Quick answer

To add an OTP SMS API to a Node.js and React app, keep all SMS calls on the server. Your Express backend generates a code with crypto.randomInt, stores only its hash with a 5-minute expiry, and sends it with one fetch call to the SMSGatewayHub SendSMS endpoint (channel=OTP, API key, DLT entity ID and template ID). React only shows the phone and OTP screens and posts to your own /api/otp/send and /api/otp/verify routes. OTP SMS costs ₹0.185 to ₹0.245 per SMS + GST, with 2-6 second typical delivery.

Key takeaways

  • Never call the SMS API from React: anything in the browser bundle, including your API key, is public.
  • Express does the work: generate, hash, send, verify and rate-limit on the server.
  • React does the screen: a 6-box OTP input with paste support, a resend timer and autocomplete="one-time-code" for autofill.
  • One use, short life: the code expires in 5 minutes and is deleted after success or 5 wrong tries.
  • Cost and speed: ₹0.185 to ₹0.245 per OTP SMS, 2-6 seconds typical delivery.

Our step-by-step Node.js OTP guide covers the single API call. This article builds the full stack: an Express backend you can drop into a real project and a React login screen your users will actually find easy.

Why must React never call the OTP SMS API directly?

A React app runs in the user's browser. Every environment variable you bundle into it, every request it makes and every header it sends can be read in the browser's developer tools. If React called the SMS API with your key, anyone could copy the key and send SMS on your balance, or flood your users with codes.

JobReact (browser)Express (server)
Collect phone number and codeYes-
Generate the OTPNeverYes
Hold the API keyNeverYes, in an environment variable
Call SendSMSNeverYes
Check the codeNeverYes, against the stored hash
Rate limitingShow the timer onlyEnforce it

What do you need before you start?

  • An SMSGatewayHub account and API key (sign-up gives 1,000 free SMS credits, no credit card).
  • A DLT entity ID, a transactional sender ID and an approved OTP template. Our team helps with DLT registration and the template process.
  • Node.js 18 or later (built-in fetch), Express, express-rate-limit and a store such as Redis.

How do you build the Express backend for send and verify OTP?

Install the packages:

npm install express express-rate-limit redis

Then the send helper. The text must match your approved DLT template exactly; only the code changes.

// sms.js
const SMS_URL = 'https://www.smsgatewayhub.com/api/mt/SendSMS';

async function sendOtpSms(number, otp) {
  const params = new URLSearchParams({
    APIKey: process.env.SGH_API_KEY,
    senderid: process.env.SGH_SENDER_ID,      // e.g. ABCDEF
    channel: 'OTP',
    DCS: '0',
    flashsms: '0',
    number,                                   // 91 + 10 digits
    text: `${otp} is your OTP to log in to ABC App. Do not share it. - ABC`,
    route: '1',
    EntityId: process.env.SGH_ENTITY_ID,
    dlttemplateid: process.env.SGH_OTP_TEMPLATE_ID,
  });
  const res = await fetch(`${SMS_URL}?${params}`, { signal: AbortSignal.timeout(10000) });
  const data = await res.json();
  // data.ErrorCode === '000' means accepted; keep data.JobId for the delivery report
  console.log('otp', number.slice(-4), data.ErrorCode, data.JobId);
  return data;
}

module.exports = { sendOtpSms };

A successful reply:

{ "ErrorCode": "000", "ErrorMessage": "Success", "JobId": "20047",
  "MessageData": [ { "Number": "9198XXXXXXXX", "MessageId": "..." } ] }

Now the routes. Codes are stored as an HMAC with a secret pepper, compared in constant time and deleted after one use.

// otp-routes.js
const express = require('express');
const crypto = require('crypto');
const rateLimit = require('express-rate-limit');
const { createClient } = require('redis');
const { sendOtpSms } = require('./sms');

const router = express.Router();
const redis = createClient({ url: process.env.REDIS_URL });
redis.connect();

const PEPPER = process.env.OTP_PEPPER;   // long random secret
const TTL = 300, GAP = 45, MAX_TRIES = 5;
const hash = (n, c) => crypto.createHmac('sha256', PEPPER).update(`${n}:${c}`).digest('hex');

// per-IP limit on the send route (tune to your traffic)
const sendLimiter = rateLimit({ windowMs: 60 * 60 * 1000, limit: 10,
  standardHeaders: true, legacyHeaders: false });

router.post('/send', sendLimiter, async (req, res) => {
  const number = String(req.body.number || '');
  if (!/^91[6-9]\d{9}$/.test(number)) return res.status(400).json({ ok: false, error: 'Invalid number' });

  // resend cooldown: SET NX succeeds only if no gap key exists
  const free = await redis.set(`otp:gap:${number}`, '1', { NX: true, EX: GAP });
  if (!free) return res.status(429).json({ ok: false, error: 'Please wait before resending' });

  const otp = String(crypto.randomInt(100000, 1000000));
  await redis.set(`otp:h:${number}`, hash(number, otp), { EX: TTL });
  await redis.del(`otp:t:${number}`);

  try {
    const data = await sendOtpSms(number, otp);
    if (data.ErrorCode !== '000') return res.status(502).json({ ok: false, error: 'Could not send the code' });
    res.json({ ok: true, expiresIn: TTL, resendIn: GAP });
  } catch (e) {
    res.status(502).json({ ok: false, error: 'SMS service not reachable, try again' });
  }
});

router.post('/verify', async (req, res) => {
  const number = String(req.body.number || ''), code = String(req.body.otp || '');
  const stored = await redis.get(`otp:h:${number}`);
  if (!stored) return res.status(400).json({ ok: false, error: 'Code expired' });

  const tries = await redis.incr(`otp:t:${number}`);
  await redis.expire(`otp:t:${number}`, TTL);
  if (tries > MAX_TRIES) { await redis.del(`otp:h:${number}`); return res.status(429).json({ ok: false, error: 'Too many attempts' }); }

  const a = Buffer.from(stored), b = Buffer.from(hash(number, code));
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return res.status(400).json({ ok: false, error: 'Wrong code' });

  await redis.del(`otp:h:${number}`, `otp:t:${number}`);   // one use only
  // create the session / JWT here
  res.json({ ok: true });
});

module.exports = router;

Mount it with app.use(express.json()); app.use('/api/otp', require('./otp-routes'));. If you prefer bcrypt for the stored code, it works too; HMAC with a pepper is faster and equally safe for short-lived codes because the pepper never leaves the server.

ℹ️
Do not retry the SMS call in a loop on a failed reply. SMSGatewayHub already applies automatic retry with load balancing across operator routes. Let the user tap resend after the cooldown instead.

How do you build the React OTP login screen?

A good OTP screen does four things: six separate boxes, paste of the whole code into any box, a visible resend timer, and browser autofill. The component below does all four and talks only to your Express routes.

// OtpLogin.jsx
import { useEffect, useRef, useState } from 'react';

export default function OtpLogin() {
  const [number, setNumber] = useState('');
  const [step, setStep] = useState('phone');
  const [digits, setDigits] = useState(Array(6).fill(''));
  const [wait, setWait] = useState(0);
  const [msg, setMsg] = useState('');
  const boxes = useRef([]);

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

  async function post(url, body) {
    const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body) });
    return r.json();
  }

  async function send() {
    setMsg('');
    const d = await post('/api/otp/send', { number: '91' + number });
    if (!d.ok) return setMsg(d.error);
    setStep('code'); setWait(d.resendIn || 45); setDigits(Array(6).fill(''));
    setTimeout(() => boxes.current[0]?.focus(), 0);
  }

  function setAt(i, v) {
    const clean = v.replace(/\D/g, '');
    if (clean.length > 1) {                      // pasted or autofilled full code
      const next = clean.slice(0, 6).split('');
      setDigits([...next, ...Array(6 - next.length).fill('')]);
      boxes.current[Math.min(next.length, 5)]?.focus();
      return;
    }
    const next = [...digits]; next[i] = clean; setDigits(next);
    if (clean && i < 5) boxes.current[i + 1]?.focus();
  }

  async function verify() {
    const d = await post('/api/otp/verify', { number: '91' + number, otp: digits.join('') });
    setMsg(d.ok ? 'Verified' : d.error);
  }

  if (step === 'phone') return (
    <form onSubmit={e => { e.preventDefault(); send(); }}>
      <label htmlFor="ph">Mobile number</label>
      <input id="ph" type="tel" inputMode="numeric" autoComplete="tel-national"
        maxLength={10} value={number} onChange={e => setNumber(e.target.value.replace(/\D/g, ''))} />
      <button type="submit" disabled={number.length !== 10}>Send OTP</button>
      <p role="alert">{msg}</p>
    </form>
  );

  return (
    <form onSubmit={e => { e.preventDefault(); verify(); }}>
      <p>Enter the 6-digit code sent to +91 {number}</p>
      <div style={{ display: 'flex', gap: 8 }}>
        {digits.map((d, i) => (
          <input key={i} ref={el => (boxes.current[i] = el)} value={d}
            inputMode="numeric" autoComplete={i === 0 ? 'one-time-code' : 'off'}
            aria-label={`Digit ${i + 1}`} maxLength={i === 0 ? 6 : 1}
            onChange={e => setAt(i, e.target.value)}
            onKeyDown={e => { if (e.key === 'Backspace' && !d && i > 0) boxes.current[i - 1]?.focus(); }} />
        ))}
      </div>
      <button type="submit" disabled={digits.join('').length !== 6}>Verify</button>
      <button type="button" onClick={send} disabled={wait > 0}>
        {wait > 0 ? `Resend in ${wait}s` : 'Resend OTP'}
      </button>
      <p role="alert">{msg}</p>
    </form>
  );
}

The first box carries autocomplete="one-time-code" (written autoComplete in JSX) and accepts up to six characters, so iOS Safari and Chrome on Android can offer the code from the SMS and fill all six boxes in one tap. The timer reads the server's resendIn value, but the real limit is enforced in Express.

What should the OTP message look like for autofill?

  • Put the code at the start: 482913 is your OTP to log in to ABC App.
  • Use digits only for the code, 4 to 8 long.
  • Keep the rest of the text exactly as registered on DLT; only the {#numeric#} part changes.
  • For web OTP on Android Chrome you can also add the line @yourdomain.com #482913 at the end, but only if that line is part of your approved DLT template.
✔
Users without good SMS reach? Add WhatsApp or voice as a fallback channel, or skip codes entirely with OneTap Verify login links. The resend and fallback logic is covered in our verify and resend OTP guide.

Why use SMSGatewayHub as the OTP SMS API for Node.js?

  • One GET call, JSON reply: native fetch in Node 18+ is all you need. See the developer API docs.
  • 2-6 second typical delivery on priority transactional routes with automatic retry and load balancing across operator routes.
  • ₹0.185 to ₹0.245 per OTP SMS + 18% GST, DLT scrubbing included, pay only for delivered. Full rates on OTP SMS pricing.
  • Free DLT help for entity, sender ID and OTP templates.
  • Since 2009, 99.9% uptime SLA, ISO 27001 certified.
Get 1,000 free SMS credits and wire up your OTP login today
No credit card. Free DLT registration help. Put your API key in an environment variable and run the Express routes above.
Create free account

Frequently asked questions

Can I call the OTP SMS API directly from React?

No. Anything in a React bundle is public, including an API key. Call the SMS API only from your Node.js server and let React post to your own send and verify routes.

How do I generate a secure OTP in Node.js?

Use crypto.randomInt(100000, 1000000) for a 6-digit code. Store only an HMAC or bcrypt hash with a 5-minute expiry and compare with crypto.timingSafeEqual.

How does OTP autofill work in a React app?

Set autocomplete="one-time-code" (autoComplete in JSX) on the OTP input and start the SMS with the code. iOS Safari and Android Chrome can then offer the code from the SMS and fill it in one tap.

How much does an OTP SMS cost?

OTP SMS on SMSGatewayHub costs ₹0.185 to ₹0.245 per SMS plus 18% GST, depending on pack size, with DLT scrubbing included. You pay only for delivered OTPs.

How do I stop OTP abuse on my Node.js API?

Add express-rate-limit on the send route, a 30-60 second resend cooldown per number, a cap of about 3 sends per number per 15 minutes, and burn the code after 5 wrong attempts.

Related reading: OTP SMS API, OTP REST API reference, OTP SMS API in Python, OTP SMS API for Flutter and iOS and testing your OTP API.

Sources: SMSGatewayHub OTP SMS API page and developer API documentation (November 2026); Node.js crypto documentation; express-rate-limit and React documentation; WHATWG HTML autocomplete specification (one-time-code); TRAI Telecom Commercial Communications Customer Preference Regulations for DLT rules. Prices exclude 18% GST and can change; confirm your rate with sales before purchase.