DEV Community

IversonBlake8417
IversonBlake8417

Posted on

Node.js Logistics Notifications: Email Attachments, SMS Preferences, and Opt-Out Evidence

Option Pick this when Evidence to request in evaluation
Resend Report attachments make email the primary delivery channel Attachment submission, suppression scope, and identifiers for reconciling a send
Twilio SMS control messages deserve a separate integration decision STOP processing, inbound event timing, and suppression synchronization
Amazon SES An email service should fit the infrastructure your team operates Message construction, suppression configuration, and records retained by the application
A shared REST gateway Email and SMS should share an HTTP integration boundary Channel-specific suppression decisions and the freshness of collected events

Sending a logistics report promptly competes with preserving evidence that its recipient was eligible. Resolve that trade-off at dispatch: Short answer: store user channel preferences per event type, check destination suppression before sending, and synchronize unsubscribe, STOP, and administrator opt-outs into both the application database and provider suppression lists. Keep a decision record for each channel, including the one you skipped.

The generated report travels as an email attachment. SMS is a separately selected notice. It must never become an automatic escape hatch around an email opt-out.

How should an event notification system record user channel preferences and suppression?

Start with the question an operator must answer: why did shipment report manifest-482, version 2, reach an email dispatch decision while its SMS notice was withheld? These identifiers are illustrative. The evidence should connect the report version, event, recipient, channel choice, suppression observation, and final decision. A log saying “notification processed” answers almost none of that.

Make absence explainable.

A useful diagram in words is: generated attachment → report event → current channel preferences plus suppression observations → recorded decision → dispatch attempt → later provider outcome. Alongside that path, unsubscribe, STOP, and administrator actions feed a local block plus a provider synchronization task. Those two paths must meet before another send is authorized.

There are three different claims here. An eligibility decision says the application allowed an attempt. An accepted request says the provider accepted that attempt. A subsequent outcome describes what happened afterward. None proves that somebody opened the attachment, and none independently certifies legal compliance. Preserve those distinctions in logs and dashboards; otherwise a green worker metric can conceal an unanswered delivery question.

For compliance evidence, a skipped channel is a useful result. Record not_selected, opted_out, suppressed, or evidence_missing rather than squeezing every non-send into “failed” (including a channel the recipient never selected). The reason changes the response: a deliberate opt-out should stay blocked, while missing suppression evidence calls for reconciliation before reconsidering dispatch.

Pick an integration by the evidence it leaves behind

Pick Resend when the report email is the main deliverable and SMS can be evaluated separately. Its documentation is a starting point for reviewing the email integration. Require an attachment acceptance example and an explanation of suppression handling before selecting it. The application still needs a policy connecting email choices to SMS choices; choosing an email service doesn't supply that policy.

Pick Twilio for evaluation when the SMS side, particularly inbound control messages, drives the decision. Review its messaging policy and the exact STOP behavior for the configuration you intend to use. Confirm how an inbound instruction reaches your database. A stopped SMS destination must not accidentally erase an independent email preference, nor should a later preference update silently remove a channel-wide opt-out.

Pick Amazon SES when the email integration belongs alongside infrastructure your team already operates. Review attachment construction and account-level suppression documentation together. The trade-off to evaluate is the application work required to join those records to the report event, rather than treating a successful email submission as the complete evidence trail.

These are candidate selection rules, not benchmark results.

Infrai fits the shared gateway option through a plain REST API with one key and one bill for email and SMS. That reduces credential inventory and invoice reconciliation for the report workflow. No SDK installation is required; any language capable of HTTP can call it. Its public, self-describing discovery surface supplies request and response schemas without requiring a key, which helps the report team review suppression contracts before integrating credentials. Evaluate that convenience against pull-based email and SMS event collection: an evidence freshness requirement needs an explicit polling and reconciliation design.

Use the same acceptance exercise for every candidate. Select email only. Generate a report. Opt out before dispatch. Verify that the attachment is withheld, the SMS preference remains independent, and the evidence explains both channel decisions. Then repeat with SMS only and a STOP instruction. This makes the comparison about observable behavior instead of marketing language.

Build a decision record before building a dashboard

Here is a small Node.js TypeScript example. It runs locally in a TypeScript-capable Node.js setup, uses no credentials, and makes no provider calls. The sample event, attachment name, and user identifier are synthetic.

The important boundary is visible: provider suppression state is an input, not an inference from a successful HTTP response. Unknown state blocks dispatch. Production adapters must obtain current state from their documented provider contracts.

type Channel = "email" | "sms";
type Suppression = "clear" | "blocked" | "unknown";
type Reason =
  | "eligible"
  | "opted_out"
  | "not_selected"
  | "suppressed"
  | "evidence_missing";

const event = {
  id: "report-482-v2",
  type: "report.ready" as const,
  reportId: "manifest-482",
  version: 2,
  attachment: "manifest-482-v2.pdf",
};
const user = {
  id: "dispatch-team-9",
  revision: 1,
  preferences: { "report.ready": { email: true, sms: false } },
  optedOut: { email: false, sms: false },
};
const provider: Record<Channel, Suppression> = {
  email: "clear",
  sms: "clear",
};
const syncTasks: Array<{
  userId: string;
  channel: Channel;
  revision: number;
  action: "suppress";
}> = [];

