Developer Quick-Start: Build SMS two-factor authentication in RedwoodJS using Sinch Verification API. Step-by-step tutorial covering phone verification, dbAuth integration, GraphQL mutations, and production security best practices for Node.js applications. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.
Implementing two-factor authentication (2FA) in RedwoodJS applications strengthens security by requiring users to verify their identity through SMS one-time passwords (OTP). This comprehensive guide demonstrates how to build SMS-based phone verification using Sinch's Verification API with RedwoodJS v8.6+ and its built-in dbAuth authentication system for production-ready 2FA implementation.
Quick Reference
| Feature | Implementation |
|---|---|
| Authentication Method | SMS-based OTP with Sinch Verification API |
| Framework | RedwoodJS v8.6+ with dbAuth |
| Node.js Version | v22 LTS (supported until April 2027) |
| Database | PostgreSQL v9.6+ with Prisma ORM v5/v6 |
| OTP Delivery Time | 30 seconds average |
| Verification Report Retention | 14 days |
| Conversion Rate Improvement | Up to 11% with multi-method fallbacks |
| Primary Use Case | Phone number verification and 2FA login |
Prerequisites for RedwoodJS 2FA Implementation
Before implementing SMS OTP authentication in your RedwoodJS application, ensure you have:
- Node.js v22 LTS (recommended, Active LTS until October 2025, maintained until April 2027) or later
- RedwoodJS v8.6+ installed (v7 is no longer actively maintained; upgrade guide available)
- A Sinch account with SMS capabilities (sign up here)
- PostgreSQL database (v9.6+ for Prisma v5 compatibility)
- Prisma ORM (v5+ requires Node.js 16.13.0 minimum, TypeScript 4.7+)
- Basic familiarity with RedwoodJS, GraphQL, and Prisma
Note: RedwoodJS v8 introduced enhanced dbAuth features including improved session management and WebAuthn support for biometric authentication.
What You'll Build: RedwoodJS SMS Authentication System
You'll build upon RedwoodJS's built-in dbAuth system, adding a second verification step after
successful password authentication. Sinch generates and verifies the OTP codes automatically, handling SMS
delivery and code validation through their Verification API.
Project Overview: RedwoodJS Two-Factor Authentication
- Goal: Enhance application security by adding an SMS-based OTP verification step after standard password login for RedwoodJS applications.
- Problem Solved: Protects user accounts even if passwords are compromised by requiring access to the user's registered phone number.
- Technologies:
- RedwoodJS: Full-stack JavaScript/TypeScript framework. You'll leverage its structure, CLI, dbAuth, Prisma ORM, and GraphQL API.
- Node.js: The underlying runtime environment.
- Prisma: Database toolkit for schema definition, migrations, and type-safe database access.
- Sinch Verification API: Third-party service for sending and managing OTPs via SMS. Sinch handles OTP generation and verification.
- React: For the frontend components.
- Architecture (Sinch-Generated OTP Flow):
- Browser/User: Sends Login Request (Email/Password) to RedwoodJS Frontend.
- RedwoodJS Frontend: Sends GraphQL Mutation (login) to RedwoodJS API (dbAuth).
- RedwoodJS API (
dbAuth): Validates Credentials against the Database (Prisma). - Database (Prisma): Confirms User Found & Password OK, responds to API.
- RedwoodJS API: Initiates Sinch Verification request to Sinch Verification API.
- Sinch Verification API: Sends OTP SMS to User's Phone.
- RedwoodJS API: Responds to Frontend: Needs OTP.
- RedwoodJS Frontend: Displays OTP Input to Browser/User.
- Browser/User: Submits OTP to Frontend.
- RedwoodJS Frontend: Sends GraphQL Mutation (verifyOtp) to API.
- RedwoodJS API: Verifies OTP with Sinch Verification API.
- Sinch Verification API: Confirms OTP Valid, responds to API.
- RedwoodJS API: Optionally updates User Record (e.g., isPhoneVerified) in Database.
- RedwoodJS API: Responds to Frontend: Success.
- RedwoodJS Frontend: Updates state to Logged In (Session Active) for Browser/User.
- Prerequisites:
- Node.js (LTS version recommended) and Yarn installed.
- RedwoodJS CLI installed (yarn global add redwoodjs/cli).
- Access to a database supported by Prisma (PostgreSQL recommended).
- A Sinch account with access to the Verification API.
- Basic understanding of RedwoodJS, React, GraphQL, and Prisma.
- Outcome: A RedwoodJS application where users with a verified phone number, after entering the correct password, must enter an OTP code sent by Sinch to their registered phone number to complete the login process.
How to Set Up RedwoodJS Project with Authentication
First, create a new RedwoodJS project and set up the basic database authentication.
- Create RedwoodJS App:
yarn create redwood-app ./redwood-sinch-otp
cd redwood-sinch-otp
- Configure Database:
- Edit
schema.prismato connect to your database (e.g., PostgreSQL). Update thedatasource dbblock:
Prisma
// schema.prisma
datasource db {
provider = "postgresql" // Or your chosen DB
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
binaryTargets = "native"
}
- Create a
.envfile in the project root and add your database connection string:
# .env
DATABASE_URL=postgresql://user:password@host:port/database
- Set up Redwood
dbAuth:
yarn rw setup auth dbAuth
- Follow the post-install instructions printed in the terminal carefully. This involves adding fields to your User model in schema.prisma and configuring api/src/functions/auth.js.
- Define Initial User Schema:
- Modify
schema.prismaaccording to thedbAuthsetup instructions. YourUsermodel should look something like this initially:
Prisma
// schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
hashedPassword String
salt String
resetToken String?
resetTokenExpiresAt DateTime?
// Add other user fields as needed, like name
name String?
}
- Apply Database Migrations:
yarn rw prisma migrate dev --name initial-setup
- Generate Basic Auth Pages:
yarn rw generate dbAuth
- This creates Login, Signup, Forgot Password, and Reset Password pages and components. Follow the post-install instructions, especially regarding redirect configuration after login/signup (e.g., in web/src/pages/LoginPage/LoginPage.js).
- Generate
SESSION_SECRET:
- Run
yarn rw g secretand copy the output. - Add it to your
.envfile:
# .env
DATABASE_URL=...
SESSION_SECRET=paste_your_secret_here
- Important: Keep
SESSION_SECRETprivate and unique for each environment. Do not commit it to version control.
At this point, you should have a functional RedwoodJS app with basic email/password authentication. Test the signup and login flow.
Modifying Database Schema for Phone Number Verification
We need to add fields to the User model to store the user's phone number and track whether it
has been verified (which determines if the OTP step is required). Since Sinch will generate and manage the OTP
value and its expiry, we don't need fields in our database to store the OTP itself.
- Update
schema.prisma:
Prisma
// schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
phone String? @unique // Add phone number (make required later if needed)
isPhoneVerified Boolean @default(false) // Track if phone verified (for OTP enforcement)
// We don't need otp or otpExpiresAt if Sinch handles generation/verification
hashedPassword String
salt String
resetToken String?
resetTokenExpiresAt DateTime?
name String?
}
phone: Stores the user's phone number in E.164 format (e.g., +15551234567). Initially optional to allow signup without it.isPhoneVerified: Boolean flag. We'll only enforce OTP for users where this is true. This flag should be set after the user successfully verifies their phone number for the first time (typically via a profile settings page).
- Apply Migration:
yarn rw prisma migrate dev --name add-phone-verification-fields
Integrating Sinch Verification API with RedwoodJS
Now, let's set up the Sinch integration to send OTP SMS messages.
- Get Sinch Credentials:
- Log in to your Sinch Dashboard.
- Navigate to Verification > Apps.
- Create a new Verification App or use an existing one.
- Find your Application Key and Application Secret.
- Ensure SMS is enabled as a verification method for your app within the Sinch settings.
- Store Credentials Securely:
- Add the Sinch Key and Secret to your
.envfile:
# .env
DATABASE_URL=...
SESSION_SECRET=...
SINCH_APP_KEY=your_sinch_application_key
SINCH_APP_SECRET=your_sinch_application_secret
- Never commit these keys to version control. Add
.envto your.gitignorefile (Redwood does this by default).
- Sinch API Endpoint:
- The primary Sinch Verification API endpoints we'll use are:
- Initiate Verification: POST https://verificationapi-v1.sinch.com/verification/v1/verifications
- Report Verification (Verify Code): PUT https://verificationapi-v1.sinch.com/verification/v1/verifications/number/{phoneNumber}
Implementing Core OTP Logic in RedwoodJS
We'll create services and modify the dbAuth handler to manage the OTP request and verification
flow using Sinch.
- Install
node-fetch(if needed): RedwoodJS typically includesfetchglobally, but explicitly adding it can sometimes avoid issues, especially in older Node versions or specific deployment environments. If you encounterfetch is not definederrors on the API side, install it:
yarn workspace api add node-fetch@2
And import it where needed: import fetch from 'node-fetch'
- Create OTP Helper Functions (Optional):
- Since Sinch generates the OTP, we don't need generateOtp or getOtpExpiry functions for the core flow. You can keep api/src/lib/otp.ts for other potential helpers or remove it if unused.
- Create Sinch Service:
- Generate a Redwood service to encapsulate Sinch interactions:
yarn rw g service sinch
- Implement functions to initiate verification (
sendOtpSms) and verify the code (verifySinchOtp):
import fetch from 'node-fetch'
import type { Response as FetchResponse } from 'node-fetch'
import { logger } from 'src/lib/logger'
const SINCH_API_BASE_URL = 'https://verificationapi-v1.sinch.com/verification/v1'
const APP_KEY = process.env.SINCH_APP_KEY
const APP_SECRET = process.env.SINCH_APP_SECRET
interface SinchVerificationResponse {
id?: string
[key: string]: any
}
interface SinchReportResponse {
id?: string
method?: string
status?: string
reason?: string
reference?: string
source?: string
}
interface SinchErrorResponse {
errorCode: number
message: string
reference?: string
}
export const sendOtpSms = async (phoneNumber: string): Promise<{ success: boolean; verificationId?: string; error?: string }> => {
if (!APP_KEY || !APP_SECRET) {
logger.error('Sinch App Key or Secret not configured.')
return { success: false, error: 'SMS service configuration error.' }
}
if (!/^\+[1-9]\d{1,14}$/.test(phoneNumber)) {
logger.error(`Invalid phone number format provided: ${phoneNumber}`)
return { success: false, error: 'Invalid phone number format.' }
}
const basicAuth = Buffer.from(`${APP_KEY}:${APP_SECRET}`).toString('base64')
const verificationUrl = `${SINCH_API_BASE_URL}/verifications`
logger.info(`Requesting OTP SMS via Sinch for phone: ${phoneNumber.substring(0, 5)}...`)
try {
const response: FetchResponse = await fetch(verificationUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${basicAuth}`,
},
body: JSON.stringify({
identity: { type: 'number', endpoint: phoneNumber },
method: 'sms',
}),
})
const responseBody = await response.json()
if (!response.ok) {
const errorData = responseBody as SinchErrorResponse
logger.error({ sinchError: errorData }, `Sinch API error (${response.status}) initiating verification: ${errorData.message}`)
return { success: false, error: `Failed to send OTP: ${errorData.message || 'Unknown Sinch error'}` }
}
const successData = responseBody as SinchVerificationResponse
logger.info(`Sinch verification initiated successfully. ID: ${successData.id}`)
return { success: true, verificationId: successData.id }
} catch (error) {
logger.error(error, 'Error calling Sinch verification initiation API')
return { success: false, error: 'Failed to contact OTP service.' }
}
}
export const verifySinchOtp = async (phoneNumber: string, code: string): Promise<{ success: boolean; error?: string }> => {
if (!APP_KEY || !APP_SECRET) {
logger.error('Sinch App Key or Secret not configured.')
return { success: false, error: 'SMS service configuration error.' }
}
const basicAuth = Buffer.from(`${APP_KEY}:${APP_SECRET}`).toString('base64')
const reportUrl = `${SINCH_API_BASE_URL}/verifications/number/${encodeURIComponent(phoneNumber)}`
logger.info(`Verifying OTP with Sinch for phone: ${phoneNumber.substring(0, 5)}...`)
try {
const response: FetchResponse = await fetch(reportUrl, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${basicAuth}`,
},
body: JSON.stringify({
method: 'sms',
sms: { code: code },
}),
})
const responseBody = await response.json()
if (!response.ok) {
const errorData = responseBody as SinchErrorResponse
logger.error({ sinchError: errorData }, `Sinch API verification error (${response.status}): ${errorData.message}`)
if (response.status === 400 || response.status === 404) {
return { success: false, error: 'Invalid or expired OTP code.' }
}
return { success: false, error: `OTP verification failed: ${errorData.message || 'Sinch error'}` }
}
const reportData = responseBody as SinchReportResponse
if (reportData.status === 'SUCCESSFUL') {
logger.info(`Sinch verification successful for ${phoneNumber.substring(0, 5)}...`)
return { success: true }
} else {
logger.warn(`Sinch verification status: ${reportData.status} (Reason: ${reportData.reason || 'N/A'}) for ${phoneNumber.substring(0, 5)}...`)
return { success: false, error: 'Invalid or expired OTP code.' }
}
} catch (error) {
logger.error(error, 'Error calling Sinch verification report API')
return { success: false, error: 'Failed to contact OTP verification service.' }
}
}
- Create GraphQL Mutations for OTP:
- Generate the SDL and service stubs:
yarn rw g sdl otp --no-crud
- Define the mutations in the SDL:
export const schema = gql`
type Mutation {
"""
Requests an OTP to be sent via Sinch to the user's registered phone number.
Requires standard authentication (valid session cookie from initial password login).
Used for resending OTP during login or for initial phone verification.
"""
requestOtp: OtpResponse! @requireAuth
"""
Verifies the OTP entered by the user against Sinch.
Requires standard authentication. If successful, the login process is complete.
"""
verifyOtp(otp: String!): OtpResponse! @requireAuth
}
type OtpResponse {
success: Boolean!
message: String
}
`
- Implement the service logic:
import { db } from 'src/lib/db'
import { requireAuth, context } from 'src/lib/auth'
import { logger } from 'src/lib/logger'
import { sendOtpSms, verifySinchOtp } from 'src/services/sinch/sinch'
import type { MutationResolvers } from 'types/graphql'
const getCurrentUserPhone = async () => {
const user = context.currentUser
if (!user?.id) {
throw new Error("User not authenticated.")
}
const dbUser = await db.user.findUnique({
where: { id: user.id },
select: { phone: true, isPhoneVerified: true }
})
if (!dbUser?.phone) {
throw new Error("User does not have a registered phone number.")
}
return { phone: dbUser.phone, isPhoneVerified: dbUser.isPhoneVerified }
}
export const requestOtp: MutationResolvers['requestOtp'] = async () => {
const { phone } = await getCurrentUserPhone()
const result = await sendOtpSms(phone)
if (!result.success) {
logger.error(`Failed to request OTP for user ${context.currentUser.id}: ${result.error}`)
return { success: false, message: result.error || 'Failed to initiate OTP.' }
}
logger.info(`OTP requested successfully via Sinch for user ${context.currentUser.id}`)
return { success: true, message: 'A new OTP has been sent to your registered phone number.' }
}
export const verifyOtp: MutationResolvers['verifyOtp'] = async ({ otp }) => {
const userId = context.currentUser.id
const { phone, isPhoneVerified } = await getCurrentUserPhone()
if (!/^\d{4,8}$/.test(otp)) {
return { success: false, message: 'Invalid OTP format.' }
}
const result = await verifySinchOtp(phone, otp)
if (!result.success) {
logger.warn(`OTP verification failed for user ${userId}: ${result.error}`)
return { success: false, message: result.error || 'Invalid or expired OTP.' }
}
logger.info(`OTP verified successfully via Sinch for user ${userId}`)
if (!isPhoneVerified) {
await db.user.update({
where: { id: userId },
data: {
isPhoneVerified: true,
},
})
logger.info(`Marked phone as verified for user ${userId}`)
}
return { success: true, message: 'Verification successful. Logging you in...' }
}
- Modify
dbAuthLogin:
- Edit
api/src/functions/auth.js(or.ts). Modify thelogin.handlerto check if OTP is required and trigger the initial Sinch SMS send if necessary.
import { db } from 'src/lib/db'
import { logger } from 'src/lib/logger'
import { sendOtpSms } from 'src/services/sinch/sinch'
import { DbAuthHandler } from '@redwoodjs/auth-dbauth-api'
export const handler = DbAuthHandler(db, {
dbAuthHandlerOptions: {
cookie: {
secure: process.env.NODE_ENV === 'production',
sameSite: 'Lax',
path: '/',
},
secret: process.env.SESSION_SECRET,
authFields: {
id: 'id',
username: 'email',
hashedPassword: 'hashedPassword',
salt: 'salt',
},
login: {
handler: async (user) => {
logger.info(`User ${user.id} passed password check.`);
const userWithPhone = await db.user.findUnique({
where: { id: user.id },
select: { phone: true, isPhoneVerified: true }
});
if (userWithPhone?.phone && userWithPhone.isPhoneVerified) {
logger.info(`User ${user.id} has a verified phone and requires OTP verification.`);
sendOtpSms(userWithPhone.phone).catch(e => {
logger.error(e, `Background OTP send failed for user ${user.id}`);
});
throw new Error('AUTH_OTP_REQUIRED');
} else {
logger.info(`User ${user.id} logging in without OTP (phone: ${userWithPhone?.phone ? 'present' : 'missing'}, verified: ${userWithPhone?.isPhoneVerified ?? 'N/A'}).`);
return user;
}
},
},
},
})
- Handling
AUTH_OTP_REQUIRED: If you throw this error, theuseAuth().logIn()call on the frontend will fail. You'll need to catch this specific error message in yourLoginPagecomponent and transition the UI to the OTP input state instead of treating it as a generic login failure. - Note on "Fire and Forget": The
sendOtpSms(...).catch(...)call runs in the background. If the Sinch API call fails silently (e.g., network issue, temporary Sinch outage), the user might not receive the OTP, but the login flow will still proceed to the OTP entry step. For production systems, consider using a more robust background job queue (like Redis with BullMQ) to handle sending the SMS, allowing for retries and better error monitoring. However, for simplicity, this guide uses the basic "fire and forget" approach with logging.
Building the Frontend OTP Components in RedwoodJS
Modify the LoginPage to handle the OTP step.
- Add State for OTP:
- In
web/src/pages/LoginPage/LoginPage.js(or.tsx), add state to manage the UI flow:
import React, { useState, useEffect } from 'react'
import { navigate, routes } from '@redwoodjs/router'
import { MetaTags } from '@redwoodjs/web'
import { toast } from '@redwoodjs/web/toast'
import { Form, Label, TextField, PasswordField, Submit, FieldError } from '@redwoodjs/forms'
import { useAuth } from '@redwoodjs/auth'
import { useMutation, gql } from '@redwoodjs/web'
const REQUEST_OTP_MUTATION = gql`
mutation RequestOtpMutation {
requestOtp {
success
message
}
}
`
const VERIFY_OTP_MUTATION = gql`
mutation VerifyOtpMutation($otp: String!) {
verifyOtp(otp: $otp) {
success
message
}
}
`
const LoginPage = () => {
const { isAuthenticated, logIn, currentUser, loading: authLoading } = useAuth()
const [uiState, setUiState] = useState('login')
useEffect(() => {
if (isAuthenticated) {
navigate(routes.home())
}
}, [isAuthenticated])
const onSubmitLogin = async (data) => {
setUiState('loading')
const response = await logIn({ username: data.username, password: data.password })
if (response.message) {
} else if (response.error) {
if (response.error.message === 'AUTH_OTP_REQUIRED') {
toast('Password correct. Please enter the OTP sent to your phone.')
setUiState('otp')
} else {
toast.error(response.error.message || 'Login Failed')
setUiState('login')
}
} else {
toast.success('Welcome back!')
navigate(routes.home())
}
if (uiState === 'loading' && response.error?.message !== 'AUTH_OTP_REQUIRED') {
setUiState('login')
}
}
const onSubmitOtp = async (data) => {
setUiState('loading')
verifyOtp({ variables: { otp: data.otp } });
}
const handleResendOtp = () => {
setUiState('loading')
requestOtp();
}
const [verifyOtp] = useMutation(VERIFY_OTP_MUTATION, {
onCompleted: (data) => {
if (data.verifyOtp.success) {
toast.success(data.verifyOtp.message || 'Login successful!')
navigate(routes.home())
} else {
toast.error(data.verifyOtp.message || 'OTP Verification Failed')
setUiState('otp')
}
},
onError: (error) => {
toast.error(error.message || 'An error occurred during OTP verification.')
setUiState('otp')
}
});
const [requestOtp] = useMutation(REQUEST_OTP_MUTATION, {
onCompleted: (data) => {
if (data.requestOtp.success) {
toast.success(data.requestOtp.message || 'New OTP sent.')
} else {
toast.error(data.requestOtp.message || 'Failed to send new OTP.')
}
setUiState('otp')
},
onError: (error) => {
toast.error(error.message || 'An error occurred requesting a new OTP.')
setUiState('otp')
}
});
return (
<>
<MetaTags title="Login" />
<h1>Login</h1>
{uiState === 'login' && (
// Standard Login Form
<Form onSubmit={onSubmitLogin}>
<Label name="username" errorClassName="error">Username (Email)</Label>
<TextField name="username" validation={{ required: true }} errorClassName="error" />
<FieldError name="username" className="error" />
<Label name="password" errorClassName="error">Password</Label>
<PasswordField name="password" validation={{ required: true }} errorClassName="error" />
<FieldError name="password" className="error" />
<Submit disabled={authLoading || uiState === 'loading'}>{authLoading || uiState === 'loading' ? 'Logging in...' : 'Login'}</Submit>
</Form>
)}
{uiState === 'otp' && (
// OTP Input Form (see Step 2)
<Form onSubmit={onSubmitOtp}>
{/* OTP Form content here */}
</Form>
)}
{uiState === 'loading' && (
<div>Loading...</div> // Generic loading indicator
)}
{/* Links to signup, forgot password etc. */}
</>
)
}
export default LoginPage
- Create OTP Input Form:
- Add the form JSX that renders when
uiStateis'otp'.
{uiState === 'otp' && (
<Form onSubmit={onSubmitOtp}>
<h2>Enter OTP</h2>
<p>Enter the 6-digit code sent by SMS to your registered phone number.</p>
<Label name="otp" errorClassName="error">OTP Code</Label>
<TextField
name="otp"
validation={{
required: true,
pattern: { value: /^\d{6}$/, message: 'Enter 6 digits' } // Adjust pattern/length if Sinch uses different length
}}
errorClassName="error"
maxLength="6" // Match expected length
/>
<FieldError name="otp" className="error" />
<Submit disabled={uiState === 'loading'}>{uiState === 'loading' ? 'Verifying...' : 'Verify OTP'}</Submit>
<button type="button" onClick={handleResendOtp} disabled={uiState === 'loading'}>
{uiState === 'loading' ? 'Sending...' : 'Resend OTP'}
</button>
</Form>
)}
Frequently Asked Questions About RedwoodJS SMS 2FA
What is the difference between Sinch SMS API and Sinch Verification API?
The Sinch Verification API is purpose-built for phone number verification workflows, handling OTP generation, delivery, and validation automatically. It achieves up to 11% higher conversion rates through multiple verification methods (SMS, FlashCall, Data) with automatic fallbacks. The standard SMS API requires manual OTP generation and validation logic. For 2FA implementations, always use the Verification API.
Does Sinch Verification API work with RedwoodJS v7?
While technically compatible, RedwoodJS v7 is no longer actively maintained. This guide targets RedwoodJS v8.6+, which includes enhanced dbAuth features like improved session management and WebAuthn support. Upgrade to v8 using the official upgrade guide before implementing 2FA.
How long does Sinch retain verification reports?
Sinch retains verification reports and delivery receipts for 14 days after creation. Ensure your application processes callbacks and stores necessary verification data (verification IDs, timestamps, success status) within this retention window for compliance and auditing purposes.
Can you use Sinch OTP verification without storing phone numbers in the database?
No. You must store phone numbers in your database to implement 2FA effectively. The phone field
(E.164 format) and isPhoneVerified boolean flag are essential for determining which users require
OTP verification during login. Without database storage, you cannot enforce 2FA consistently across sessions.
What happens if the Sinch SMS fails to deliver?
If Sinch fails to deliver an SMS (network issues, invalid number, carrier problems), the user won't receive the OTP code. Sinch's Verification API automatically tracks delivery status and can trigger fallback methods (FlashCall, Data verification) if configured. Implement robust error handling and allow users to request new codes with rate limiting (e.g., 3 attempts per hour).
How much does Sinch Verification API cost per verification?
Sinch charges per verification attempt, with pricing varying by destination country. Check your Sinch Dashboard pricing page for current rates. Implement rate limiting (per-IP, per-user, per-phone) to prevent abuse and control costs. Failed verifications still incur charges, so validate phone number formats before initiating verification.
Yes. Modify the signup handler in api/src/functions/auth.js instead of
login. After creating the user account, initiate Sinch verification and mark the account as
"pending verification" until the user completes OTP validation. This prevents fake account creation and
ensures valid contact information.
What phone number format does Sinch require?
Sinch requires E.164 format for all phone numbers:
+[country code][subscriber number] without spaces, hyphens, or parentheses. Examples:
+14155552671 (US), +442071234567 (UK), +8190123456789 (Japan). Validate
format using regex /^\+[1-9]\d{1,14}$/ on both client and server before sending to Sinch.
How do you test Sinch OTP integration in development?
Sinch provides test credentials in your Dashboard for development. Use your personal phone number for initial testing. For automated testing, consider mock services that simulate Sinch's Verification API responses, or use Sinch's sandbox environment if available. Never test with production credentials committed to version control.
Does RedwoodJS dbAuth support WebAuthn for biometric 2FA?
Yes. RedwoodJS v8 introduced WebAuthn support for biometric authentication (TouchID, FaceID, USB fingerprint readers) alongside traditional passwords. You can implement both SMS OTP and WebAuthn as 2FA options, allowing users to choose their preferred second factor. See the dbAuth v8 documentation for WebAuthn implementation details.
Conclusion: Production-Ready RedwoodJS 2FA Implementation
You've successfully implemented SMS-based OTP two-factor authentication in your RedwoodJS application using Sinch's Verification API. This implementation significantly enhances account security by requiring both password knowledge and phone access for login.
Key Implementation Highlights:
- Sinch Verification API handles OTP generation, delivery, and validation automatically with 14-day report retention
- RedwoodJS v8.6+ dbAuth provides enhanced session management and optional WebAuthn support for biometric authentication
- Node.js v22 LTS offers long-term support until April 2027 for production stability
- Prisma v5/v6 enables type-safe database operations with PostgreSQL v9.6+ compatibility
- E.164 phone format validation prevents delivery failures and ensures global compatibility
Next Steps to Enhance Your Implementation:
- Add Multi-Method Verification: Implement FlashCall and Data verification as fallbacks for SMS delivery failures
- Implement Rate Limiting: Protect against abuse with per-IP, per-user, and per-phone attempt limits
- Set Up Monitoring: Track verification conversion rates, delivery times, and failure patterns via Sinch analytics
- Enable WebAuthn: Offer biometric 2FA options (TouchID, FaceID) alongside SMS OTP in RedwoodJS v8
- Implement Backup Codes: Generate one-time recovery codes for users who lose phone access
- Add Phone Verification UI: Create profile pages for users to add, verify, and manage phone numbers
- Configure Production Environment: Set up proper environment variables, HTTPS, and security headers for deployment
Additional Resources:
- Sinch Verification API Documentation β Complete API reference and best practices
- RedwoodJS v8 dbAuth Guide β Authentication system documentation
- Node.js LTS Release Schedule β Version support timelines
- Prisma v6 Upgrade Guide β Database ORM migration details
- E.164 Phone Number Format Specification β International numbering standards
Your RedwoodJS application now provides robust two-factor authentication that protects user accounts even when passwords are compromised. The Sinch Verification API's multi-method approach with automatic fallbacks ensures high delivery rates and optimal user experience.
Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)
If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.
curl -X POST https://api.sendsmsnokyc.com/messages \
-H "x-api-key: $SMSROUTE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"to": ["+14155551234"],
"channel": ["sms"],
"body": "Your verification code is 482910"
}'
- Instant onboarding: No KYC paperwork or sales queues β grab an API key and fund with crypto (BTC/USDT) or card.
- Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
- Transparent global pricing: Compare exact per-country termination rates on our live pricing page.
Ship Global SMS in One API Call
Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.
Explore SMSRoute Developers β