Developer Quick-Start: Complete guide to building production-ready SMS-based OTP/2FA system using Node.js, Fastify, TypeScript, and Infobip API 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.
This guide provides a step-by-step walkthrough for building a production-ready SMS-based One-Time Password (OTP) or Two-Factor Authentication (2FA) system using Node.js, the Fastify framework, and the Infobip API. We will cover everything from initial project setup to deployment considerations and troubleshooting.
By following this guide, you will create a secure and reliable mechanism to verify user phone numbers via SMS, enhancing application security during registration, login, or critical actions.
Project Overview and Goals
What We're Building:
We will build a backend API using Fastify that exposes endpoints for:
- Initiating OTP: Sending an SMS containing a unique code to a user's phone number via Infobip.
- Verifying OTP: Validating the code submitted by the user against the one sent.
Problem Solved:
This implementation addresses the need for robust user verification, mitigating risks like account takeover, fake registrations, and unauthorized access by confirming possession of a specific phone number.
Technologies Used:
- Node.js: The JavaScript runtime environment.
- Fastify: A high-performance, low-overhead web framework for Node.js. Chosen for its speed, extensibility, and developer-friendly features like built-in validation and logging.
- TypeScript: Adds static typing to JavaScript, improving code quality, maintainability, and developer productivity.
- Infobip: A global communication platform providing APIs for various channels, including SMS. We'll use their 2FA API specifically designed for OTP workflows.
- Prisma: A modern database toolkit for Node.js and TypeScript, simplifying database access, migrations, and type safety.
- PostgreSQL: A powerful, open-source relational database (though Prisma supports others).
- Axios: A promise-based HTTP client for making requests to the Infobip API.
- dotenv / @fastify/env: For managing environment variables securely.
- bcrypt: For securely hashing passwords (if implementing user registration).
- @fastify/rate-limit: To protect against brute-force attacks.
System Architecture:
+-------------+ +-----------------+ +-------------+ +-----------------+
| End User | <---> | Fastify API | <---> | Infobip API | <---> | User's Phone |
| (Browser/App)| | (Node.js) | | (2FA Service) | | (Receives SMS) |
+-------------+ +--------+--------+ +-------------+ +-----------------+
|
|
+-----+-----+
| Database |
| (PostgreSQL)|
+-----------+
- The user initiates an action requiring OTP (e.g., enters phone number).
- The Fastify API receives the request.
- The Fastify API calls the Infobip 2FA API to generate and send an OTP SMS.
- Infobip sends the SMS to the user's phone.
- The user receives the OTP and submits it back to the Fastify API.
- The Fastify API calls the Infobip 2FA API to verify the submitted PIN.
- Infobip confirms if the PIN is valid.
- The Fastify API responds to the user, granting or denying access/verification.
- OTP attempt data is stored/updated/deleted in the database.
Prerequisites:
- Node.js (v18 or later recommended) and npm/yarn installed. Install Node.js
- An active Infobip account. Create Infobip Account
- Access to a PostgreSQL database (local or cloud-hosted). Docker is a convenient way to run one locally. Install Docker
- Basic understanding of TypeScript, Node.js, REST APIs, and asynchronous programming.
Final Outcome:
A Fastify application with API endpoints capable of sending and verifying SMS OTPs using Infobip, including basic security measures and database integration.
1. Setting up the Project
Let's initialize our Fastify project with TypeScript, Prisma, and necessary dependencies.
1.1 Initialize Project & Install Core Dependencies:
Open your terminal and run the following commands:
mkdir fastify-infobip-otp
cd fastify-infobip-otp
npm init -y
npm install fastify typescript @types/node ts-node-dev --save-dev
npm install @fastify/env @fastify/sensible
npx tsc --init --rootDir src --outDir dist --esModuleInterop --resolveJsonModule --lib esnext --module commonjs --allowJs true --noImplicitAny true
Explanation:
- npm init -y: Creates a basic package.json.
- fastify: The core framework.
- typescript, @types/node: TypeScript compiler and Node.js types.
- ts-node-dev: Utility for running TypeScript projects with auto-reloading during development.
- @fastify/env: Plugin for loading and validating environment variables.
- @fastify/sensible: Adds useful defaults like error handling and headers.
- tsc --init ...: Creates a tsconfig.json file configured for our project structure (src for source, dist for compiled output).
1.2 Configure package.json Scripts:
Update the scripts section in your package.json:
{
"name": "fastify-infobip-otp",
"version": "1.0.0",
"description": "Infobip OTP implementation with Fastify",
"main": "dist/server.js",
"scripts": {
"build": "tsc",
"start": "node dist/server.js",
"dev": "ts-node-dev --respawn --transpile-only --exit-child src/server.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"fastify",
"infobip",
"otp",
"2fa",
"typescript",
"prisma"
],
"author": "",
"license": "ISC"
}
Explanation:
- build: Compiles TypeScript code to JavaScript in the dist directory.
- start: Runs the compiled JavaScript application (for production).
- dev: Runs the application using ts-node-dev for development, automatically restarting on file changes.
- test: Placeholder for running automated tests (not implemented in detail in this guide).
1.3 Project Structure:
Create the following directories and files:
fastify-infobip-otp/
βββ prisma/
β βββ schema.prisma # Database schema definition
βββ src/
β βββ plugins/ # Fastify plugins (env, sensible, etc.)
β βββ modules/ # Feature modules (e.g., auth, otp)
β β βββ otp/
β β βββ otp.routes.ts # API routes for OTP
β β βββ otp.service.ts # Business logic for OTP (Infobip interaction)
β βββ lib/ # Shared libraries (e.g., prisma client)
β β βββ prisma.ts # Prisma client instance
β βββ server.ts # Main application entry point
βββ .env # Environment variables (DO NOT COMMIT)
βββ .env.example # Example environment variables
βββ .gitignore # Files/folders to ignore in git
βββ package.json
βββ package-lock.json
βββ tsconfig.json
Explanation:
- This structure promotes modularity and separation of concerns.
- plugins: Encapsulates Fastify plugin registrations.
- modules: Contains specific application features (like OTP handling). Each module typically has routes, services, schemas, etc.
- lib: Holds shared utilities like the configured Prisma client.
1.4 Setup Environment Variables:
Create .env.example and .env files.
DATABASE_URL="postgresql://user:password@host:port/database?schema=public"
INFOBIP_BASE_URL="<YOUR_INFOBIP_API_BASE_URL>"
INFOBIP_API_KEY="<YOUR_INFOBIP_API_KEY>"
INFOBIP_APPLICATION_ID="<YOUR_INFOBIP_2FA_APP_ID>"
INFOBIP_MESSAGE_ID="<YOUR_INFOBIP_2FA_MESSAGE_ID>"
cp .env.example .env
Add .env and dist to your .gitignore:
# .gitignore
node_modules
dist
.env
npm-debug.log*
yarn-debug.log*
yarn-error.log*
Obtaining Infobip Credentials:
- API Key & Base URL:
- Log in to your Infobip Portal.
- Navigate to the "Developers" section or your account settings.
- Your unique Base URL (e.g., xxxxx.api.infobip.com) should be displayed.
- Generate an API Key if you haven't already. Securely copy both the Base URL and the API Key.
- Path: Look for "API Keys" under account/developer settings. The Base URL is often shown prominently on the dashboard's developer section.
- Application ID & Message ID:
- These are specific to Infobip's 2FA service. You need to create a "2FA Application" and a "2FA Message Template" within that application via the Infobip Portal or their API.
- Portal Method:
- Navigate to Apps -> 2FA.
- Click "Create Application". Configure settings like PIN attempts, time-to-live (TTL - e.g., 300 seconds for 5 minutes), etc. Save it. Copy the generated Application ID.
- Inside the application, click "Create Message Template". Define the message text (e.g., Your verification code is {{pin}}), PIN type (Numeric), PIN length, etc. Save it. Copy the generated Message ID.
- Path: Navigate to Apps -> 2FA. The "Create Application" and "Create Message Template" buttons are usually prominent here. The IDs are displayed after creation.
- API Method: We'll cover creating these via API later as an alternative/programmatic approach in the otp.service.ts section, but for initial setup, using the portal is easier.
1.5 Install Database (Prisma) & HTTP Client (Axios):
npm install @prisma/client axios
npm install prisma --save-dev
1.6 Initialize Prisma:
npx prisma init --datasource-provider postgresql
This creates the prisma/schema.prisma file and updates .env with a placeholder
DATABASE_URL. Ensure your actual DATABASE_URL in .env points to your
running PostgreSQL instance.
1.7 Define Basic Prisma Schema:
Modify prisma/schema.prisma:
Prisma
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL") // Loads from .env
}
// Optional: Basic User model if you need registration
// model User {
// id String @id @default(cuid())
// email String @unique
// password String // Store hashed password
// phone String? @unique // User's phone number - consider if uniqueness is truly required globally
// isPhoneVerified Boolean @default(false)
// createdAt DateTime @default(now())
// updatedAt DateTime @updatedAt
// }
// Model to temporarily store OTP details (link pinId to a user/phone)
model OtpAttempt {
id String @id @default(cuid())
phone String // Phone number OTP was sent to
pinId String @unique // The pinId received from Infobip
expiresAt DateTime // When the OTP expires (based on Infobip TTL)
createdAt DateTime @default(now())
@@index([phone]) // Index for faster lookups by phone
}
Explanation:
- We define an OtpAttempt model to store the pinId returned by Infobip when an OTP is sent. This is crucial for the verification step. We link it to the phone number and add an expiry time.
- A basic User model is commented out β uncomment and adapt if you are building full user registration. Note the comment on phone @unique: consider carefully if a phone number must be unique across all users in your application, as this might prevent legitimate scenarios like shared family numbers or number reuse over time.
- An index is added to OtpAttempt.phone to speed up lookups during verification.
1.8 Create Initial Database Migration:
Ensure your database server is running and accessible using the DATABASE_URL specified in
.env.
npx prisma migrate dev --name init
This command:
- Creates SQL migration files in prisma/migrations.
- Applies the migration to your database, creating the OtpAttempt table (and User table if uncommented).
- Generates the Prisma Client based on your schema.
1.9 Setup Basic Fastify Server:
Create src/server.ts:
import Fastify from 'fastify';
import sensible from '@fastify/sensible';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import envPlugin from './plugins/env';
import otpRoutes from './modules/otp/otp.routes';
import { prisma } from './lib/prisma';
declare module 'fastify' {
interface FastifyInstance {
prisma: typeof prisma;
config: any;
}
}
async function buildServer() {
const server = Fastify({
logger: true,
}).withTypeProvider<TypeBoxTypeProvider>();
await server.register(envPlugin);
await server.register(sensible);
server.decorate('prisma', prisma);
await server.register(otpRoutes, { prefix: '/api/otp' });
server.get('/health', async () => {
return { status: 'ok', timestamp: new Date().toISOString() };
});
server.addHook('onClose', async () => {
server.log.info('Server shutting down...');
await prisma.$disconnect();
server.log.info('Prisma client disconnected.');
});
return server;
}
async function start() {
const server = await buildServer();
try {
const port = server.config.PORT;
await server.listen({ port: port, host: '0.0.0.0' });
['SIGINT', 'SIGTERM'].forEach((signal) => {
process.on(signal, async () => {
await server.close();
});
});
} catch (err) {
server.log.error(err);
await prisma.$disconnect();
process.exit(1);
}
}
start();
1.10 Setup Environment Variable Loading:
First, install TypeBox dependencies:
npm install @sinclair/typebox @fastify/type-provider-typebox
Now, create src/plugins/env.ts:
import fp from 'fastify-plugin';
import fastifyEnv, { FastifyEnvOptions } from '@fastify/env';
import { Static, Type } from '@sinclair/typebox';
const EnvSchema = Type.Object({
DATABASE_URL: Type.String(),
INFOBIP_BASE_URL: Type.String({ format: 'uri' }),
INFOBIP_API_KEY: Type.String(),
INFOBIP_APPLICATION_ID: Type.String(),
INFOBIP_MESSAGE_ID: Type.String(),
PORT: Type.Optional(Type.Number({ default: 3000 })),
OTP_TTL_MINUTES: Type.Optional(Type.Number({ default: 5 }))
});
type EnvConfig = Static<typeof EnvSchema>;
declare module 'fastify' {
interface FastifyInstance {
config: EnvConfig;
}
}
export default fp(async (fastify) => {
const options: FastifyEnvOptions = {
confKey: 'config',
schema: EnvSchema,
dotenv: true,
data: process.env
};
await fastify.register(fastifyEnv, options);
fastify.log.info('Environment variables loaded and validated.');
}, { name: 'env-plugin' });
1.11 Setup Prisma Client Instance:
Create src/lib/prisma.ts:
import { PrismaClient } from '@prisma/client';
export const prisma = new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'info', 'warn', 'error'] : ['error'],
});
Project Setup Complete:
At this point, you have a basic Fastify application structure with TypeScript, environment variable loading,
Prisma configured, and the initial database migration applied. You can run npm run dev to start
the development server. It won't do much yet beyond a health check, but it confirms the basic setup is
working.
2. Implementing Core Functionality (OTP Service)
Now, let's implement the service that interacts with the Infobip 2FA API.
Create src/modules/otp/otp.service.ts:
import axios, { AxiosInstance, AxiosError } from 'axios';
import { prisma } from '../../lib/prisma';
import { FastifyInstance } from 'fastify';
interface InfobipConfig {
baseURL: string;
apiKey: string;
applicationId: string;
messageId: string;
otpTtlMinutes: number;
}
interface InfobipSendResponse {
pinId: string;
to: string;
ncStatus: string;
smsStatus: string;
}
interface InfobipVerifyResponse {
pinId: string;
verified: boolean;
msisdn: string;
attemptsRemaining: number;
}
interface InfobipErrorResponse {
requestError?: {
serviceException?: {
messageId: string;
text: string;
validationErrors?: Record<string, string>;
};
};
}
export class OtpService {
private axiosInstance: AxiosInstance;
private config: InfobipConfig;
private logger: FastifyInstance['log'];
constructor(config: InfobipConfig, logger: FastifyInstance['log']) {
this.config = config;
this.logger = logger;
this.axiosInstance = axios.create({
baseURL: config.baseURL,
headers: {
'Authorization': `App ${config.apiKey}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
this.axiosInstance.interceptors.response.use(
response => response,
(error: AxiosError<InfobipErrorResponse>) => {
const errorData = error.response?.data?.requestError?.serviceException;
this.logger.error({
msg: 'Infobip API Error',
status: error.response?.status,
code: errorData?.messageId,
text: errorData?.text,
url: error.config?.url,
}, `Infobip API request failed: ${errorData?.text || error.message}`);
return Promise.reject(new Error(errorData?.text || 'Infobip API request failed'));
}
);
}
async sendOtp(phone: string, language?: string): Promise<string> {
const url = `/2fa/2/pin`;
const requestBody = {
applicationId: this.config.applicationId,
messageId: this.config.messageId,
from: "InfoSMS",
to: phone,
...(language && { language }),
};
this.logger.info(`Sending OTP to ${phone} using AppID: ${this.config.applicationId}, MsgID: ${this.config.messageId}`);
try {
const response = await this.axiosInstance.post<InfobipSendResponse>(url, requestBody);
const { pinId } = response.data;
const expiresAt = new Date(Date.now() + this.config.otpTtlMinutes * 60 * 1000);
await prisma.$transaction([
prisma.otpAttempt.deleteMany({
where: { phone: phone }
}),
prisma.otpAttempt.create({
data: {
phone,
pinId,
expiresAt,
}
})
]);
this.logger.info(`Successfully sent OTP to ${phone}, pinId: ${pinId} stored.`);
return pinId;
} catch (error: any) {
this.logger.error(`Failed to send OTP to ${phone}: ${error.message}`);
throw new Error(`Failed to send OTP: ${error.message}`);
}
}
async verifyOtp(pinId: string, pin: string): Promise<boolean> {
const url = `/2fa/2/pin/${pinId}/verify`;
const requestBody = { pin };
this.logger.info(`Verifying OTP for pinId: ${pinId}`);
try {
const otpAttempt = await prisma.otpAttempt.findUnique({
where: { pinId },
});
if (!otpAttempt) {
this.logger.warn(`Verification attempt for non-existent or already verified pinId: ${pinId}`);
return false;
}
if (new Date() > otpAttempt.expiresAt) {
this.logger.warn(`Verification attempt for expired pinId: ${pinId}`);
await prisma.otpAttempt.delete({ where: { pinId } }).catch(e => this.logger.error(e, "Failed to cleanup expired OTP attempt"));
return false;
}
const response = await this.axiosInstance.post<InfobipVerifyResponse>(url, requestBody);
const { verified, attemptsRemaining } = response.data;
this.logger.info(`Verification result for pinId ${pinId}: ${verified}, attempts remaining: ${attemptsRemaining}`);
if (verified) {
await prisma.otpAttempt.delete({
where: { pinId },
});
this.logger.info(`Successfully verified and removed OTP record for pinId: ${pinId}`);
} else {
if (attemptsRemaining <= 0) {
this.logger.warn(`OTP verification failed for pinId ${pinId} - maximum attempts reached.`);
await prisma.otpAttempt.delete({ where: { pinId } }).catch(e => this.logger.error(e, "Failed to cleanup exhausted OTP attempt"));
}
}
return verified;
} catch (error: any) {
const axiosError = error as AxiosError<InfobipErrorResponse>;
const errCode = axiosError.response?.data?.requestError?.serviceException?.messageId;
const errText = axiosError.response?.data?.requestError?.serviceException?.text;
this.logger.error(`Failed to verify OTP for pinId ${pinId}: ${errText || error.message} (Code: ${errCode})`);
if (axiosError.response?.status === 400 || axiosError.response?.status === 404) {
if (errCode === 'PIN_EXPIRED' || errCode === 'PIN_NOT_FOUND' || errCode === 'WRONG_PIN') {
if (errCode === 'PIN_EXPIRED' || errCode === 'PIN_NOT_FOUND') {
const attemptExists = await prisma.otpAttempt.findUnique({ where: { pinId }, select: { id: true } });
if (attemptExists) {
await prisma.otpAttempt.delete({ where: { pinId } }).catch(e => this.logger.error(e, "Failed to cleanup invalid/expired OTP attempt"));
}
}
}
return false;
}
throw new Error(`Failed to verify OTP: ${errText || error.message}`);
}
}
async createApplication(name: string, configuration: any) {
const url = `/2fa/2/applications`;
const requestBody = { name, configuration, enabled: true };
this.logger.info(`Attempting to create 2FA Application: ${name}`);
try {
const response = await this.axiosInstance.post(url, requestBody);
this.logger.info(`Successfully created 2FA Application ${name}`, response.data);
return response.data;
} catch (error: any) {
this.logger.error(`Failed to create 2FA Application ${name}: ${error.message}`);
throw error;
}
}
async createMessageTemplate(applicationId: string, messageText: string, pinType: string, pinLength: number) {
const url = `/2fa/2/applications/${applicationId}/messages`;
const requestBody = {
messageText,
pinType,
pinLength,
};
this.logger.info(`Attempting to create Message Template for AppID: ${applicationId}`);
try {
const response = await this.axiosInstance.post(url, requestBody);
this.logger.info(`Successfully created Message Template for AppID ${applicationId}`, response.data);
return response.data;
} catch (error: any) {
this.logger.error(`Failed to create Message Template for AppID ${applicationId}: ${error.message}`);
throw 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 β