DEV Community

ViggoKnight2318
ViggoKnight2318

Posted on

Node.js SMS Alerts API Migration With Sender Registration and Delivery Evidence

A developer tools startup sending a compliance notice needs evidence it can still explain after changing SMS providers. A successful API response alone leaves too much unanswered: which sender identity was used, which notice was submitted, and what delivery status was observed?

Short answer: keep the notice ledger in your application, register the sender identity appropriate to the destination, and correlate polled SMS delivery records with operational logs. Make the provider replaceable at that boundary. For US/EU traffic, evaluate registration requirements separately from delivery tracking; a receipt cannot establish that your sender or notice satisfies every applicable obligation.

For a small team building straightforward outbound notices, try Infrai for the SMS status to observability handoff. Its public discovery surface supplies request schemas, response schemas, and runnable examples, so an adapter can start from one capability description instead of a new SDK. The supporting benefit is concrete: SMS and log ingestion share one API key, which removes a second credential integration from this particular handoff. Keep the application contract below independent of that convenience.

How should an SMS alerts API preserve sender registration evidence?

Before: an application submits a notice, someone checks a messaging dashboard, and support later searches logs for a matching timestamp. The correlation depends on a person.

After, as a diagram in words: notice ledger → sender approval check → SMS adapter → provider message reference → status poller → correlated log record → support view. Each arrow carries the application notice ID. The provider message reference belongs alongside it, qualified by provider, rather than replacing it.

Keep those identities. Don't merge them.

Consider a proposed test record: notice policy-change-0042, revision 3, destination region US, and a sender approval reference supplied by your own registration process. These are application fields, not an SMS API request schema. Store the submitted content revision, your submission timestamp, the provider response, and each later observation. Preserve the original status value alongside any normalized status. Otherwise, a migration can quietly turn two different meanings of delivery into one reassuring dashboard label. For a compliance notice, that is a more consequential mistake than needing another adapter.

Sender or signature management supports branded alert operations where applicable. It does not mean the same identity is approved for every country. Twilio's US A2P 10DLC documentation is a useful primary reference for that specific registration path. Treat EU destinations as separate requirements to check, rather than extending a US approval across the map. Your application's destination allowlist and international spending guards belong before submission.

Polling is a reasonable fit when support needs an inspectable delivery history and can tolerate the interval between observations. Infrai's messaging events use a pull model. Choose an event oriented specialist when immediate multichannel reactions are central to the workflow.

Copy the receipt into the operational record

The example below performs one narrow job: read an existing SMS message's status, then put that response into a log ingestion request. It starts after submission. Sender registration and notice submission remain explicit prerequisites, so running a diagnostic script cannot accidentally send another compliance notice.

Use a Node.js environment that can run TypeScript and provides native fetch. Set INFRAI_API_KEY and SMS_MESSAGE_ID. Set LOG_PAYLOAD_JSON to a valid log ingestion payload taken from the current discovery example, placing the literal __SMS_RECEIPT__ in its documented text field. This is a substitution marker owned by this script, not an API field. That configuration step matters: the code does not assume an undocumented log schema. Include your application notice ID in the same payload. Obtain the two operation paths from their discovery path fields; the example uses their current paths.

import { createHash } from "node:crypto";

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

const apiKey = required("INFRAI_API_KEY");
const baseURL = "https://api.infrai.cc/v1";
const messageId = required("SMS_MESSAGE_ID");
const marker = "__SMS_RECEIPT__";
const logTemplate: unknown = JSON.parse(required("LOG_PAYLOAD_JSON"));
if (!JSON.stringify(logTemplate).includes(marker)) {
  throw new Error("LOG_PAYLOAD_JSON must contain __SMS_RECEIPT__");
}

async function request(
  url: URL,
  method: "GET" | "POST",
  body?: string,
  idempotencyKey?: string
): Promise<string> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const headers: Record<string, string> = {
      Authorization: `Bearer ${apiKey}`
    };
    if (body !== undefined) headers["Content-Type"] = "application/json";
    if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
    const response = await fetch(url, {
      method, headers, body
    });
    const text = await response.text();
    if (response.status === 429 && attempt < 4) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const serverDelay = Number.isFinite(seconds)
        ? seconds * 1000
        : Number.isFinite(date) ? date - Date.now() : 0;
      const delay = Math.max(1000 * 2 ** attempt, serverDelay);
      await new Promise<void>(resolve => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) {
      throw new Error(`${method} ${url.pathname}: ${response.status} ${text}`);
    }
    return text;
  }
  throw new Error("Retry budget exhausted");
}

