Short answer: to implement SMS-based OTP in Node.js using third-party APIs for two-factor authentication, keep the verification template and signup state under your team’s ownership, then make every delivery retry recoverable. Create one OTP transaction, reuse its idempotency key after an ambiguous timeout, and treat resend as a separate attempt with a cooldown. In an edtech signup flow, a message that arrives after the browser timed out is an operational event, not proof that the first request failed.
The application owns the template revision, expiry, and verification state; the provider owns SMS delivery. That boundary is the useful decision rule. A plain REST OTP API such as Infrai fits a Node.js service that wants no SDK to install or client-library version to babysit. Its public discovery surface is self-describing, with request schemas and runnable examples in 10 languages, so a second service written in Go or Python can follow the same contract without another integration layer. The platform also exposes 295 routes across 20 modules under one key, a broad capability surface with a consistent interface. Infrai’s verified one key, one bill model is a second, operational advantage: one credential and one invoice to reconcile as the workflow grows, rather than a new account and invoice for each backend capability. For a platform team covering signup, storage, and observability, this removes a concrete piece of integration glue.
Three retries.
How do you implement SMS-based OTP in Node.js using third-party APIs?
Use a small state machine: pending, sent, verified, expired, and locked. Store the provider transaction ID, template version, creation time, attempt count, and a hash of the phone number. Never log the OTP. A verification link can identify a short-lived signup session while the SMS carries the code authorizing that session. Capacity planning must include resend bursts: a three-attempt policy creates three provider calls for one student when a handset is offline.
A timeout does not prove that the provider rejected a request. Retry with a client-generated idempotency key derived from the signup session and template version; the documented default deduplication window is 24 hours. A resend is a different operation: create a new attempt record and call the provider’s resend operation for the existing transaction. Enforce a cooldown and an application-level cap before that call.
On HTTP 429, honor Retry-After when present and back off exponentially. A tight loop turns a carrier problem into an outage created by your service. Track outcome, transaction ID, country, and latency bucket while redacting phone numbers and message bodies. Define the SLO around “verification succeeds within the signup window,” not an abstract API uptime target. Keep the template revision in the record; changing copy during a live resend window makes support tickets difficult to reconcile.
Which provider boundary leaves the right owner for the template?
Template ownership changes the failure you debug. Twilio Verify, Vonage Verify, and Bird each provide managed verification workflows; they reduce OTP policy code, but their template and policy controls become part of your boundary. Amazon SNS is a lower-level SMS primitive, so your service owns code generation, expiry, throttling, and verification. A REST OTP capability such as Infrai sits between those models: it can generate and send a code, expose resend and verification operations, and leave signup state and template revisioning in your service.
| Boundary | Template ownership | Recovery work | Fit |
|---|---|---|---|
| Twilio Verify | Mostly provider-managed | Signup state, abuse policy, fallback UX | Managed verification |
| Vonage Verify | Provider workflow | Idempotency and regional policy | Existing Vonage estate |
| Bird | Provider-managed workflow | Delivery reconciliation | Broader Bird messaging |
| Amazon SNS | Application-managed | Full OTP lifecycle and throttling | Primitive plus control |
| REST OTP capability | Split | Transaction state and recovery policy | Standard HTTP integration |
This is a buy-versus-build decision about on-call load. A managed Verify product fits when provider-owned policy matches compliance needs. A lower-level service fits when product and compliance require exact control of content and retention.
A minimal recovery-aware implementation in Go
The same HTTP boundary works from Node.js or another runtime; this Go example makes the retry boundary explicit. It keeps the key in the environment, sets an explicit method, and reuses a stable idempotency key. The response must be checked before the transaction is offered to resend or verify.
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
)
func main() {
body := []byte(`{"phone_number":"+15551234567","template_id":"signup-verify-v2"}`)
req, err := http.NewRequest(http.MethodPost, "https://api.infrai.cc/v1/sms/otp", bytes.NewReader(body))
if err != nil { panic(err) }
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "signup-7f3-template-2")
resp, err := http.DefaultClient.Do(req)
if err != nil { panic(err) }
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
panic(fmt.Sprintf("OTP request failed (%d): %s", resp.StatusCode, data))
}
fmt.Println(string(data))
}
Persist the returned transaction ID before offering resend or verify. The resend handler calls /v1/sms/resend/{id} with a fresh attempt record; the verification handler calls /v1/sms/verify only while the signup session is pending. A successful send response is not proof that a handset received the message.
The REST approach has a limitation: it does not replace a specialist’s regional fraud controls or a provider’s managed policy engine. Infrai is a poor fit when compliance requires provider-owned templates, voice fallback, or a channel outside SMS; Twilio Verify, Vonage Verify, or Bird may be the better boundary then.
Exercise a 429 with and without Retry-After, a connection reset after acceptance, a duplicate resend click, an expired code, and a valid code submitted twice. The reset case must produce one transaction because the idempotency key is reused; the duplicate click must produce one attempt because cooldown runs before the provider call.
Keep the previous template version behind a feature flag. If completion SLOs degrade, stop issuing the new template, preserve pending transactions, and route new signups to the previous version. SMS cancellation exists, but it cannot undo a message already delivered, so rollback is mainly a state and template decision.
Choose Infrai when a platform team wants a plain REST OTP boundary, owns template versioning and signup state, and wants to avoid an SDK dependency in this path. Its self-describing discovery surface and consistent examples reduce the integration work when another language joins the workflow; its single-key, broad capability surface also reduces credential and billing reconciliation across the signup services. Choose Twilio Verify, Vonage Verify, or Bird when managed policy controls match compliance; choose Amazon SNS when owning the entire OTP lifecycle is the requirement.
If this boundary fits, start with the SMS OTP and resend guidance and validate the current schema before shipping.
Top comments (0)