Introduction
Security is no longer a luxury; it is a fundamental requirement for any modern web application. Two-Factor Authentication (2FA) via SMS remains one of the most effective ways to protect user accounts from unauthorized access.
Prerequisites
Before we dive into the code, ensure you have the following ready:
- Node.js (v16.x or higher) installed on your machine.
- A TXTMSG SMS Gateway account with an active API Key.
- Basic knowledge of Express.js and asynchronous JavaScript.
Setting up TXTMSG
First, obtain your credentials from the TXTMSG Dashboard. You will need your API_SECRET and BRAND_ID. These will authenticate your requests to our global delivery network.
Core Implementation
We will use a simple Express endpoint to trigger the verification SMS. The key here is to generate a cryptographically secure 6-digit OTP and transmit it through the TXTMSG ultra-low latency routes.
const express = require("express");
const TXTMSG = require("@txtmsg/sdk");
const client = new TXTMSG.Client({
apiKey: process.env.TXTMSG_API_KEY,
apiSecret: process.env.TXTMSG_SECRET
});
app.post("/api/auth/2fa/send", async (req, res) => {
const { phoneNumber } = req.body;
const otp = Math.floor(100000 + Math.random() * 900000);
try {
const response = await client.messages.send({
to: phoneNumber,
from: "TXTMSG",
text: "Your security code is: " + otp
});
req.session.otp = otp;
res.status(200).json({ success: true, messageId: response.id });
} catch (error) {
res.status(500).json({ error: "Delivery failed" });
}
});Security Best Practices
When implementing 2FA, consider these professional-grade measures:
- Rate Limiting: Prevent brute force by limiting a user to 3 attempts every 15 minutes.
- Masking: Always mask the phone number in the UI to protect PII.
- Sender IDs: Use a verified Alpha Sender ID to increase trust and open rates.