Implement SMS-based OTP in Node.js using a third-party verification API after the storefront's password check, with a server-controlled template and destination suppression checked before every send. Template ownership decides who can change the message, who generates the code, and which evidence your team needs when a shopper cannot sign in.
TL;DR: In Node.js, keep third-party credentials on the server, bind each provider challenge to a pending login, and grant access only after successful verification and atomic challenge consumption. Track permanent destination failures separately from expired codes. An email bounce must never become an automatic block on that customer's phone number.
The useful operational question is specific: can support explain why a login text was attempted, which approved template produced it, and why another text was suppressed? Build that evidence into the flow. Keep the code itself out of it.
What does template ownership change in a storefront login?
Start with the message contract. A verification service can own code generation, expiration, and checking while your application owns the approved wording and the decision to initiate a challenge. Another arrangement lets the application generate and validate codes while a messaging service delivers the text. Both require deliberate security controls. This note uses the first arrangement; its application code never handles the OTP value during sending.
That choice reduces the verification logic the storefront must maintain.
It also creates a dependency: the provider must expose the challenge lifecycle and template controls your application needs. Check those capabilities before selecting the arrangement. A delivery-only API cannot satisfy the verification interface below without an additional implementation.
For an illustrative store, call the template store-login-v3. Its purpose is account access after the password step. Keep promotions and order-receipt copy elsewhere. Record a template revision alongside each challenge so a wording change can be connected to verification outcomes without collecting message bodies. The revision is an application identifier, not a claim about any provider's template syntax.
Keep the ownership split explicit. A content owner approves the wording; the authentication owner controls challenge policy and release approval. A provider-controlled template still needs a recorded revision or equivalent change record. Otherwise, a deployment can appear unchanged while the shopper sees different instructions.
SMS has a security boundary too. NIST treats authentication over the public telephone network as restricted and calls for attention to risks such as SIM changes and number porting. A password followed by SMS verification can implement two-factor authentication, but delivery status alone cannot authenticate the shopper. Plan an alternative authenticator and a recovery process appropriate to the account's risk.
Replace a send log with a challenge timeline
Before: the application records that an SMS request succeeded. Support sees a successful request and a shopper who still cannot sign in. That log cannot distinguish provider acceptance, delivery, code entry, or a successful login.
After: pending password-authenticated login → suppression decision → approved template revision → provider challenge → verification result → atomic consumption → authenticated session. Delivery receipts attach to the challenge as separate evidence.
That's the diagram.
Use an application challenge ID as the join key. Keep provider IDs in restricted records, and use a pseudonymous destination key for correlation. Exclude OTP values, phone numbers, credentials, and session tokens from ordinary logs. A keyed destination identifier still deserves access controls and a retention policy; it isn't anonymous merely because it looks opaque.
An example trace could contain template revision store-login-v3, channel sms, purpose login, and outcome suppressed. Those are illustrative field values. A suppression event should also identify the rule that made the decision, such as a previously confirmed permanent destination failure. An expired challenge gets a different outcome. Expiration says nothing about whether the phone number exists.
For metrics, count starts, suppressed starts, successful verifications, expirations, and delivery failures by bounded reason categories. Keep challenge IDs in logs, not metric labels. Compare completed verifications with started challenges over a defined window, allowing time for entry before treating an incomplete challenge as a failure. Alert thresholds should come from the store's measured baseline; a universal success percentage would hide differences in traffic and destination mix.
How should Node.js implement SMS-based OTP using third-party APIs?
The following TypeScript example defines an application contract for a Node.js backend. It uses an injected adapter around a third-party verification API. The method names are local interfaces, not provider endpoints. Implement the adapter against the selected service's documented authentication, request fields, and status meanings.
The example assumes the provider supports expiring, single-use challenges and failed-attempt limits. If those guarantees are missing, implement them explicitly before exposing this flow. The pending login must already have passed password verification, and its session binding must come from trusted server state.
import { randomUUID } from "node:crypto";
type PendingLogin = { id: string; accountId: string };
type Destination = { phone: string; key: string };
type Challenge = {
id: string;
loginId: string;
providerId: string;
destinationKey: string;
templateRevision: string;
};
interface VerificationApi {
start(input: {
phone: string;
templateRevision: string;
}): Promise<{ id: string }>;
check(id: string, code: string): Promise<boolean>;
}
interface Store {
isSuppressed(destinationKey: string): Promise<boolean>;
save(challenge: Challenge): Promise<void>;
findForLogin(id: string, loginId: string): Promise<Challenge | null>;
consumeOnce(id: string, loginId: string): Promise<boolean>;
}
interface Controls {
allow(loginId: string, action: "send" | "check"): Promise<boolean>;
}
type Audit = (event: {
name: string;
loginId: string;
challengeId?: string;
templateRevision?: string;
}) => void;
export function otpFlow(
api: VerificationApi,
store: Store,
controls: Controls,
audit: Audit,
) {
const templateRevision = "store-login-v3";
return {
async start(login: PendingLogin, destination: Destination) {
if (!(await controls.allow(login.id, "send"))) return null;
if (await store.isSuppressed(destination.key)) {
audit({ name: "otp.suppressed", loginId: login.id });
return null;
}
const remote = await api.start({
phone: destination.phone,
templateRevision,
});
const challenge: Challenge = {
id: randomUUID(),
loginId: login.id,
providerId: remote.id,
destinationKey: destination.key,
templateRevision,
};
await store.save(challenge);
audit({
name: "otp.started",
loginId: login.id,
challengeId: challenge.id,
templateRevision,
});
return challenge.id;
},
async verify(login: PendingLogin, id: string, code: string) {
if (!(await controls.allow(login.id, "check"))) return false;
const challenge = await store.findForLogin(id, login.id);
if (!challenge) return false;
if (!(await api.check(challenge.providerId, code))) return false;
const consumed = await store.consumeOnce(id, login.id);
audit({
name: consumed ? "otp.verified" : "otp.consume_rejected",
loginId: login.id,
challengeId: id,
});
return consumed;
},
};
}
Require 2 independent decisions before session issuance: provider verification and local atomic consumption.
There are important contracts behind those short methods. consumeOnce must atomically reject an expired or previously consumed challenge and confirm that the pending login is still eligible. A read followed by an ordinary update is insufficient under concurrent requests. The caller may create an authenticated session only after verify returns true. If issuing that session fails, require a fresh challenge through the recovery path. Don't make a consumed code reusable to repair session issuance. Consider concurrent requests carrying the same correct code: even if both provider checks report success, the local consume operation must allow only one winner. The pending login must also permit only one completed authentication, so multiple outstanding challenges cannot independently complete it. This requirement belongs in the storage contract, where a transaction or conditional write can enforce it across application instances.
The destination must come from the account's enrolled phone record. Accepting an arbitrary phone number from the browser would let someone who knows the password send the second factor to a number they control. Changing that enrolled number needs its own authenticated process. Apply shared, atomic limits to sends and checks; include account, destination, and request-origin controls where appropriate. A limit attached only to a freshly created pending-login ID is easy to evade by starting another login.
Keep failures closed.
Provider errors and storage errors must not produce an authenticated session. Map them to a generic user-facing response and record sanitized operational outcomes. A timeout during start is ambiguous: the provider might already have accepted the text. Use documented idempotency or reconciliation capabilities when available. Blindly retrying can send duplicate codes and make the template's instructions harder to follow.
Should every failed message suppress the customer?
No. Suppress a destination only when the evidence and channel policy justify it. Keep email bounce handling and SMS failure handling in separate namespaces. An email address and a phone number belong to the same customer record, but they are different delivery destinations with different failure semantics.
Normalize authenticated provider events into your own bounded categories, preserving the original reason in restricted diagnostic records. Confirm callback authenticity using the provider's documented mechanism before changing suppression state. Deduplicate events and retain their relationship to the original destination and challenge. A callback for an old phone number must not block a newly enrolled one.
A permanent invalid-destination result can justify stopping further attempts to that destination. A temporary delivery failure needs a retry policy. A wrong code needs a verification limit. These are three different decisions. If a provider's status mapping is unclear, resolve its documented meaning before treating it as a permanent block. Delivery success must never clear an authentication failure or create a session.
Suppression needs ownership.
Let a verified destination correction or an authorized review resolve the relevant record. An ordinary request for another text should not erase it. This is where template ownership becomes operational: the team approving the login text should also approve the message shown when delivery is unavailable, so the shopper gets a coherent next step without an account-enumeration signal.
Email authentication is a separate concern. SPF describes sender authorization for email; it doesn't verify SMS codes or establish whether a shopper controls a phone number. Keep those mechanisms separate in both implementation and dashboards.
Does this add too much work to a small login flow?
It adds state. That state answers questions a send receipt cannot.
Keep the implementation focused: one pending login, one challenge record per attempt, explicit template revision, and destination-specific suppression. The operational trade-off is durable storage and adapter maintenance in exchange for explainable decisions. There is also messaging and support cost when duplicate sends or confusing templates cause repeated attempts. Measure those outcomes before changing policy; price is not a substitute for an authentication design.
Before release, exercise a successful login, a wrong code, expiration, concurrent submissions, a repeated callback, an invalid destination, and an ambiguous send timeout. Confirm that no delivery event grants access and no email bounce suppresses a phone number. Test template changes with the same care as verification logic: the expected revision must reach the adapter, and logs must retain the revision without retaining the secret.
Deploy template revisions deliberately. Compare the resulting challenge outcomes with the previous revision, and retain the ability to restore approved wording. The deciding evidence is a trace from a legitimate pending login to a consumed challenge, with a clear reason whenever delivery was blocked. That gives the storefront a teachable, supportable two-factor flow.
References
- NIST SP 800-63B, authentication and authenticator management: https://pages.nist.gov/800-63-4/sp800-63b.html
- OWASP Multifactor Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
- Node.js crypto documentation, including
randomUUID: https://nodejs.org/api/crypto.html - RFC 7208, Sender Policy Framework: https://datatracker.ietf.org/doc/html/rfc7208
Top comments (0)