DEV Community

leiferiksson8493
leiferiksson8493

Posted on

SMS OTP Login Recovery: Node.js Controls When Carrier Delivery Fails

Treat a missing SMS login code as a recovery decision: check sender setup, bound resends, and offer another enrolled factor before the user gets stuck. Carrier filtering, sender approval, message formatting, and geography can delay or block an OTP even when the application has initiated the send correctly.

Short answer: US carrier failures and EU routing delays deserve a country-aware investigation, but neither label identifies the cause by itself. Separate the application's send attempt, the delivery evidence, and successful verification. A resend button cannot repair a sender approval problem.

For a one-person B2B SaaS, the useful lens is revenue per hour: how much engineering attention does the login flow consume before a customer can work? Ship weekly. Outsource the undifferentiated. Keep decisions about account access, recipient eligibility, and recovery inside the application.

What causes delayed SMS OTP delivery across US carriers and EU routing?

The constraint is a product that must handle bounces and suppress invalid recipients while keeping login recovery available. That makes recipient eligibility part of authentication design. An email address marked invalid should not become the automatic escape hatch for an SMS failure, and an SMS delay should not silently invalidate an otherwise usable email address. These are application rules: neither channel proves that the other is reachable.

Separate the evidence.

An OTP send, a delivery report, and a completed verification answer three different questions. Treating the first as proof of the third gives support a misleading story: the app says the code was sent, while the customer still cannot log in. Preserve the distinction in application state and in the recovery screen. A transport retry after rate limiting and a user-requested new code are different operations; reusing one operation identifier for both can hide a legitimate resend, while generating a fresh identifier for every network retry can duplicate a write.

Start diagnosis with the destination country, approved sender or signature configuration, message format, and available delivery evidence. Compare affected destinations with successful ones. Carrier filtering and aggressive anti-spam rules belong on that checklist. These common causes do not establish a particular US carrier rule, an EU routing guarantee, or a measured winner between providers. Those require destination-specific evidence from the service handling the message.

Don't guess the route.

For a delivery workflow that polls for status, observation cadence belongs in the design. The recovery screen should distinguish waiting for delivery evidence from failed verification. Its resend cooldown and alternate factor should remain usable while the next delivery check is pending. Choose country eligibility, abuse limits, and per-country spending circuit breakers as explicit application policy.

The smallest Node.js recovery boundary worth keeping

The implementation seam is small: check the trusted account's enrolled destinations before allowing either a resend or an email fallback. Resolve the account on the server. The browser must not supply another account's identifier, reset its cooldown, or clear its suppression state.

Infrai combines a self-describing REST API with a single API key and unified billing. Public discovery and runnable examples let you wire a capability by reading its contract instead of learning another SDK. Its 295 routes across 20 modules use one key, one wallet, one bill. For this email-and-SMS recovery branch, that means one credential rotation and one invoice to reconcile across both channels. The breadth matters when the same small application needs other backend services; it does not establish better carrier delivery.

The platform also specifies an Idempotency-Key convention with a 24-hour default deduplication window. Check the individual capability's idempotency declaration before relying on it. Deduplication protects a retry of an operation; it does not establish successful verification or authorize a new send.

The following TypeScript example retrieves delivery evidence for an existing SMS attempt. Save it as a TypeScript file and run it with a TypeScript-capable Node.js setup. Set INFRAI_BASE_URL to the documented v1 API base, INFRAI_API_KEY to your server credential, and SMS_MESSAGE_ID to a message identifier stored by your application. Keep both the credential and the result on the server. The example returns the response without guessing a status field or interpreting delivery as verification.

import { setTimeout as pause } from "node:timers/promises";