function decision(channel: Channel) {
  const selected = user.preferences[event.type][channel];
  const reason: Reason = user.optedOut[channel]
    ? "opted_out"
    : !selected
      ? "not_selected"
      : provider[channel] === "blocked"
        ? "suppressed"
        : provider[channel] === "unknown"
          ? "evidence_missing"
          : "eligible";

  return {
    eventId: event.id,
    reportId: event.reportId,
    reportVersion: event.version,
    attachment: channel === "email" ? event.attachment : null,
    userId: user.id,
    preferenceRevision: user.revision,
    channel,
    providerSuppression: provider[channel],
    reason,
    allowed: reason === "eligible",
    evaluatedAt: new Date().toISOString(),
  };
}

function optOut(channel: Channel): void {
  user.optedOut[channel] = true;
  user.revision += 1;
  syncTasks.push({
    userId: user.id,
    channel,
    revision: user.revision,
    action: "suppress",
  });
}

console.log(JSON.stringify(decision("email")));
console.log(JSON.stringify(decision("sms")));
optOut("email");
console.log(JSON.stringify(decision("email")));
console.log(JSON.stringify({ pendingSuppressionSync: syncTasks.length }));
Enter fullscreen mode Exit fullscreen mode

The sequence yields an eligible email decision, an unselected SMS decision, and then an opted-out email decision with one synchronization task pending. It doesn't send the attachment or claim delivery. This executable example isolates the policy your dispatch adapter must enforce without guessing a provider's request fields.

Persist the boundary.

In a production database, save the local opt-out and its outbox task in one transaction. The synchronization worker applies provider suppression and records completion; local dispatch remains blocked while that work is pending. Make replay safe with a stable operation identity, using the provider's documented idempotency mechanism where available. A duplicate unsubscribe should preserve the block, not generate a second business action.

The sample uses memory to expose the ordering. It has no durable queue, database transaction, or concurrent worker coordination. A real worker should load current preferences and suppression evidence immediately before dispatch, retain a stable identity for each event-recipient-channel attempt, and distinguish a retry from a new report version. A unique database record can coordinate local workers, but it cannot create an atomic transaction with a remote send. Define that commitment boundary explicitly.

For a read-only contract inspection, the following separate TypeScript program checks email suppression over HTTP. Set INFRAI_API_KEY, INFRAI_BASE_URL to the documented HTTPS v1 API base, and REPORT_RECIPIENT_EMAIL to a controlled test destination. It prints the returned JSON without inventing a suppression field. Bind the documented response schema to the decision model before using that response to authorize dispatch.

async function main(): Promise<void> {
  const apiKey = process.env.INFRAI_API_KEY;
  const baseURL = process.env.INFRAI_BASE_URL;
  const email = process.env.REPORT_RECIPIENT_EMAIL;
  if (!apiKey || !baseURL || !email) {
    throw new Error("Set API key, v1 API base, and controlled recipient");
  }
  const base = new URL(baseURL);
  if (base.protocol !== "https:" || base.pathname.replace(/\/$/, "") !== "/v1") {
    throw new Error("Use the documented HTTPS v1 API base");
  }
  const url = `${baseURL.replace(/\/$/, "")}/email/suppression/check/${encodeURIComponent(email)}`;
  for (let attempt = 0; attempt < 4; attempt++) {
    const response = await fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
      signal: AbortSignal.timeout(15000),
    });
    if (response.status === 429 && attempt < 3) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const delay = Number.isFinite(seconds)
        ? Math.max(0, seconds * 1000)
        : Number.isFinite(date)
          ? Math.max(0, date - Date.now())
          : 1000 * 2 ** attempt;
      await response.body?.cancel();
      await new Promise<void>((resolve) => setTimeout(resolve, delay));
      continue;
    }
    const body = await response.text();
    if (!response.ok) {
      throw new Error(`Suppression check HTTP ${response.status}: ${body}`);
    }
    console.log(JSON.stringify(JSON.parse(body), null, 2));
    return;
  }
}

main().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Checking preferences only when the report is generated is insufficient. A recipient may opt out while the attachment waits in a queue. The dispatch decision needs the current preference revision; an earlier “eligible” log must not become a reusable permission slip. If a suppression check cannot supply usable evidence, defer dispatch and record that reason separately from an explicit opt-out.

Now the dashboard has something worth counting. Proposed application metrics include decisions by channel and reason, pending suppression synchronizations, age of the oldest pending task, and time since the last successful event collection. Put event and recipient correlation identifiers in access-controlled evidence records rather than using them as unbounded metric labels. Keep report contents and destination addresses out of routine logs.

A practical alert exercise is concrete: pause the synchronization worker, process an opt-out, and verify that the pending-task age grows while the next local email decision remains blocked. Choose the alert threshold from the team's required evidence freshness; a made-up universal threshold would hide the actual operational decision.

Limits that should change the choice

Pull-based event collection creates a gap between a provider observing an inbound instruction and the application processing it. Measure that collection lag. If the workflow requires immediate webhook-driven reactions, evaluate providers and configurations against that requirement before committing to a polling design.

Email and SMS preferences do not cover voice escalation, WhatsApp, or RCS. Likewise, moving a shipment report into an attachment does not establish consent, a lawful retention policy, or a particular jurisdiction's compliance status. Those requirements need their own review.

Keep the scope honest: this design explains eligibility, suppression synchronization, and dispatch evidence. It doesn't prove receipt or make an already accepted external send reversible. That limit belongs in the operating procedure, where the report team can act on it.

References

Resend's introduction, Twilio's Messaging Policy, and the Amazon SES guides below are starting points for provider evaluation. CTIA's messaging guidance informs the SMS policy discussion; it doesn't replace a review of applicable requirements for a specific logistics workflow.

Sources

Top comments (0)