Most OTP tutorials stop at “generate a random number and send it.” That works in a demo and fails in production, where attackers guess codes, spam your endpoint, and run up your messaging bill.
In this tutorial we’ll build a small OTP service in Node.js and Express that handles the parts tutorials skip: secure code generation, hashing, expiry, attempt limits and rate limiting.
What we’re building
Two endpoints:
-
POST /otp/sendgenerates a code and delivers it -
POST /otp/verifychecks the code the user entered
And these protections:
- Cryptographically secure code generation
- Codes stored as hashes, never in plain text
- Short expiry and single use
- A maximum number of verification attempts
- Rate limiting on sending
Setup
mkdir otp-demo && cd otp-demo
npm init -y
npm install express express-rate-limit
Create server.js. We’ll build it in pieces.
1. Generate a secure code
Don’t use Math.random(). It isn’t designed for security. Use Node’s crypto module:
const crypto = require("crypto");
function generateCode() {
// 6-digit code, uniformly random, padded with leading zeros
return crypto.randomInt(0, 1_000_000).toString().padStart(6, "0");
}
2. Store a hash, not the code
If your store leaks, plain-text codes can be used immediately. Store an HMAC instead:
const OTP_SECRET = process.env.OTP_SECRET || "change-me-in-production";
function hashCode(identifier, code) {
return crypto
.createHmac("sha256", OTP_SECRET)
.update(`${identifier}:${code}`)
.digest("hex");
}
Including the identifier (phone number or email) in the hash ties a code to one user.
3. Send with expiry and limits
For this demo we’ll use an in-memory Map. In production use Redis (or another shared store with TTL support) so it works across servers and restarts.
const express = require("express");
const rateLimit = require("express-rate-limit");
const app = express();
app.use(express.json());
const CODE_TTL_MS = 5 * 60 * 1000; // 5 minutes
const MAX_ATTEMPTS = 5;
const store = new Map(); // identifier -> { hash, expiresAt, attempts }
const sendLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 send requests per IP per window
standardHeaders: true,
legacyHeaders: false,
});
// Replace this with your real delivery method (see the last section)
async function deliverCode(channel, to, code) {
console.log(`[DEMO] Sending ${code} to ${to} via ${channel}`);
}
app.post("https://dev.to/otp/send", sendLimiter, async (req, res) => {
const { to, channel = "email" } = req.body;
if (!to) return res.status(400).json({ error: "Missing 'to'" });
// Per-identifier cooldown: block repeat sends within 60 seconds
const existing = store.get(to);
if (existing && existing.sentAt && Date.now() - existing.sentAt < 60_000) {
return res.status(429).json({ error: "Please wait before requesting a new code" });
}
const code = generateCode();
store.set(to, {
hash: hashCode(to, code),
expiresAt: Date.now() + CODE_TTL_MS,
attempts: 0,
sentAt: Date.now(),
});
await deliverCode(channel, to, code);
// Don't return the code, and keep the response generic
res.json({ message: "If the details are valid, a code has been sent" });
});
Two details matter here:
- The per-IP limiter stops one client from flooding you.
- The per-identifier cooldown stops someone from spamming a single victim’s phone number from many IPs.
4. Verify safely
app.post("https://dev.to/otp/verify", (req, res) => {
const { to, code } = req.body;
if (!to || !code) return res.status(400).json({ error: "Missing fields" });
const record = store.get(to);
if (!record) return res.status(400).json({ error: "Invalid or expired code" });
// Expired
if (Date.now() > record.expiresAt) {
store.delete(to);
return res.status(400).json({ error: "Invalid or expired code" });
}
// Too many attempts
if (record.attempts >= MAX_ATTEMPTS) {
store.delete(to);
return res.status(429).json({ error: "Too many attempts. Request a new code." });
}
record.attempts += 1;
// Constant-time comparison
const expected = Buffer.from(record.hash, "hex");
const actual = Buffer.from(hashCode(to, String(code)), "hex");
const valid =
expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
if (!valid) return res.status(400).json({ error: "Invalid or expired code" });
store.delete(to); // single use
res.json({ verified: true });
});
app.listen(3000, () => console.log("OTP server running on :3000"));
Notes:
- All failures return the same generic message, so attackers learn nothing.
-
timingSafeEqualavoids timing leaks in the comparison. - The record is deleted after success, so a code works only once.
5. Test it
node server.js
In another terminal:
curl -X POST http://localhost:3000/otp/send
-H "Content-Type: application/json"
-d '{"to":"user@example.com","channel":"email"}'
Copy the code from the server console, then verify:
curl -X POST http://localhost:3000/otp/verify
-H "Content-Type: application/json"
-d '{"to":"user@example.com","code":"123456"}'
Production checklist
- Move storage to Redis with a TTL, using atomic operations for the attempt counter
- Keep
OTP_SECRETin an environment variable or secrets manager - Add per-day spend caps and alerts so fraud can’t drain your budget
- Restrict countries you don’t serve
- Require HTTPS everywhere
- Log delivery and failure events by country and channel
- Consider offering more than one channel, because delivery is the least reliable part
The delivery part
You’ll notice deliverCode() is just a stub. Everything above is about generating and checking codes safely. Actually getting the code to the user, over WhatsApp, Telegram, email or SMS, with fallback when a channel fails, is a separate problem.
You can wire up each provider yourself. If you’d rather use one API for it, that’s what I’m building with Authly: OTP delivery over WhatsApp, Telegram and Email with automatic failover. The docs show how to send and verify codes. Check them to see whether it fits your stack.
Summary
A secure OTP flow needs:
- Secure random generation
- Hashed storage
- Short expiry and single use
- Attempt limits
- Rate limits per IP and per identifier
- Generic error messages
What would you add to this? Let me know in the comments, and I’ll cover it in a follow-up.