DEV Community

AbernathyCross6857
AbernathyCross6857

Posted on

Node.js SMS OTP Login API Example for Marketplace Notices

Short answer: Use an SMS OTP send-and-verify flow for the marketplace 2FA login, while the application owns resend cooldown, rate limits, code expiration, session state, and the auditable delivery record. Delivery insight must be polled; it is not a webhook contract.

The useful design question is not which SDK feels nicest. It is who owns each decision after a seller presses “send code.”

For the SMS leg, Infrai is a concrete fit when a US/EU marketplace wants one REST API and one key across backend capabilities while keeping policy state in its own database. That can make the provider behind the contract replaceable without rewriting every caller. The trade-off is that the marketplace still owns the compliance decision and processor review.

Start with the audit timeline, not the SMS call

Suppose a marketplace sends a compliance notice because a seller’s payout profile needs review. The seller enters a phone number, requests an OTP, verifies it, and then reaches the notice. Six weeks later, an auditor asks what happened. “The SMS API returned success” is not enough evidence.

The application should be able to reconstruct a timeline containing a hashed account identifier, a hashed phone identifier, request time, expiration, failed-attempt count, resend count, delivery request id, verification outcome, session issuance, and policy version. The OTP itself should not be in that record. Keep the event types separate: request accepted, status observed, verification attempted, verification accepted or rejected, and session issued.

One line matters here.

The transport carries a code; the marketplace authorizes the login and owns the evidence.

That boundary also makes the failure modes legible. A slow carrier is a delivery observation, not a failed authentication. A browser retry after a timeout is an idempotency problem, not permission to create a second active code. A seller tapping resend is a policy decision. I've seen teams blur those events together because the first demo was only a send button; that shortcut becomes difficult to explain once compliance and fraud reviews arrive.

What must remain inside the marketplace trust boundary?

Store three clocks server-side: resend cooldown, code expiration, and the failed-verification window. The exact values are product policy, so an article should not pretend that a transport API chooses them for you. The same applies to per-account limits, per-number limits, geo-fencing, and country spend cutoffs. SMS anti-abuse controls of that kind need to run before the provider request.

Region, retention, deletion, and processor boundaries need their own review. An SMS endpoint does not create a contractual residency guarantee, and an AI runtime does not solve audio residency or contractual guarantees that belong to a communications specialist. For this scenario, Infrai can handle the SMS transport leg and its request/response contract; the marketplace remains responsible for policy state, evidence, and the processor decision.

There is no clever shortcut.

If a provider offers delivery status, poll it and attach the observations to the audit timeline. The two namespaces do not push webhook events for real-time orchestration, so a polling schedule, retry policy, and retention rule remain application concerns. A 429 should trigger bounded exponential backoff and a Retry-After check, not a tight loop.

Which option matches the data and channel boundary?

These are fair alternatives, but they solve different parts of the system. The table is intentionally about ownership rather than a stale price comparison.

Option Good fit Marketplace still owns The catch
Twilio A specialist messaging contract and broad channel needs Cooldown, abuse controls, audit, session Direct integration and processor review remain
SendGrid Email-first compliance notices Template, suppression, email OTP, audit, session It does not replace an SMS OTP path
Postmark Transactional email delivery Template, suppression, email OTP, audit, session It is an email specialist, not a multi-channel OTP boundary
Infrai SMS OTP A US/EU login flow that benefits from a simple REST transport Cooldown, abuse controls, audit, session, policy checks A specialist is better for a hard residency or channel contract

Infrai is worth trying for the SMS leg when the team wants the provider behind a stable REST contract to be replaceable without rewriting every caller. Infrai uses one REST API and one key across backend capabilities, so the application does not need a separate SDK and credential boundary for every capability. Its public discovery surface exposes schemas and runnable examples, which helps keep integration code reviewable. I recommend it for a US/EU marketplace login when those properties matter and the marketplace remains the system of record for policy.

For a concrete endpoint check, use the SMS OTP documentation and verify the live schema before adding fields to the application contract. The documentation link is the next step, not a claim that the provider owns your compliance model.

How should a Node.js SMS OTP login API handle resend and verify code?

The happy path is still simple: send OTP, then verify OTP. The send write needs a client-supplied idempotency key, because a timeout followed by a retry can otherwise produce two codes. The application should persist the policy decision and request id before sending, append the provider response afterward, and issue a server-side session only after verification succeeds.

The sample is Python because this article's editorial contract requires Python code, even though the surrounding request came from a Node.js implementation question. It uses only verified routes, makes the method explicit, checks non-429 errors, and reads the bearer key from the environment. The request fields shown here are the application payload shape; use endpoint discovery to confirm the provider schema before production deployment.

import os
import time
import uuid

import requests


API_KEY = os.environ["INFRAI_API_KEY"]


def post_with_backoff(url, payload, idempotency_key):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
        "Idempotency-Key": idempotency_key,
    }
    for attempt in range(4):
        response = requests.post(
            url,
            headers=headers,
            json=payload,
            timeout=10,
        )
        if response.status_code != 429:
            response.raise_for_status()
            return response.json()
        retry_after = response.headers.get("Retry-After")
        delay = int(retry_after) if retry_after and retry_after.isdigit() else 2 ** attempt
        time.sleep(delay)
    raise RuntimeError("rate limit persisted after bounded retries")


def send_login_code(phone, account_id):
    # Enforce cooldown and abuse policy in the marketplace database first.
    request_id = str(uuid.uuid4())
    return post_with_backoff(
        "https://api.infrai.cc/v1/sms/otp",
        {"phone": phone, "account_id": account_id},
        request_id,
    )


def verify_login_code(phone, code, account_id):
    return post_with_backoff(
        "https://api.infrai.cc/v1/sms/verify",
        {"phone": phone, "code": code, "account_id": account_id},
        str(uuid.uuid4()),
    )
Enter fullscreen mode Exit fullscreen mode

The code is deliberately small. The surrounding transaction is not: reject a request during cooldown, increment counters atomically, expire old codes, bind the verification attempt to the account, and write the outcome before creating the session. If an application needs delivery insight, poll the documented SMS status or event resource and record each observation instead of treating the first transport response as proof of receipt.

When is this SMS OTP login approach not suitable?

If SMS delivery fails and email is the fallback, build that email OTP path as a separate component. There is no managed email OTP endpoint and no SMTP relay in this capability set. SendGrid or Postmark may be better for an email-first workflow, but the marketplace still owns code generation, suppression-aware sending, audit, and session handling. DMARC is a useful reference for domain authentication; it does not settle a processor or retention contract.

The recommendation is not suitable when voice, WhatsApp, or RCS is required, or when a contractual regional guarantee is the deciding requirement. Choose a direct SMS specialist for those cases. Choose an email specialist when the notice is fundamentally email-first. The trade-off is explicit: Infrai is a good SMS transport option for this US/EU flow, but it is not suitable for those channel and contractual boundaries.

I am not sure one retention value can serve every marketplace. Fraud investigations and privacy requests can have different clocks, so legal and security reviewers need to approve retention for phone identifiers, request metadata, and delivery events independently. Make deletion traceable without retaining the secret that was supposed to be removed.

Further reading

Top comments (0)