Implement WhatsApp OTP Verification in Node.js
Any statistics or percentages in this article are general industry figures or illustrations, not QuackAPI measurements or promises. Results depend on your audience, consent and sending patterns. QuackAPI connects to WhatsApp as a linked device (an unofficial method), so read our risk and acceptable use policy before sending.
Why WhatsApp OTP?
WhatsApp OTP verification offers higher delivery rates than SMS-based OTP, reaching 95%+ globally. Users are more likely to see and act on WhatsApp messages quickly, reducing verification drop-off rates.
WhatsApp OTP is also more cost-effective than SMS OTP for international users. With QuackAPI, you can send OTP messages at a flat subscription rate rather than paying per-message carrier fees.
Generating Secure OTP Codes
Use cryptographically secure random number generation for OTP codes. Never use Math.random() as it is not cryptographically secure. The crypto module in Node.js provides the randomInt function for generating secure random integers.
const crypto = require("crypto");
function generateOTP(length = 6) {
const min = Math.pow(10, length - 1);
const max = Math.pow(10, length) - 1;
return crypto.randomInt(min, max).toString();
}
// Generate a 6-digit OTP
const otp = generateOTP();
console.log(otp); // e.g., "847293"Sending OTP via QuackAPI API
Once you have generated the OTP code, send it to the user via the QuackAPI messaging API. Format the message clearly so users can easily identify and copy the verification code.
const axios = require("axios");
async function sendOTP(phoneNumber, otpCode) {
const message = `Your verification code is: ${otpCode}\n\nThis code expires in 5 minutes. Do not share this code with anyone.`;
const response = await axios.post(
"https://quackapi.com/v1/messages/send",
{
deviceId: 1,
to: phoneNumber,
content: message,
type: "text"
},
{
headers: {
"Content-Type": "application/json",
"x-api-key": process.env.QUACKAPI_API_KEY
}
}
);
return response.data;
}Storing and Verifying Codes
Store OTP codes with their associated phone number, creation timestamp, and attempt count. Use an in-memory store like Redis for fast lookups, or a database if you need persistence. Hash the OTP before storing for added security.
const otpStore = new Map();
function storeOTP(phoneNumber, otpCode) {
otpStore.set(phoneNumber, {
code: otpCode,
createdAt: Date.now(),
attempts: 0,
maxAttempts: 3
});
}
function verifyOTP(phoneNumber, inputCode) {
const stored = otpStore.get(phoneNumber);
if (!stored) {
return { valid: false, error: "No OTP found for this number" };
}
stored.attempts += 1;
if (stored.attempts > stored.maxAttempts) {
otpStore.delete(phoneNumber);
return { valid: false, error: "Maximum attempts exceeded" };
}
if (stored.code === inputCode) {
otpStore.delete(phoneNumber);
return { valid: true };
}
return { valid: false, error: "Invalid code" };
}Handling Code Expiry
OTP codes should expire after a short time window, typically 5 to 10 minutes. Check the creation timestamp against the current time during verification. Implement automatic cleanup to prevent stale entries from accumulating in your store.
const OTP_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes
function verifyOTPWithExpiry(phoneNumber, inputCode) {
const stored = otpStore.get(phoneNumber);
if (!stored) {
return { valid: false, error: "No OTP found" };
}
if (Date.now() - stored.createdAt > OTP_EXPIRY_MS) {
otpStore.delete(phoneNumber);
return { valid: false, error: "OTP has expired" };
}
return verifyOTP(phoneNumber, inputCode);
}
// Cleanup expired OTPs every minute
setInterval(() => {
const now = Date.now();
for (const [phone, data] of otpStore.entries()) {
if (now - data.createdAt > OTP_EXPIRY_MS) {
otpStore.delete(phone);
}
}
}, 60000);Complete Express API
Here is a complete Express.js API with endpoints for requesting and verifying OTPs. This example ties together all the previous sections into a production-ready service.
const express = require("express");
const app = express();
app.use(express.json());
app.post("/api/otp/request", async (req, res) => {
const { phoneNumber } = req.body;
if (!phoneNumber) {
return res.status(400).json({ error: "Phone number required" });
}
const otp = generateOTP();
storeOTP(phoneNumber, otp);
try {
await sendOTP(phoneNumber, otp);
res.json({ success: true, message: "OTP sent via WhatsApp" });
} catch (error) {
res.status(500).json({ error: "Failed to send OTP" });
}
});
app.post("/api/otp/verify", (req, res) => {
const { phoneNumber, code } = req.body;
const result = verifyOTPWithExpiry(phoneNumber, code);
if (result.valid) {
res.json({ success: true, message: "Phone number verified" });
} else {
res.status(400).json({ success: false, error: result.error });
}
});
app.listen(3000);