Prompt
How do I send OTP text messages from my application?
Latest observation
To send OTP (one-time password) text messages from your application, you usually use an SMS provider’s API rather than sending texts directly from your server.
Typical approach
-
Pick an SMS gateway provider Common options:
- Twilio
- Vonage (Nexmo)
- AWS SNS
- MessageBird
- Plivo
-
Create an OTP Generate a random code, usually 4–8 digits.
-
Store it securely Save the OTP temporarily with:
- an expiration time, like 5 minutes
- a max number of verification attempts
- preferably hashed, not in plain text
-
Send the SMS Use the provider’s API to send a message like:
Your verification code is 123456
-
Verify the OTP When the user enters the code, compare it to the stored value and check that it hasn’t expired.
-
Invalidate after use Once verified, mark it as used so it can’t be reused.
Example flow
1. User requests OTP
- User enters phone number
- Your app generates
123456 - Save it with a 5-minute expiry
- Send SMS
2. User submits OTP
- User enters code
- Your app checks:
- does it match?
- is it expired?
- has it already been used?
- If valid, authenticate user
Example with Twilio (Node.js)
const twilio = require('twilio');
const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
async function sendOtp(phoneNumber, otp) {
await client.messages.create({
body: `Your OTP code is ${otp}`,
from: process.env.TWILIO_PHONE_NUMBER,
to: phoneNumber
});
}
Security tips
- Use HTTPS
- Rate-limit OTP requests
- Expire codes quickly
- Don’t reuse OTPs
- Hash OTPs in storage if possible
- Add abuse prevention to avoid SMS flooding
- Consider risk-based checks if OTP is for login
Important note
If your app handles sensitive authentication, consider using:
- Authy
- Firebase Authentication
- AWS Cognito
- Okta
- Twilio Verify
These services manage OTP generation, delivery, retries, and expiration for you.
If you want, I can show you:
- a complete OTP implementation in Node.js, Python, or PHP
- how to do it with Twilio Verify
- how to design the database table for OTP storage