Developer Quick-Start: Implement Time-based One-Time Password (TOTP) two-factor authentication in Next.js using Twilio Verify API and Authy. Includes RFC 6238 compliance, security best practices, and production-ready code examples. 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.
Enhance your Next.js application's security by adding Time-based One-Time Password (TOTP) Two-Factor Authentication (2FA) using Twilio Verify and the Twilio Authy app. This guide walks you through the complete implementation, enabling your users to secure their accounts by verifying their identity through codes generated on their Authy-linked device after initial password login.
This implementation adds a robust security layer, mitigating risks associated with compromised passwords and unauthorized access. By the end of this guide, you'll have a functional 2FA flow integrated into your Next.js application.
TOTP Standard Compliance: This implementation follows RFC 6238 (TOTP: Time-Based One-Time Password Algorithm), an IETF standard published in May 2011. TOTP extends the HMAC-based One-Time Password (HOTP) algorithm by using time as the moving factor, providing short-lived OTP values with enhanced security (source: RFC 6238).
What You'll Build
Integrate Twilio Verify's TOTP functionality into an existing Next.js application that already includes basic user registration, login (with JWT), and a protected dashboard. The integration modifies the login flow:
- First-time Login After Registration/Enabling 2FA: User logs in (password check succeeds, JWT issued) β User scans a QR code with the Twilio Authy app β User enters the code from Authy β Account is verified and linked β User accesses the dashboard.
- Subsequent Logins: User logs in (password check succeeds, JWT issued) β User enters the current code from the Authy app β Code is verified β User accesses the dashboard.
Problem You'll Solve:
Add a second layer of security beyond just a password, ensuring that even if a user's password is compromised, access requires physical possession of their registered device running the Authy app.
Technologies You'll Use:
- Next.js: React framework for the frontend and API routes (acting as your Node.js backend). You'll use the Pages Router as per the example project.
- Twilio Verify API: Handles the generation, validation, and lifecycle management of TOTP factors and challenges via the Authy app. The Verify API v2 provides comprehensive 2FA capabilities including TOTP, SMS, voice, email, and passkeys (source: Twilio Verify API Documentation).
- Twilio Authy App: Mobile application (iOS/Android) your end-users use to scan QR codes and generate TOTP codes. TOTP provides enhanced security over SMS/email channels as codes work offline and no PII (personally identifiable information) is required (source: Twilio Verify TOTP Overview).
- MongoDB Atlas: Cloud database for storing user credentials and TOTP factor details.
- Node.js: Runtime environment for Next.js API routes.
twilioNode.js Helper Library: Simplifies interaction with the Twilio API.jsonwebtoken: For managing user sessions via JWTs (assumed to be handled by the starter project).mongoose: ODM for interacting with MongoDB.
What You'll Need Before Starting:
- Node.js (v16 or later recommended) installed
- npm or yarn package manager
- A free Twilio account
- Twilio Authy app installed on your smartphone (iOS or Android)
- A free MongoDB Atlas account
- ngrok installed and authenticated (optional: useful for testing with a public URL, but not required for local TOTP functionality)
- Basic understanding of Next.js, React, and REST APIs
TOTP Security Benefits:
- Enhanced Security: Tokens automatically expire (default 30-second window per RFC 6238), and there are no OTPs for fraudsters to intercept, making TOTP more secure than SMS, email, or voice channels.
- Offline Functionality: Generate and verify TOTP tokens without internet connectivity as long as device time is synchronized.
- Privacy-Preserving: TOTP doesn't require phone numbers, so no PII is stored in the Twilio Verify system.
- Lower Cost: TOTP verifications typically cost less than SMS or voice-based 2FA.
TOTP Technical Specifications (RFC 6238 Compliance):
- Time Step (X): Default 30 seconds. Configure in Twilio Verify Service between 20β60 seconds (source: Twilio Verify Service API).
- Code Length: Default 6 digits. Configure between 3β8 digits in Twilio Verify Service.
- Skew: Default 1 time-step. Twilio allows 0β2 time-steps to account for clock drift between client and server.
- Algorithm: HMAC-SHA-1 (default), with optional HMAC-SHA-256 or HMAC-SHA-512 support per RFC 6238.
- Time Base (T0): Unix epoch (January 1, 1970, 00:00:00 UTC).
System Architecture:
Note: Ensure your publishing platform supports Mermaid diagram rendering. The diagram below illustrates the intended flow β verify it against your actual implementation.
graph LR
A[User Browser] -- Login Request (User/Pass) --> B(Next.js Frontend);
B -- API Call /api/users/authenticate --> C{Next.js API Route};
C -- Query User --> D[(MongoDB Atlas)];
C -- Password Check OK / JWT Issued --> C;
alt First Time 2FA / Not Authenticated (user.authenticated == false)
C -- Redirect --> E{Scan QR Page (/account/scan)};
E -- Request Factor --> F(API Route /api/code/create);
F -- Create Factor --> G[Twilio Verify API];
G -- Binding URI --> F;
F -- Binding URI --> E;
E -- Display QR Code --> A;
A -- User Scans QR --> H(Authy App);
H -- Generate Code --> A;
A -- Submit Code --> I{Verify Code Page (/account/code)};
I -- Verify Request --> J(API Route /api/code/verify);
J -- Verify New Factor --> G;
G -- Verification Status (verified) --> J;
J -- Update user.authenticated=true, store factorSid --> D;
J -- Success Response --> I;
I -- Redirect --> K[Dashboard];
else Subsequent Logins / Already Authenticated (user.authenticated == true)
C -- Redirect --> I;
A -- Enter Code --> I;
I -- Challenge Request --> L(API Route /api/code/challenge);
L -- Create Challenge (using stored factorSid) --> G;
G -- Challenge Status (approved) --> L;
L -- Success Response --> I;
I -- Redirect --> K;
end
style G fill:#F9BBB7,stroke:#333,stroke-width:2px
style D fill:#97C491,stroke:#333,stroke-width:2px
What You'll Have When You're Done: A Next.js application where users must complete a TOTP verification step using the Authy app after password authentication to access protected routes.
1. Set Up Your Project
Use a starter project that includes basic authentication and database setup.
Clone the Starter Project: Open your terminal and navigate to the directory where you want your project. Clone the repository and install dependencies:
git clone https://github.com/DesmondSanctity/twilio-authy.git
cd twilio-authy
npm install
Important Note: This guide assumes the twilio-authy starter repository exists,
is accessible, and contains the necessary base components: Next.js (v13.2.4 with Pages Router is mentioned),
base JWT authentication, Mongoose setup, and helper functions like apiHandler and
fetchWrapper. Verify the repository's contents and README match these assumptions before
proceeding.
Set Up MongoDB Atlas:
- Go to the MongoDB Atlas website and sign up or log in.
- Create a new project if necessary.
- Create a Database: Click "Build a Database." Choose the free M0 tier, select a cloud provider and region. Leave cluster tier settings as default. Name your cluster (e.g., twilio-2fa-demo).
- Create Database User: Under "Security" β "Database Access," click "Add New Database User." Enter a username (e.g., twilioUser) and generate or create a strong password. Save this password securely. Grant the user "Read and write to any database" privileges (for simplicity in this demo; restrict in production).
- Configure Network Access: Under "Security" β "Network Access," click "Add IP Address." Select "ALLOW ACCESS FROM ANYWHERE" (0.0.0.0/0). Click "Confirm." (Again, restrict this to specific IPs in production).
- Get Connection String: Go back to "Database" under "Deployment." Find your cluster and click "Connect." Select "Drivers." Choose "Node.js" and the latest version. Copy the connection string provided. It looks like mongodb+srv://<username>:<password>@<cluster-url>/?retryWrites=true&w=majority.
Set Up Twilio:
- Log in to your Twilio Console.
- Find Account SID and Auth Token: On the main dashboard, you'll find your Account SID and Auth Token. Copy these values.
- Create a Twilio Verify Service:
- Navigate to "Explore Products" in the left sidebar (or use the search bar).
- Find and click on "Verify."
- In the Verify sidebar, click "Services."
- Click "Create service now."
- Give your service a friendly name (e.g., NextJS Authy Demo).
- Under "Verification Channels," ensure TOTP is enabled (disable others like SMS/Call if not needed).
- Click "Continue."
- Review settings (defaults work fine for this guide). Configure code length if desired.
- TOTP Configuration Options (Optional):
- Issuer: Defaults to service friendly name. This appears in the Authy app to identify your service.
- Time Step: Defaults to 30 seconds (20β60 second range). Defines how often new TOTP codes are generated.
- Code Length: Defaults to 6 digits (3β8 digit range). Balance security with user experience.
- Skew: Defaults to 1 time-step (0β2 range). Allows validation of codes from adjacent time windows to handle clock drift (source: Twilio Verify Service API).
- Click "Complete Setup" or "Save."
- Copy the Service SID: On the service's settings page, find and copy the Service SID (starts with VA...).
Security Note β API Key Authentication (Production Recommendation): For production applications, Twilio strongly recommends using API Keys instead of your Account SID and Auth Token. API Keys provide better security through:
- Credential rotation without downtime
- Restricted permissions and scope
- Separate credentials for different environments
- Easier revocation if compromised
To create an API Key: Navigate to Account β API Keys & Tokens in the Twilio Console. Use the API Key SID as the username and API Key Secret as the password (source: Twilio Verify API Authentication).
Configure Environment Variables:
Create a file named .env in the root directory of your twilio-authy project. Add
the following variables, replacing the placeholders with your actual credentials:
.env
# MongoDB Connection String (replace <password> and other placeholders)
MONGODB_URI=mongodb+srv://twilioUser:<YOUR_MONGODB_PASSWORD>@<your-cluster-url>/?retryWrites=true&w=majority
# JWT Secret (use a long, random, secure string)
JWT_SECRET=your-very-secure-and-random-jwt-secret-key
# Twilio Credentials
TWILIO_ACCOUNT_SID=<Your Twilio Account SID starting with AC...>
TWILIO_AUTH_TOKEN=<Your Twilio Auth Token>
TWILIO_VERIFY_SERVICE_SID=<Your Twilio Verify Service SID starting with VA...>
MONGODB_URI: Your MongoDB Atlas connection string, with the <password> placeholder replaced by the database user password you created.JWT_SECRET: A long, random string used to sign JSON Web Tokens for session management. Keep this secret.TWILIO_ACCOUNT_SID: Your main Twilio account identifier. Find this on the Twilio Console dashboard.TWILIO_AUTH_TOKEN: Your Twilio secret key. Find this on the Twilio Console dashboard. Treat this like a password.TWILIO_VERIFY_SERVICE_SID: The unique identifier for the Twilio Verify service you created. Find this in the Verify service settings in the Twilio Console.
Why Use Environment Variables? Environment variables keep sensitive credentials out of your source code, making your application more secure and configurable across different environments (development, staging, production).
2. Understand the Authentication Flow
The starter project has a basic Register β Login β Dashboard flow. You'll modify this to incorporate 2FA:
- JWT Issuance: The initial login process (e.g., in
userService.logincalling/api/users/authenticate) verifies the password and, upon success, issues a JSON Web Token (JWT). This JWT maintains the user's session for subsequent API requests. - 2FA Check Timing: The 2FA verification step happens after the initial password authentication and JWT issuance but before granting access to the final protected resources (like the dashboard). The JWT proves the password was correct; the 2FA code proves possession of the registered device.
- TOTP Time Synchronization Considerations (RFC 6238): TOTP relies on synchronized time between the client (Authy app) and validation server (Twilio). Due to potential clock drift, RFC 6238 recommends:
- Maximum 1 time-step network delay allowance for validation
- Resynchronization mechanisms if drift exceeds thresholds
- Twilio's skew parameter (default 1, max 2) handles this by validating codes from adjacent time windows
- For 30-second time steps with skew=1, the maximum acceptable time drift is approximately 89 seconds (29s in current window + 60s for 2 backward steps) (source: RFC 6238 Section 5.2)
- Initial Setup Flow (First Time Enabling 2FA):
- User registers or logs in (password check succeeds, JWT issued).
- System checks if user.authenticated (a flag in the User model) is false.
- Redirect to /account/scan.
- /account/scan page calls /api/code/create endpoint.
- /api/code/create uses Twilio Verify to create a newFactor (TOTP type) for the user. Twilio returns a binding.uri.
- Use the binding.uri to generate a QR code displayed on the /account/scan page.
- User scans the QR code using the Twilio Authy app. Authy now generates codes for this account.
- User is redirected or navigated to /account/code.
- User enters the 6-digit code from Authy into the form on /account/code.
- Form submits to /api/code/verify.
- /api/code/verify uses Twilio Verify to validate the newFactor using the submitted code.
- On success, Twilio confirms the factor is verified. The API updates the user's record in MongoDB (sets authenticated: true and stores factorSid). Temporary binding keys (user.keys) are cleared.
- Redirect to /dashboard.
- Subsequent Login Flow (User Already Has 2FA Enabled):
- User logs in (password check succeeds, JWT issued).
- System checks if user.authenticated is true.
- Redirect to /account/code.
- User enters the current 6-digit code from Authy into the form on /account/code.
- Form submits to /api/code/challenge.
- /api/code/challenge uses Twilio Verify to create and check a challenge using the user's stored factorSid and the submitted code.
- On success (challenge status is approved), redirect to /dashboard.
3. Implement Your Backend API (Next.js API Routes)
The core logic resides in helper functions and Next.js API routes. The starter project already has user authentication logic; you'll add the Twilio-specific parts.
Location: helpers/api/user-repo.js (Data access and Twilio logic),
pages/api/code/ (API endpoints)
Update Your Mongoose Schema: Ensure your Mongoose User schema (likely defined
in helpers/api/db.js or a similar location in the starter project) includes these fields:
- factorSid: { type: String } β Store the Twilio Factor SID after successful verification.
- authenticated: { type: Boolean, default: false } β Track if the user has completed the initial 2FA setup.
- keys: { type: Object } β Store factor.binding information temporarily (including the URI for the QR code) between factor creation and verification. CRITICAL SECURITY WARNING: See security notes below.
CRITICAL SECURITY WARNING β Storing Sensitive Factor Data:
The example code stores factor.binding (which includes binding.secret) temporarily
in the MongoDB keys field. This is NOT recommended for production due to these
security risks:
- Secret Exposure: The binding.secret is cryptographic material you should treat like a password. Storing it in plaintext in the database increases your attack surface.
- Compliance Risk: Storing secrets without encryption may violate security compliance standards (PCI DSS, SOC 2, etc.).
- Data Breach Impact: If your database is compromised, attackers gain access to TOTP secrets and can generate valid codes.
Production-Ready Alternatives:
- Session Storage (Recommended): Store the binding URI in server-side session storage (e.g., Redis, encrypted session cookies) instead of MongoDB. Clear the session after successful verification.
- Encryption at Rest: If database storage is required, encrypt the keys field using application-level encryption (AES-256) with proper key management (AWS KMS, Azure Key Vault, HashiCorp Vault).
- Time-Limited Tokens: Implement automatic cleanup of unverified factors after a short timeout (e.g., 15 minutes).
- No Storage: Pass the binding URI directly to the frontend after factor creation without storing it server-side. This requires the user to complete verification in the same session.
MongoDB Atlas provides encryption at rest by default, but application-level encryption provides additional defense-in-depth (source: MongoDB Security Best Practices).
Key Helper Functions (helpers/api/user-repo.js):
These functions interact directly with the Twilio Node.js SDK. Ensure the Twilio client is initialized (the starter project likely does this using the environment variables).
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const serviceSid = process.env.TWILIO_VERIFY_SERVICE_SID;
const client = require('twilio')(accountSid, authToken);
async function createFactor({ name, identity }) {
const user = await User.findById(identity);
if (!user) throw 'User not found';
if (!serviceSid) throw 'Twilio Verify Service SID not configured';
console.log(`Creating factor for identity: ${identity} in service: ${serviceSid}`);
try {
const factor = await client.verify.v2
.services(serviceSid)
.entities(identity.toString())
.newFactors.create({
friendlyName: `${name}'s Authy TOTP`,
factorType: 'totp'
});
console.log(`Factor created: ${factor.sid}`);
user.keys = factor.binding;
user.factorSid = factor.sid;
await user.save();
return factor;
} catch (error) {
console.error('Error creating Twilio factor:', error);
throw `Failed to create 2FA factor: ${error.message}`;
}
}
async function verifyNewFactor({ identity, code }) {
const user = await User.findById(identity);
if (!user) throw 'User not found';
if (!user.factorSid) throw 'Factor SID not found for user, cannot verify. Please try setup again.';
if (!serviceSid) throw 'Twilio Verify Service SID not configured';
console.log(`Verifying factor ${user.factorSid} for identity: ${identity} with code: ${code}`);
try {
const factor = await client.verify.v2
.services(serviceSid)
.entities(identity.toString())
.factors(user.factorSid)
.update({ authPayload: code });
console.log(`Factor verification status: ${factor.status}`);
if (factor.status === 'verified') {
user.authenticated = true;
user.keys = undefined;
await user.save();
console.log(`User ${identity} successfully verified and marked as authenticated.`);
} else {
console.log(`Factor verification failed for ${identity}. Status: ${factor.status}`);
throw 'Invalid verification code.';
}
return factor;
} catch (error) {
console.error(`Twilio API Error verifying factor (${error.code || 'N/A'}): ${error.message}`, { status: error.status });
let userMessage = `Failed to verify code: ${error.message || error}`;
if (error.code === 60202) {
userMessage = "Too many verification attempts. Please try again later.";
} else if (error.code === 60200 || error.status === 400) {
userMessage = "Invalid verification code format.";
} else if (error.code === 60203) {
userMessage = "Maximum verification attempts exceeded. Please wait before trying again.";
} else if (error.status === 404) {
userMessage = "Verification session expired or factor not found. Please try setting up 2FA again.";
} else if (error.status === 429) {
userMessage = "Too many requests. Please wait a moment and try again.";
}
throw userMessage;
}
}
async function createChallenge({ identity, factorSid, code }) {
const user = await User.findById(identity);
if (!user) throw 'User not found';
if (!factorSid) throw 'Factor SID is required for challenge.';
if (!serviceSid) throw 'Twilio Verify Service SID not configured';
if (!user.authenticated || user.factorSid !== factorSid) {
console.warn(`Challenge attempt failed: User ${identity} state invalid (authenticated: ${user.authenticated}, stored SID: ${user.factorSid}, provided SID: ${factorSid})`);
throw 'Invalid factor or user state for challenge.';
}
console.log(`Creating challenge for identity: ${identity}, factor: ${factorSid} with code: ${code}`);
try {
const challenge = await client.verify.v2
.services(serviceSid)
.entities(identity.toString())
.challenges.create({
authPayload: code,
factorSid: factorSid
});
console.log(`Challenge created: ${challenge.sid}, Status: ${challenge.status}`);
if (challenge.status !== 'approved') {
console.log(`Challenge for ${identity} not approved. Status: ${challenge.status}`);
throw 'Invalid verification code.';
}
console.log(`Challenge approved for ${identity}.`);
return challenge;
} catch (error) {
console.error(`Twilio API Error creating challenge (${error.code || 'N/A'}): ${error.message}`, { status: error.status });
let userMessage = `Failed to verify code: ${error.message || error}`;
if (error.code === 60202) {
userMessage = "Too many verification attempts. Please try again later.";
} else if (error.code === 60200 || error.status === 400) {
userMessage = "Invalid verification code format.";
} else if (error.code === 60203) {
userMessage = "Maximum verification attempts exceeded. Please wait before trying again.";
} else if (error.status === 404) {
userMessage = "Verification factor not found for this user.";
} else if (error.status === 429) {
userMessage = "Too many requests. Please wait a moment and try again.";
}
throw userMessage;
}
}
export const usersRepo = {
authenticate,
getAll,
getById,
create,
update,
delete: _delete,
createFactor,
verifyNewFactor,
createChallenge
};
API Endpoints (pages/api/code/):
Create the pages/api/code directory if it doesn't exist. Then create the following files:
pages/api/code/create.js(Creates the initial TOTP factor)
import { apiHandler, usersRepo } from 'helpers/api';
export default apiHandler({
post: createFactorHandler
});
async function createFactorHandler(req, res) {
const identity = req.body.identity;
const name = req.body.name;
if (!name || !identity) {
return res.status(400).json({ message: 'User name and identity are required' });
}
try {
const factor = await usersRepo.createFactor({ name, identity });
return res.status(200).json({
sid: factor.sid,
binding: {
uri: factor.binding?.uri
}
});
} catch (error) {
console.error("API Error creating factor:", error);
return res.status(500).json({ message: error.message || 'Failed to create factor' });
}
}
pages/api/code/verify.js(Verifies the factor after QR scan)
import { apiHandler, usersRepo } from 'helpers/api';
export default apiHandler({
post: verifyNewFactorHandler
});
async function verifyNewFactorHandler(req, res) {
const { identity, code } = req.body;
if (!identity || !code) {
return res.status(400).json({ message: 'User identity and code are required' });
}
try {
const factor = await usersRepo.verifyNewFactor({ identity, code });
return res.status(200).json({ status: factor.status });
} catch (error) {
console.error("API Error verifying factor:", error);
return res.status(400).json({ message: error.message || 'Verification failed' });
}
}
pages/api/code/challenge.js(Verifies code for subsequent logins)
import { apiHandler, usersRepo } from 'helpers/api';
export default apiHandler({
post: createChallengeHandler
});
async function createChallengeHandler(req, res) {
const { identity, factorSid, code } = req.body;
if (!identity || !factorSid || !code) {
return res.status(400).json({ message: 'Identity, factor SID, and code are required' });
}
try {
const challenge = await usersRepo.createChallenge({ identity, factorSid, code });
return res.status(200).json({ status: challenge.status });
} catch (error) {
console.error("API Error creating challenge:", error);
return res.status(400).json({ message: error.message || 'Verification failed' });
}
}
Explanation:
- We define asynchronous functions in user-repo.js that encapsulate the calls to the Twilio SDK (createFactor, verifyNewFactor, createChallenge). These handle finding the user, calling Twilio, updating the user record in MongoDB, and implementing enhanced error handling.
- Each API route (create.js, verify.js, challenge.js) imports the apiHandler (provides error handling, method routing) and the usersRepo.
- They define a handler function for the POST method, which calls the corresponding usersRepo function with data from the request body (req.body).
- Responses are sent back to the client, typically indicating success (status: 'verified' or status: 'approved') or failure with a user-friendly error message derived from the backend logic. We avoid sending sensitive data like the full factor or user object back to the client unnecessarily.
4. Frontend Service Implementation
The frontend service acts as an intermediary between the UI components and the backend API routes.
Location: services/user.service.js
Update this file to include functions that call the new API endpoints. The starter uses RxJS
(BehaviorSubject) for state management and a fetchWrapper for making API calls.
import { BehaviorSubject } from 'rxjs';
import getConfig from 'next/config';
import Router from 'next/router';
import { fetchWrapper } from 'helpers';
const { publicRuntimeConfig } = getConfig();
const baseUrl = `${publicRuntimeConfig.apiUrl}/users`;
const codeBaseUrl = `${publicRuntimeConfig.apiUrl}/code`;
const userSubject = new BehaviorSubject(process.browser && JSON.parse(localStorage.getItem('user')));
export const userService = {
user: userSubject.asObservable(),
get userValue() { return userSubject.value },
login,
logout,
register,
getAll,
getById,
update,
delete: _delete,
createFactor,
verifyNewFactor,
createChallenge
};
async function createFactor(name, identity) {
return await fetchWrapper.post(`${codeBaseUrl}/create`, { name, identity });
}
async function verifyNewFactor(identity, code) {
const response = await fetchWrapper.post(`${codeBaseUrl}/verify`, { identity, code });
if (response && response.status === 'verified') {
let storedUser = JSON.parse(localStorage.getItem('user'));
if (storedUser && storedUser.user) {
storedUser.user.authenticated = true;
localStorage.setItem('user', JSON.stringify(storedUser));
userSubject.next(storedUser);
console.log(""Local user state updated to authenticated."");
}
}
return response;
}
async function createChallenge(identity, factorSid, code) {
const response = await fetchWrapper.post(`${codeBaseUrl}/challenge`, { identity, factorSid, code });
if (response && response.status === 'approved') {
console.log(""Challenge approved."");
}
return response;
}
Explanation:
- We add three new async functions: createFactor, verifyNewFactor, and createChallenge.
- Each function uses the fetchWrapper (provided by the starter) to make a POST request to the corresponding API endpoint created in the previous step (/api/code/\*).
- They pass the required data (identity, name, code, factorSid) in the request body.
- verifyNewFactor has additional logic: upon successful verification (response.status === 'verified'), it updates the user object stored in localStorage and notifies any subscribers via userSubject.next() to reflect the authenticated: true state. This ensures the UI reacts correctly.
- createChallenge primarily relies on the API response to determine success; routing logic in the component usually handles the next step upon approval.
5. Frontend UI Implementation
We need to modify the login page logic and create two new pages: one to scan the QR code
(scan.js) and one to enter the TOTP code (code.js).
1. Modify Login Page (pages/account/login.js):
Update the onSubmit function to route users based on their authenticated status
after successful password login.
export default Login;
function Login() {
const router = useRouter();
async function onSubmit({ username, password }) {
alertService.clear();
try {
await userService.login(username, password);
const user = userService.userValue?.user;
if (user) {
if (user.authenticated) {
console.log("User authenticated, redirecting to code entry.");
const returnUrl = router.query.returnUrl || '/dashboard';
router.push({ pathname: '/account/code', query: { returnUrl } });
} else {
console.log("User not authenticated, redirecting to QR scan setup.");
router.push('/account/scan');
}
} else {
console.error("User data not found after successful login.");
alertService.error('Login succeeded but user data is missing. Please try again.');
}
} catch (error) {
alertService.error(error);
}
}
}
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 β