DEV Community

Cover image for How to Add WhatsApp OTP Login to a Node.js App (with Automatic Telegram Fallback)
Authly
Authly

Posted on

How to Add WhatsApp OTP Login to a Node.js App (with Automatic Telegram Fallback)

SMS codes fail more often than you'd expect: carrier filtering, slow routes, regional rules. Meanwhile, most of your users already have WhatsApp open all day.

In this tutorial we'll build phone verification in Node.js and Express that sends the code over WhatsApp, falls back to Telegram if WhatsApp can't deliver it, and verifies the code server-side. We'll use the Authly OTP API and its official SDK, and add the protections that production apps need.

What we're building

  • POST /auth/send-otp sends a code to a phone number
  • POST /auth/verify-otp checks the code the user typed
  • WhatsApp first, Telegram as automatic fallback
  • Input validation and rate limiting

Setup

mkdir whatsapp-otp-demo && cd whatsapp-otp-demo
npm init -y
npm install express express-rate-limit authly-otp
Enter fullscreen mode Exit fullscreen mode

Create a free account at authly.space and copy your API key. New accounts get free test credits (7 WhatsApp, 7 Telegram and 100 Email OTPs), so you can test real delivery without a credit card.

Store the key in an environment variable. Never put it in client-side code or commit it to Git:

export AUTHLY_API_KEY="your_api_key_here"
Enter fullscreen mode Exit fullscreen mode

Add "type": "module" to your package.json so we can use import.

The server

Create server.js:

import express from "express";
import rateLimit from "express-rate-limit";
import Authly from "authly-otp";

const app = express();
app.use(express.json());

const authly = new Authly(process.env.AUTHLY_API_KEY);

// E.164 phone format: + followed by 8-15 digits
const E164 = /^\+[1-9]\d{7,14}$/;

// Limit send requests per IP: 5 per 15 minutes
const sendLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5,
  standardHeaders: true,
  legacyHeaders: false,
});

// Limit verify attempts per IP: 20 per 15 minutes
const verifyLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 20,
  standardHeaders: true,
  legacyHeaders: false,
});

app.post("/auth/send-otp", sendLimiter, async (req, res) => {
  const { phone } = req.body;

  if (!phone || !E164.test(phone)) {
    return res.status(400).json({ error: "Enter a valid phone number, e.g. +14155552671" });
  }

  try {
    const { otpId } = await authly.otp.send({
      to: phone,
      channel: "whatsapp",
      fallbackChannel: "telegram",
      lang: "en",
    });

    // Send the otpId to the client so it can submit it with the code
    res.json({ otpId });
  } catch (err) {
    console.error("OTP send failed:", err.message);
    res.status(502).json({ error: "Could not send the code. Please try again." });
  }
});

app.post("/auth/verify-otp", verifyLimiter, async (req, res) => {
  const { otpId, code } = req.body;

  if (!otpId || !/^\d{4,8}$/.test(String(code))) {
    return res.status(400).json({ error: "Invalid request" });
  }

  try {
    const result = await authly.otp.verify({ otpId, code: String(code) });

    if (!result.verified) {
      return res.status(400).json({ error: "Invalid or expired code" });
    }

    // The phone number is verified. Create the user's session here.
    res.json({ verified: true });
  } catch (err) {
    console.error("OTP verify failed:", err.message);
    res.status(400).json({ error: "Invalid or expired code" });
  }
});

app.listen(3000, () => console.log("Server running on http://localhost:3000"));
Enter fullscreen mode Exit fullscreen mode

How it works

  1. The user enters a phone number. Your server validates the format and calls authly.otp.send() with channel: "whatsapp".
  2. If WhatsApp can't deliver the message, Authly retries on fallbackChannel: "telegram", so you don't have to write retry logic.
  3. You get back an otpId. The client sends it back with the code the user entered.
  4. authly.otp.verify() checks the code, and you create the session only when verified is true.

Test it

Start the server:

node server.js
Enter fullscreen mode Exit fullscreen mode

Request a code:

curl -X POST http://localhost:3000/auth/send-otp \
  -H "Content-Type: application/json" \
  -d '{"phone":"+14155552671"}'
Enter fullscreen mode Exit fullscreen mode

You'll receive the code on WhatsApp, and the response contains an otpId. Then verify it:

curl -X POST http://localhost:3000/auth/verify-otp \
  -H "Content-Type: application/json" \
  -d '{"otpId":"PASTE_OTP_ID","code":"123456"}'
Enter fullscreen mode Exit fullscreen mode

Security checklist for production

  • Keep the API key on the server only. Never call the OTP API directly from browser or mobile code.
  • Validate phone numbers (E.164) before sending, so you don't pay for junk requests.
  • Rate limit by IP, and also by phone number (for example with Redis) so one number can't be spammed from many IPs.
  • Restrict countries to the ones you actually serve, to reduce SMS pumping and similar fraud.
  • Use generic error messages, so attackers learn nothing from failures.
  • Create the session only after verified is true, and don't trust a verified flag from the client.
  • Log failures per country and channel, so you spot delivery problems early.
  • Set a spend limit or alert on your account so abuse can't produce a surprise bill.

Why use WhatsApp with a fallback?

  • Reach: in many markets people check WhatsApp before SMS.
  • Cost: WhatsApp OTP rates start at $0.008 in India, and Telegram OTP is a flat $0.015. Check the pricing page for your countries.
  • Resilience: a second channel means one failed route doesn't become a lost signup.

Next steps

  • Add email as a third channel for users without WhatsApp or Telegram
  • Store the verified phone number against the user record
  • Add a 60-second resend cooldown in your UI
  • Read the full API docs and the SDK page

I'm the maker of Authly. If you try this tutorial and hit a problem, or want another framework covered (Next.js, Laravel, Django, Flutter), tell me in the comments.

Top comments (0)