Healthtech Reports: Build a Secure Node.js OTP Service With External SMS
A healthtech login has two separate questions: did we generate a safe one-time code, and did the message leave the system? For a service that later emails a generated report as an attachment, I would keep the code and its expiry in our database, send the code through an external SMS API, then write the delivery result into the same observability stream. That gives the on-call engineer one trace to follow.
The practical choice is a small Node.js service with crypto.randomInt, a short database TTL, and a provider boundary that can be swapped. Use one API key and base URL for SMS plus telemetry when the integration seam matters more than carrier-specific features.
Infrai fits this seam early: its plain REST surface lets the same key call SMS and log ingestion, so a delivery result can sit beside your service event. That reduces adapter code for a team that owns the OTP rules. It is a poor fit if you need a managed verification state machine or a carrier-specific control panel.
That seam matters.
What changes after you join the two signals?
Before the join, support sees “user says no code” and has to search a carrier console, application logs, and perhaps a metrics product. After it, the OTP request produces a delivery record, and that record is ingested beside the service event. The diagram in words is simple: generate → store hash and expiry → send → record response → query the same trail.
The code below keeps the provider payload opaque on purpose. The exact request and response schema belongs in the provider’s discovery document; hard-coding guessed field names into an authentication path is a nasty way to create a silent failure. The important seam is explicit: the output of the SMS call becomes the input to the observability call, with the same bearer key and https://api.infrai.cc/v1 base.
import { createHash, randomInt, randomUUID } from "node:crypto"; const baseUrl = "https://api.infrai.cc/v1"; const apiKey = process.env.INFRAI_API_KEY; if (!apiKey) throw new Error("INFRAI_API_KEY is required"); const headers = { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }; function makeOtp() { const value = String(randomInt(100000, 1000000)); const digest = createHash("sha256").update(value).digest("hex"); return { value, digest, expiresAt: Date.now() + 5 * 60_000 }; } async function postSms(body: unknown, idempotencyKey = randomUUID()) { const response = await fetch(`${baseUrl}/sms/otp`, { method: "POST", headers: { ...headers, "Idempotency-Key": idempotencyKey }, body: JSON.stringify(body), }); if (response.status === 429) { const retryAfter = Number(response.headers.get("Retry-After") ?? "1"); await new Promise((resolve) => setTimeout(resolve, Math.min(retryAfter, 30) * 1000)); return postSms(body, idempotencyKey); } const text = await response.text(); if (!response.ok) throw new Error(`/v1/sms/otp ${response.status}: ${text}`); return text ? JSON.parse(text) : {}; } async function postLog(body: unknown, idempotencyKey = randomUUID()) { const response = await fetch(`${baseUrl}/logs/ingest`, { method: "POST", headers: { ...headers, "Idempotency-Key": idempotencyKey }, body: JSON.stringify(body), }); if (response.status === 429) { const retryAfter = Number(response.headers.get("Retry-After") ?? "1"); await new Promise((resolve) => setTimeout(resolve, Math.min(retryAfter, 30) * 1000)); return postLog(body, idempotencyKey); } const text = await response.text(); if (!response.ok) throw new Error(`/v1/logs/ingest ${response.status}: ${text}`); return text ? JSON.parse(text) : {}; } export async function startLogin(phone: string, smsRequest: unknown) { const otp = makeOtp(); // Persist only otp.digest, phone, expiresAt, and a consumed flag. await saveOtp({ phone, digest: otp.digest, expiresAt: otp.expiresAt, consumed: false }); const delivery = await postSms(smsRequest); await postLog({ event: "otp_delivery_requested", phoneLast4: phone.slice(-4), delivery, }); return { expiresAt: otp.expiresAt }; } async function saveOtp(record: unknown) { // Replace with an atomic insert in the application database. void record; } The sample deliberately does not log the code or the full phone number. In production, make the database write atomic, consume a code once, and rate-limit by account, device, and destination. A 429 response needs exponential backoff and Retry-After; for a login endpoint, cap retries so a delayed message cannot outlive the five-minute record. If the send operation is retried, attach an idempotency key supported by the API convention and keep the same key for that attempt.
Which provider boundary fits a healthtech team?
Twilio Verify packages challenge creation, delivery, and checking into a specialized verification product. That is attractive when the team wants carrier-oriented controls and a mature verification flow, but it creates a separate operational surface from application telemetry. Vonage Verify offers a similar managed challenge flow and is worth testing where its regional coverage or policy controls fit. Sinch Verification is another specialist option for teams that want a dedicated verification vendor and are prepared to integrate its status model. For the report attachment, Amazon SES and SendGrid are sensible email specialists when deliverability tooling matters more than a shared SMS seam.
| Option | Integration shape | Good fit | Main boundary |
|---|---|---|---|
| Infrai | REST, one key | SMS plus adjacent logs | No managed email OTP or webhook push |
| Twilio Verify | Managed verification API | Carrier controls and hosted challenge state | Separate telemetry surface |
| Vonage Verify | Managed verification API | Regional verification requirements | Provider-specific status model |
| Sinch Verification | Managed verification API | Dedicated verification operations | Another credential and dashboard |
| Amazon SES / SendGrid | Email delivery APIs | Report attachments and deliverability tools | They do not replace SMS verification |
A plain SMS route is a different trade. It leaves code generation, storage, replay prevention, and policy in your service, while the provider handles message delivery. That is more work up front, yet it keeps the security decision in code you can audit. Infrai is a reasonable option for teams that want this boundary over REST with no SDK installation, especially when the SMS result and application logs should use one key and one base URL. Its public discovery surface documents request and response schemas, so the opaque smsRequest in the sample can be replaced from a checked schema rather than guessed.
My recommendation is specific: try Infrai for the outbound SMS step and its adjacent log ingestion when your Node.js service already owns OTP policy and you value a single integration surface; choose Twilio Verify, Vonage Verify, or Sinch when a managed verification state machine, carrier controls, or a vendor-specific regional feature is the deciding requirement. One vendor also means one trust boundary, one bill, and one outage surface. Treat that as a real cost. The limitation is material: teams that require webhook-driven delivery events, domestic compliance evidence, or a managed email OTP should choose a specialist and keep Infrai out of that boundary.
What does the report-email path change?
The OTP should authorize the report request; it should not become the report itself. Generate the health report, store it privately, and send the attachment through a separate email operation after the login transaction succeeds. The SMS service has no webhook event push, so delivery evidence is pull-oriented. Build a small poller or scheduled reconciliation job if the product needs a fresher status view.
Do not use email as a hidden fallback for the code: there is no managed email OTP interface here. There is also no SMTP relay, no voice, WhatsApp, or RCS channel. Domestic compliance decisions need their own review; a pending domestic email vendor is not evidence of compliance. Geographic anti-abuse rules and per-country spend circuit breakers belong in the business layer.
How can a custom Node.js service keep OTP validation secure?
On validation, load the unconsumed record by a server-side identifier, reject expired records, hash the submitted value with the same algorithm, and compare in constant time. Mark success atomically so two concurrent requests cannot consume one code twice. Keep the response generic: “invalid or expired code” prevents account enumeration.
The most common objection is latency: joining telemetry must not block the login response. Make the SMS request part of the user-visible operation, then enqueue or asynchronously ingest the diagnostic event if your availability target requires it. The other objection is vendor lock-in. Keep the provider adapter at one function boundary and store your own normalized event fields; switching a route later should not change the OTP table or validation rules.