This tutorial builds a custom one-time password system in Node.js using Twilio SMS that gives you full control over code generation, storage, expiry, and verification logic without delegating those concerns entirely to the Twilio Verify API. It targets developers who need custom OTP behaviour such as a specific code format, a non-standard expiry window, or integration with an existing session store. You will generate a cryptographically secure code using Node's built-in crypto module, store it with an expiry timestamp, send it via Twilio, and verify it in a separate Express endpoint.
Prerequisites and Setup
Install the packages with npm install twilio express dotenv; no extra package is needed for code generation since Node.js ships with the crypto module. Store your Twilio credentials in a .env file with Account SID, Auth Token, and sending number. The OTP store in this tutorial uses a Map keyed by phone number; replace it with a Redis store or database table in production so codes survive server restarts and can be shared across multiple Node.js instances. Set the expiry window to 5 minutes and the maximum attempt count to 3 to balance usability with security.
npm install twilio express dotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
The Complete Code
Node's crypto.randomInt(0, 1000000) generates a cryptographically secure integer that is zero-padded to six digits using String.padStart(6, '0') to prevent codes starting with zero from being shortened. Each store entry contains the code, a creation timestamp in milliseconds, and a failed-attempt counter. The verify endpoint rejects codes older than 5 minutes by comparing Date.now() against the stored timestamp, and locks the entry after three wrong guesses to prevent brute-force attacks. Deleting the entry on successful verification ensures each code can only be used once.
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const twilio = require('twilio');
const app = express();
app.use(express.json());
const client = twilio(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
const FROM = process.env.TWILIO_PHONE_NUMBER;
const OTP_STORE = new Map();
const OTP_EXPIRY_MS = 5 * 60 * 1000;
const OTP_MAX_TRIES = 3;
function generateCode() {
return String(crypto.randomInt(0, 1000000)).padStart(6, '0');
}
app.post('/otp/send', async (req, res) => {
const { phone } = req.body;
if (!phone) return res.status(400).json({ error: 'phone required' });
const code = generateCode();
OTP_STORE.set(phone, { code, created: Date.now(), attempts: 0 });
try {
await client.messages.create({
body: 'Your Telphi code is ' + code + '. Valid for 5 minutes.',
from: FROM,
to: phone,
});
res.json({ message: 'OTP sent' });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.post('/otp/verify', (req, res) => {
const { phone, code } = req.body;
const entry = OTP_STORE.get(phone);
if (!entry) return res.status(404).json({ error: 'No OTP requested for this number' });
if (entry.attempts >= OTP_MAX_TRIES)
return res.status(429).json({ error: 'Too many attempts. Request a new code.' });
if (Date.now() - entry.created > OTP_EXPIRY_MS) {
OTP_STORE.delete(phone);
return res.status(410).json({ error: 'Code expired. Request a new one.' });
}
if (code !== entry.code) {
entry.attempts += 1;
const remaining = OTP_MAX_TRIES - entry.attempts;
return res.status(401).json({ error: remaining + ' attempt(s) remaining.' });
}
OTP_STORE.delete(phone);
res.json({ verified: true });
});
app.listen(3000, () => console.log('OTP server on port 3000'));
Testing and Debugging
POST to /otp/send with a JSON body containing your phone number and verify the SMS arrives within a few seconds with the six-digit code. POST to /otp/verify with the correct code and confirm the 200 verified response. Test the wrong-code path three times in a row to trigger the 429 lockout response on the third failed attempt. Wait 6 minutes after sending a code and confirm the 410 expired response fires when trying to use the old code.
Taking It Further
Replace the in-memory Map with a Redis store using the ioredis package and set each key's TTL to 300 seconds so expired entries are automatically cleaned up without any cron job. Add a per-phone rate limit on the /otp/send endpoint using express-rate-limit to block more than three OTP requests per phone number within 15 minutes, preventing SMS flooding. Log every OTP request and verification attempt to an audit table without storing the code itself, keeping a tamper-evident record for security compliance. Consider switching to the Twilio Verify API for built-in fraud monitoring and adaptive verification on high-risk traffic patterns.
Contact Telphi Consulting to design a secure multi-factor authentication system using Node.js and Twilio for your web or mobile application.
Ready to Transform Your Business Communications?
Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.
Comments (0)
Join the discussion and share your thoughts (AI-moderated for quality)
Be the first to comment
No comments yet. Share your thoughts below.