SMS OTP Recipe
Send one-time passwords via SMS for phone number verification or two-factor authentication.
SMS OTP flow
For native/mobile clients add X-Auth-Strategy: bearer to /auth/sms/verify to receive tokens in the JSON body.
Step 1: Configure AuthConfig
SMS OTP is enabled by configuring the built-in HTTP SMS gateway in your AuthConfig.sms block:
const config: AuthConfig = {
// ... secrets
sms: {
endpoint: 'https://sms.yourprovider.com/send',
apiKey: process.env.SMS_API_KEY!,
username: process.env.SMS_USERNAME!,
password: process.env.SMS_PASSWORD!,
codeExpiresInMinutes: 10, // default: 10
},
};
The built-in SmsService makes a GET request to {endpoint}?username=…&password=…&phone=…&message=… with an X-API-Key header. See SmsService below.
Step 2: Mount the router
SMS endpoints are active as long as the SMS configuration is present in AuthConfig. No strategy needs to be passed to the router:
app.use('/auth', auth.router());
Step 3: Implement IUserStore methods
SMS OTP requires:
async updateSmsCode(userId: string, code: string | null, expiry: Date | null): Promise<void>
The user record must also have phoneNumber set.
Step 4: Test the flow
# Send OTP to user's phone
curl -X POST http://localhost:3000/auth/sms/send \
-H 'Content-Type: application/json' \
-d '{"userId":"123"}'
# Verify OTP code
curl -X POST http://localhost:3000/auth/sms/verify \
-H 'Content-Type: application/json' \
-d '{"userId":"123","code":"123456"}'
SmsService
The SmsService is exported and can be used directly in your own code:
import { SmsService } from 'awesome-node-auth';
const smsService = new SmsService({
endpoint: 'https://sms.yourprovider.com/send',
apiKey: process.env.SMS_API_KEY!,
username: process.env.SMS_USERNAME!,
password: process.env.SMS_PASSWORD!,
codeExpiresInMinutes: 10,
});
// Send a custom SMS
await smsService.sendSms('+39123456789', 'Your verification code: 847261');
// Generate a random OTP code
const code = smsService.generateCode(6); // '847261'
The service makes a GET request to {endpoint}?username={u}&password={p}&phone={phone}&message={msg} with an X-API-Key header.
SMS Endpoints
| Method | Path | Description |
|---|---|---|
POST | /auth/sms/send | Generate OTP + send to user's phoneNumber |
POST | /auth/sms/verify | Verify OTP → issue session tokens |