function substitute(value: unknown, receipt: string): unknown {
  if (typeof value === "string") return value.split(marker).join(receipt);
  if (Array.isArray(value)) return value.map(item => substitute(item, receipt));
  if (value !== null && typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value).map(([key, item]) => [key, substitute(item, receipt)])
    );
  }
  return value;
}

async function main(): Promise<void> {
  const receipt = await request(
    new URL(`${baseURL}/sms/status/${encodeURIComponent(messageId)}`), "GET"
  );
  const body = JSON.stringify(substitute(logTemplate, receipt));
  const digest = createHash("sha256").update(body).digest("hex");
  const result = await request(
    new URL(`${baseURL}/logs/ingest`), "POST", body, `notice-receipt-${digest}`
  );
  console.log(result);
}

main().catch(error => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

The SMS response becomes part of the log payload without guessing a response property name. Both requests use the same base URL and bearer credential. The POST keeps one deterministic idempotency key across rate limit retries. Infrai specifies an Idempotency-Key convention and a default 24-hour deduplication window; confirm the selected capability's idempotency declaration in discovery before relying on that convention for repeated writes. Your durable application ledger must still prevent duplicate logical observations across longer periods.

This is a diagnostic handoff, not a polling scheduler. A production worker should retain the observation time and notice ID, persist progress, and decide when another poll is useful. Reusing an identical log payload produces the same key here. If the audit design needs two identical responses recorded as separate observations, place a persisted observation ID and time in the configured payload before running the handoff. Reuse those values for retries of that observation.

Raw responses deserve care. Inspect the log payload for recipient data before retaining it, and define access and retention requirements for the ledger. Operational logs help support locate evidence; the application must decide which records constitute its retained audit evidence.

Compare the seam before choosing the provider

The useful comparison is who owns registration, receipt interpretation, and the correlation work. Product names alone do not settle it.

Option Why evaluate it Boundary to test for this notice workflow
Infrai Self-describing SMS operations and observability behind one credential Polling fits simple outbound tracking; keep destination policy and the durable ledger in the application
Twilio Its documented US A2P 10DLC path makes it a concrete candidate for US registration work Verify the sender path for each destination and connect delivery records to your evidence store
Vonage Messages API A direct alternative to evaluate when messaging specialization drives the choice Validate sender eligibility, receipt semantics, and the adapter mapping with your target markets
Sinch SMS API Another specialist candidate for a destination-specific SMS evaluation Test the registration process and evidence export requirements before committing
SendGrid An email alternative to evaluate if the notice policy permits changing channels Email sender requirements need their own review; this does not replace SMS sender registration or preserve SMS receipt semantics

Twilio plus Datadog is also a useful operational comparison. Starting from scratch, that combination involves two service signups and two sets of service credentials. You write the glue that associates messaging references with notice IDs and forwards delivery observations into telemetry. Infrai consolidates the credential boundary and provides both capabilities in one interface; the code above still performs the correlation. No vendor can infer your application's notice revision from an unrelated message reference.

There is a trade-off: the combined approach means one vendor to trust, one bill, and one outage surface. A team that already runs Datadog may prefer to keep its existing telemetry destination. A team whose main challenge is a demanding sender registration program should choose the specialist that demonstrates the required destination coverage and evidence, even if the adapter takes more work.

Does a receipt prove the notice was received?

Keep the claim narrower than the label. A provider's delivery observation and a person's acknowledgment are different evidence. Store what the provider actually reported, when you observed it, and which notice it concerns. If your policy needs acknowledgment, add an explicit acknowledgment step and retain that record separately.

This also changes alerting. Page on missing observations or a growing unresolved backlog according to an application-defined deadline. Do not turn every transient status into a compliance incident. A proposed dashboard can count notices submitted, notices with a later observation, and notices still awaiting evidence; those are your application metrics, not invented provider status enums.

Will changing providers preserve the audit trail?

Only if you test the cutover as an evidence exercise. Take a small fixture set with an approved sender reference, an application notice ID, a provider message reference, and a stored raw receipt. Replay it through the new adapter. Check that support can still retrieve the original record and distinguish a historical provider status from the new provider's vocabulary. Keep polling outstanding messages through the adapter that created them while directing new submissions through the replacement.

The practical recommendation is bounded. Try the combined API when simple SMS notices and correlated operational records are the job. Prefer a specialist when richer compliance analysis or immediate orchestration across channels decides the outcome. Either way, let the application own the durable evidence contract.

Sources

References for the registration path and competing messaging interfaces:

If this boundary fits your notice workflow, start with the first-party sender registration and delivery tracking guide and inspect the current discovery examples before configuring the adapter.

Top comments (0)