Frequently Asked Questions
Integrate Infobip's 2FA by setting up API routes in your Next.js application to handle the backend logic for sending and verifying OTPs. Use the Infobip Node.js SDK to interact with the Infobip API and manage the OTP workflow securely. The frontend will communicate with these API routes using fetch requests.
Next.js API routes act as a secure intermediary between the frontend and the Infobip API. They handle requests from the frontend, interact with the Infobip API using your secure credentials, and send responses back to the frontend, ensuring that sensitive information is not exposed directly to the client-side.
Infobip enhances security by adding 2FA, verifying user identity through phone number validation, and helping prevent fraudulent account creation. It utilizes OTPs sent via SMS, adding an extra layer of security beyond traditional passwords.
Implement Infobip OTP/2FA during user registration or login to verify user identity, and for transaction confirmations to enhance security and prevent fraud. This adds an extra layer of protection beyond passwords, safeguarding sensitive actions within your app.
Yes, the Infobip Node.js SDK is compatible with both Next.js Pages Router and App Router. The core logic remains the same, but file paths and routing configuration might slightly differ based on the chosen routing approach.
Create a .env.local file in the project root to store your Infobip API key, Base URL, App ID, and Message ID. Next.js loads these into process.env server-side, keeping your secrets secure. Never commit .env.local to version control.
Configure 2FA in the Infobip portal by first getting your API key and Base URL. Next, create a 2FA application, set up its parameters like maximum attempts, and finally create a message template defining the SMS content with the {{pin}} placeholder.
Implement try...catch blocks in your API routes to handle errors during OTP sending and verification. Use a structured logger to record detailed error information server-side and return generic, user-friendly error messages to the client.
Protect API keys with environment variables, implement server-side input validation and rate limiting, consider secure pinId handling methods, use HTTPS, and understand CSRF risks. These measures safeguard against common vulnerabilities.
Test with Infobip's test numbers or sandbox if available, and conduct unit tests for API routes, mocking the Infobip SDK. Implement integration tests for frontend-backend interaction, and consider end-to-end tests for staging or production environments.
Your Infobip Base URL is region-specific and can be located on the homepage of your Infobip portal. It's essential for configuring the Infobip client and ensuring successful API requests.
The pinId, returned by Infobip after initiating an OTP send request, is crucial for verifying the user-entered OTP. It identifies a specific OTP transaction.
Ensure you have Node.js, npm/yarn, an active Infobip account, basic understanding of Next.js and React, and a text editor. These prerequisites are essential for setting up and integrating Infobip's 2FA service.
Sending the pinId to the client presents a security risk as it exposes this identifier. A more secure approach is to store it server-side and retrieve it based on the user's session during verification, preventing potential misuse.
Developer Guide: Implementing Infobip OTP/2FA in Next.js with Node.js
Learn how to build secure SMS-based two-factor authentication (2FA) in Next.js applications using Infobip's API. This comprehensive tutorial covers implementing OTP verification for user registration, login security, and transaction confirmation with complete code examples and production-ready patterns.
⚠️ Critical Security Notice:
Before implementing SMS-based 2FA, understand these security limitations:
Recommended Alternatives: For higher security requirements, consider implementing TOTP (Time-based One-Time Password) apps, WebAuthn/FIDO2, or hardware security keys alongside or instead of SMS.
What You'll Build: A complete SMS OTP authentication system that sends verification codes via Infobip's messaging service and validates user input through secure API routes.
Real-World Use Cases:
Business Benefits:
Master the complete implementation process including Infobip API configuration, secure Next.js API route development, React component creation, and production deployment best practices. Perfect for developers building authentication systems, e-commerce checkout flows, or any application requiring phone number verification.
For more Next.js authentication patterns, check out our guide on implementing JWT authentication in Next.js and building secure user registration systems.
Building SMS Authentication: Project Overview
What We're Building:
We will implement a feature where a user can enter their phone number, receive an OTP via SMS powered by Infobip, and then verify that OTP within the Next.js application. This forms the core of a 2FA or phone verification system.
Problem Solved:
Compliance and Regulatory Requirements:
GDPR Compliance: Phone numbers constitute personal data requiring valid legal basis (consent or legitimate interest). For transactional OTP messages, these are considered necessary service communications and don't require advertising consent. However, you must implement proper data retention policies and honor data subject rights including data portability and erasure requests.
PCI-DSS Requirements: Payment processing systems often mandate multi-factor authentication for sensitive operations. SMS OTP satisfies PCI-DSS requirements for "something you have" authentication factors.
Data Retention: Under GDPR, organizations must define retention periods for personal data and automate deletion when retention periods expire or upon data subject request.
Enhanced Security: Adds a second layer of authentication beyond passwords, with ENISA recommending 2FA implementation for high-risk cases involving personal data processing.
User Verification: Confirms user identity by validating phone number ownership.
Fraud Prevention: Helps prevent fake account creation and secures transactions. Financial institutions report up to 99.9% reduction in account takeover attacks when implementing proper 2FA systems.
Technologies Involved:
System Architecture:
The flow involves three main components:
Prerequisites:
For additional Next.js setup guidance_ see our Next.js development environment setup guide and React authentication patterns tutorial.
Security Prerequisites:
1. Next.js Project Setup for SMS Authentication
Follow these step-by-step instructions to set up your Next.js project with all required dependencies for SMS authentication.
1.1 Create Next.js Project:
Open your terminal and run:
1.2 Install Infobip Node.js SDK:
This SDK provides convenient methods for interacting with the Infobip API.
1.3 Environment Variables:
We need to store sensitive Infobip credentials securely. Create a file named
.env.localin the root of your project. Never commit this file to version control.Essential .gitignore Setup:
First_ ensure your
.gitignorefile includes all environment files:Create Environment Template:
For team collaboration_ create
.env.examplewith the structure but no sensitive values:.env.local? Next.js automatically loads variables from this file intoprocess.envon the server side (API routes), keeping your secrets out of the frontend bundle and source control.1.4 Project Structure:
Your basic structure (using Pages Router for simplicity in examples, adapt if using App Router):
2. Infobip SMS API Configuration Guide
Before writing code, we need to configure the necessary components within the Infobip platform.
2.1 Obtain API Key and Base URL:
Log in to your Infobip Portal.
Base URL: On the homepage, locate your API Base URL. It's region-specific (e.g.,
xxxxx.api.infobip.com).Region Selection Guidance:
Copy this value into
INFOBIP_BASE_URLin your.env.local.API Key:
API Key Management. Note: The exact name and location of this section within the Infobip Portal UI might change over time. Look for settings related to API access or developer tools.Create API Key.Nextjs OTP App - Production).Submit. Copy the generated API key immediately, as it won't be shown again. Paste it intoINFOBIP_API_KEYin your.env.local.API Key Rotation Best Practices:
2.2 Create a 2FA Application:
This defines the rules for your OTP flow (e.g., how many attempts are allowed, how long the OTP is valid).
Appssection (or search for2FA Applications).Create Application.My Next.js App Verification).pinAttempts: Max number of verification attempts (recommended:3-5). Impact: Higher values increase user convenience but reduce security. Lower values may cause user frustration with legitimate typos.allowMultiplePinVerifications:false(recommended). Impact: Set tofalsefor security - each PIN can only be verified once. Setting totrueallows reuse of the same PIN multiple times within the TTL window.pinTimeToLive: How long the OTP is valid (recommended:5mfor 5 minutes). Impact: Shorter TTL increases security but may frustrate users. Longer TTL improves UX but extends vulnerability window.verifyPinLimit: Rate limit for verification attempts (recommended:1/3s- 1 attempt per 3 seconds). Impact: Prevents brute force attacks while allowing reasonable retry intervals.sendPinPerApplicationLimit: Global rate limit (e.g.,10000/1d- 10,000 per day). Cost Impact: This directly affects your SMS costs. At ~$0.0079 per US SMS, 10,000 daily messages ≈ $79/day or $2,400/month.sendPinPerPhoneNumberLimit: Per-number limit (recommended:3-5/1d- 3-5 per day per number). Impact: Prevents abuse while allowing legitimate retries. Higher limits increase spam potential and costs.true.Submit.applicationId). Paste this intoINFOBIP_2FA_APP_IDin your.env.local.2.3 Create a 2FA Message Template:
This defines the content of the SMS message sent to the user, including the OTP placeholder.
Message Templatessection.Create Message Template.NUMERIC(most common).{{pin}}placeholder where the OTP should be inserted. Example:Your verification code for My App is {{pin}}. It expires in 5 minutes.6). Remember this value for validation.InfoSMSor configure a custom one if available on your account.enfor English).Submit.messageId). Paste this intoINFOBIP_2FA_MESSAGE_IDin your.env.local.3. Building SMS OTP API Endpoints in Next.js
Now, let's create the backend endpoints that our frontend will call.
3.1 Initialize Infobip Client:
It's good practice to create a utility function or singleton instance for the Infobip client.
Create
lib/infobip.js(or.ts):3.2 API Route: Send OTP (
/api/send-otp)This route receives a phone number, uses the Infobip SDK to send an OTP, and returns the
pinIdneeded for verification.3.3 API Route: Verify OTP (
/api/verify-otp)This route receives the
pinId(obtained from the send step) and thepinentered by the user. It calls Infobip to verify.API Testing (Example using
curl):Replace placeholders with actual values. Remember to start your Next.js development server (
npm run devoryarn dev).Send OTP:
Expected Response (Success):
{""pinId"":""SOME_PIN_ID_FROM_INFOBIP""}Expected Response (Error):{ ""message"": ""Specific error message..."" }(with appropriate status code)Verify OTP (using
pinIdfrom above and the received SMS code):Expected Response (Success):
{""verified"": true, ""message"": ""OTP verified successfully.""}Expected Response (Invalid PIN):{""verified"": false, ""message"": ""Invalid or expired OTP.""}(or more specific error)4. Creating the OTP Verification UI Components
Now, let's create a simple UI for users to interact with our OTP flow.
5. Production Error Handling and Monitoring
try...catchblocks.console.logandconsole.errorwith a dedicated, structured logging library (e.g., Pino, Winston) or integrate with a logging service (e.g., Sentry, Logtail, Datadog). This allows for better filtering, searching, and alerting in production. Log detailed error information server-side, including Infobip's response data when available (error.response.data).429, invalid credentials401, etc.) by checkingerror.response.statusanderror.response.data.requestError.serviceException.messageId.try...catcharoundfetchcalls. Display clear messages to the user based on API responses. Provide ways to retry (like the ""Resend OTP"" button) or restart the process.async-retry). Be cautious with retrying OTP sends to avoid spamming users or hitting rate limits quickly. Exponential backoff is generally recommended for retrying external API calls.6. SMS Authentication Security Best Practices
.env.localfor local development) and never expose your API key in frontend code or commit it to version control. Configure restricted permissions (least privilege principle) and consider IP allowlisting for your Infobip API key in production.verifyPinLimit,sendPinPerPhoneNumberLimit,sendPinPerApplicationLimit) in your Infobip 2FA Application settings to prevent abuse at the source./api/send-otpand/api/verify-otpendpoints to protect your own server resources. Libraries likerate-limiter-flexibleorexpress-rate-limit(adapted for Next.js API routes) can be used. Hosting platforms like Vercel also offer built-in rate limiting features.pinIdpresence) on the server-side (API routes). Do not rely solely on frontend validation, as it can be bypassed. Use robust libraries likelibphonenumber-jsfor phone numbers.pinIdto the client and back. This is simpler to implement but less secure, as thepinIdis exposed. An attacker who obtains apinIdcould potentially attempt to guess the PIN by directly calling your/api/verify-otpendpoint (though Infobip's rate limits offer protection).pinIdto the client. Instead, store thepinIdserver-side immediately after the/api/send-otpcall. Associate it with the user's session (e.g., usingnext-author encrypted cookies) or a temporary secure cache (like Redis) keyed by session ID or phone number, with a TTL matching Infobip'spinTimeToLive. When the user submits the OTP to/api/verify-otp, retrieve the correctpinIdfrom the server-side storage based on their session/context and then call Infobip. This preventspinIdexposure but adds server-side state management complexity.pinAttemptssetting provides primary protection against guessing the OTP. Your API route rate limiting adds another layer of defense against hammering the verification endpoint.7. Testing SMS OTP Implementation
send-otp.js,verify-otp.js). Mock theinfobip-api-nodejs-sdkusingjest.mockor similar techniques to simulate:pinId).verified: true).verified: false).pinId).fetchcalls in your frontend tests or run against a live development server (potentially mocking the Infobip SDK at the API level).This validates the entire system, including the actual Infobip integration, but can be more complex and costly to set up and run.
8. Deploying Your Next.js OTP System to Production
When deploying your SMS OTP authentication system, consider these platform-specific configurations:
Vercel Deployment (Recommended for Next.js):
INFOBIP_*variables in Vercel dashboard under Project Settings → Environment VariablesEnvironment Variable Management:
Performance Optimization:
Monitoring and Alerting:
9. Common Issues and Troubleshooting
Issue: "Missing required environment variables" error
.env.localand properly loaded by Next.jsIssue: SMS not received by users
Issue: "Invalid credentials" or 401 errors
.env.localxxxxx.api.infobip.com)Issue: Rate limit errors (429 status)
sendPinPerPhoneNumberLimitandsendPinPerApplicationLimitsettings in Infobip 2FA ApplicationIssue: OTP verification always fails
pinTimeToLivesetting—OTP may be expiring too quicklypinIdis correctly passed from send to verify API route10. Next Steps and Advanced Features
Enhance Your Implementation:
Security Hardening:
pinIdmanagementUser Experience Improvements:
navigator.credentials.get())Related Guides: