This tutorial implements phone number verification using the Twilio Verify API in Node.js, covering sending a one-time code and validating the code a user submits in your application. It targets Node.js developers building registration flows, two-factor authentication, or account recovery features who want Twilio to manage code generation, expiry, and attempt limits. You will build a two-step flow using Express: send the OTP and check the OTP, with Twilio handling all the underlying complexity.
Prerequisites and Setup
Install the required packages with npm install twilio express dotenv and create a Verify Service in the Twilio Console under Verify, Services. Copy the Verify Service SID, which starts with VA, and add it to your .env file alongside your Account SID and Auth Token. Twilio Verify manages code generation, SMS delivery, a 10-minute expiry window, and a maximum of five verification attempts per code without any configuration on your end. The API is accessed through the same Twilio client as the rest of the SDK using the verify.v2.services(SID) namespace.
npm install twilio express dotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_VERIFY_SERVICE_SID=VAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
The Complete Code
The send step calls client.verify.v2.services(SID).verifications.create() with the to phone number and channel set to 'sms', which triggers Twilio to generate and send the OTP. The check step calls verificationChecks.create() with the phone number and the code the user entered; the returned object's status field is 'approved' on success. Catching errors and checking err.code === 60200 lets you distinguish an invalid code from a network or authentication error. Both operations return Promises so you can use async/await for clean, flat code flow in your Express handlers.
require('dotenv').config();
const express = require('express');
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 SERVICE_SID = process.env.TWILIO_VERIFY_SERVICE_SID;
app.post('/verify/send', async (req, res) => {
const { phone } = req.body;
if (!phone) return res.status(400).json({ error: 'phone is required' });
try {
const verification = await client.verify.v2
.services(SERVICE_SID)
.verifications.create({ to: phone, channel: 'sms' });
res.json({ status: verification.status });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.post('/verify/check', async (req, res) => {
const { phone, code } = req.body;
if (!phone || !code) return res.status(400).json({ error: 'phone and code required' });
try {
const check = await client.verify.v2
.services(SERVICE_SID)
.verificationChecks.create({ to: phone, code });
if (check.status === 'approved') {
res.json({ verified: true });
} else {
res.status(401).json({ verified: false, status: check.status });
}
} catch (err) {
if (err.code === 60200) {
return res.status(401).json({ verified: false, error: 'Invalid or expired code' });
}
res.status(500).json({ error: err.message });
}
});
app.listen(3000, () => console.log('Verify server on port 3000'));
Testing and Debugging
POST to /verify/send with a JSON body of { "phone": "+15551234567" } and verify the SMS arrives on the test device. Then POST to /verify/check with the phone and the code you received to confirm the approved response. Test the failure path by entering a wrong code and verifying the 401 response fires; test the lockout by entering wrong codes five times to confirm Twilio rejects further attempts. Use Twilio's magic test phone numbers in the Console to run verify flows in automated tests without consuming SMS credits.
Taking It Further
Set the channel to 'call' instead of 'sms' to deliver the OTP as an automated voice call for users who cannot receive SMS. Customize the code length (4 or 8 digits) and expiry window in the Verify Service settings in the Twilio Console without changing any code. Add a per-phone rate limit in your Express layer to prevent OTP flooding abuse, capping requests to three sends per 15 minutes per phone number. For passwordless login, combine the Verify API check with a JWT issuance step so a successful verification automatically creates an authenticated session.
Talk to Telphi Consulting about implementing phone verification as part of a secure Node.js authentication system.
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.