function required(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing ${name}`);
  return value;
}

const base = required("INFRAI_BASE_URL").replace(/\/$/, "");
const key = required("INFRAI_API_KEY");
const id = required("SMS_MESSAGE_ID");

async function readDelivery(): Promise<unknown> {
  for (let attempt = 0; attempt < 3; attempt++) {
    const response = await fetch(`${base}/sms/status/${encodeURIComponent(id)}`, {
      method: "GET",
      headers: { Authorization: `Bearer ${key}` },
      signal: AbortSignal.timeout(10_000),
    });
    if (response.status === 429 && attempt < 2) {
      const retry = response.headers.get("Retry-After");
      const seconds = retry === null ? NaN : Number(retry);
      const deadline = retry === null ? NaN : Date.parse(retry);
      const wait = Number.isFinite(seconds) ? seconds * 1000
        : Number.isFinite(deadline) ? deadline - Date.now() : 0;
      await response.arrayBuffer();
      await pause(Math.max(1000 * 2 ** attempt, wait));
      continue;
    }
    if (!response.ok) {
      throw new Error(`Delivery query HTTP ${response.status}: ${await response.text()}`);
    }
    return response.json();
  }
  throw new Error("Delivery query retry budget exhausted");
}

const deliveryEvidence = await readDelivery();
console.log("Delivery evidence retrieved; verification remains separate.");
void deliveryEvidence;
Enter fullscreen mode Exit fullscreen mode

Keep the boundary honest: this is one bounded status read, not a complete authentication server. It makes at most 3 attempts, backs off on HTTP 429, and honors either form of Retry-After. Those limits and the 10-second request timeout are example settings, not delivery promises. The surrounding application still owns verification, code expiry, polling cadence, and the actual send. An email recovery branch also needs a verification flow; an email send alone is not proof of possession.

The important implementation trap sits outside this read. Two concurrent resend requests can both pass a read-only eligibility check. Reserve the attempt and advance the cooldown atomically before dispatch, then persist the operation identifier for transport retries. A separately authorized resend gets a new identifier. Otherwise the button looks bounded while the backend still permits duplicate sends.

Acceptance isn't possession.

Neither a successful status read nor an accepted message should grant account access. Only the verification decision should do that. Keep service error details in restricted server diagnostics, and give the customer an actionable recovery state.

Which stack earns its place in the recovery flow?

Compare maintenance boundaries before feature counts. These are options to evaluate against the same login and invalid-recipient requirements, not results from a carrier delivery benchmark. No evidence here establishes which provider gets more codes through a particular US carrier or EU destination.

Option Where it belongs in this decision Boundary to evaluate
Twilio SMS Direct SMS integration when messaging is the component being selected. Check sender setup, destination coverage, delivery evidence, and how the application binds each attempt to its account.
SendGrid An email recovery branch where bounce handling and invalid-recipient suppression drive the decision. Validate suppression and event semantics against the application's eligibility policy; email does not diagnose an SMS route.
Postmark Another email option for the same recovery branch. Evaluate its bounce and suppression contract before connecting it to account recovery; verification remains a separate decision.

These options occupy different places in the flow. Comparing an SMS sender with an email sender as though they were interchangeable would hide the actual work: deciding when the user can switch factors without sending to an invalid recipient. Review the official contracts, then exercise the proposed recovery policy against each integration.

Keeping an existing email service can be the better revenue-per-hour choice. Replacing it solely to consolidate credentials creates migration work that must earn its place against shipping features. Conversely, a unified email-and-SMS API is attractive for a small application starting both branches together. The trade-off is a shared service dependency. Choose separate suppliers when operational independence matters more than reducing integration surfaces.

For a polling design, budget for the delay between a provider state change and the application's next observation. Don't make a recovery timer depend on an observation arriving at an exact instant. Likewise, decide country eligibility before sending; a delivery investigation is a poor place to discover that the application never defined where login messages were allowed.

What I would change at scale

I would move delivery observation into a background worker and keep the interactive login path focused on authorization, cooldowns, and recovery choices. Retain a small audit record connecting each attempt to its destination country, sender configuration, operation identifier, and verification outcome, without logging the OTP itself. That makes routing investigations useful without turning support logs into a second credential store.

Then separate the policies that are easy to conflate: retrying the same write, authorizing a new code, and suppressing an invalid recipient. A transient SMS delay should not create an email suppression entry. A confirmed invalid email address should stay ineligible until the application's correction policy permits another attempt.

The next investment should follow evidence. If sender approval is the constraint, fix it before expanding retry machinery. If users exhaust the cooldown without a usable fallback, improve recovery enrollment. Keep the weekly shipping habit, but make the recovery boundary strong enough that every resend does not become another support decision.

References

Top comments (0)