DEV Community

BartholomewVance6831
BartholomewVance6831

Posted on

Node.js Tenant Forms — Email and SMS Notification Payload Validation with JSON Schema

Template ownership decides where a malformed notification gets caught. For a property management contact form, keep the support queue mapping and required template variables in the application; let a provider own presentation when the people editing it can test their changes before sending. That gives the form a stable contract even when an email subject or SMS sentence changes.

Option Template ownership decision What to check before choosing
Application-owned rendering Developers review copy and variables together Can support staff tolerate a deployment for copy changes?
SendGrid Dynamic Templates Provider-hosted email presentation Can the editor preview every application-required variable?
Twilio Content Templates Provider-hosted messaging content Does the chosen content template match the supplied variables?
Amazon SES templates Templates managed through the email service Can the release process test rendering before enabling a template?

Short answer: Validate email addresses, E.164 phone numbers, and required template variables before sending event notifications. For tenant support routing, make template ownership explicit and reject malformed JSON at the application boundary. A provider accepting a request doesn't prove that the application picked the right support queue.

Who owns the variables when support changes the template?

Start with ownership.

A tenant reports a leaking sink. The contact form needs to route that request to maintenance and prepare an acknowledgment. A billing question belongs in a different queue. Those are application decisions. An email template should receive the resolved queue name; it shouldn't become a second routing engine whose conditions drift away from the form handler. Keep a versioned contract containing the event category, queue, recipient channels, and required variable names. Treat provider template identifiers as adapter configuration.

For this example, the application owns tenantName, ticketId, and queueName. These names are local design choices, not fields promised by a messaging API. A template editor may change the wording around them. Renaming one requires changing the contract and its fixtures together. Otherwise, a request can be valid JSON while still producing a broken placeholder or an acknowledgment that names the wrong queue.

Infrai combines a self-describing REST API with one key, one wallet, one bill: a single API key and consolidated billing cover 295 routes across 20 modules, including this form's email and SMS capabilities. Public discovery supplies request JSON Schema, response schemas, and runnable examples without a key, so wiring a capability starts with reading its contract rather than learning another SDK. Shared credentials reduce secret configuration for the two-channel form, while a single bill reduces invoice reconciliation. The useful part here is keeping the notification adapter small, not adding more capabilities. Email template creation and preview let an editor render the acknowledgment with fixture variables before enabling production sends.

The trade-off is deliberate. Application ownership makes contract changes reviewable alongside routing logic, but it makes copy changes a development task. Provider ownership can put presentation closer to its editors, while requiring a release check that verifies the hosted template still agrees with the application's variable set. Neither choice eliminates that check.

How should tenant forms validate email, SMS, and template variables before notification?

The first criterion is recipient validity. Parse incoming JSON before reading fields. Validate the resulting object, then validate the selected recipient channel. An email format check catches malformed addresses; it doesn't establish mailbox ownership or delivery. An E.164-shaped phone number isn't proof of an assigned number, SMS reachability, or permission to contact its owner. Don't quietly guess a country code from the property's location: a tenant may use a number from somewhere else.

Reject ambiguity early.

The second criterion is template completeness. A field existing is weaker than a field being useful. Reject an empty ticketId, a whitespace-only tenantName, and an unexpected variable name. Require the queue name to agree with the routing decision. JSON Schema can validate that a queue name is a string, but a string check alone cannot establish that a plumbing request belongs in maintenance. Keep that relationship explicit in the handler.

Structural validation and business validation have different jobs. A structural validator should produce field paths that a developer can act on. The handler should enforce relationships between fields. Avoid turning one configuration file into an entire workflow language just to express two queue mappings.

For debugging, separate malformed JSON, invalid recipient syntax, missing template variables, and a queue mismatch. They require different fixes. Record the schema version, template version, and validation category in diagnostic output; avoid copying the tenant's message or complete recipient details into routine logs. A rendering preview is evidence about placeholders. Sender guidelines address a separate delivery concern. Neither replaces input validation.

A Node.js contract for the tenant acknowledgment

This example validates an application-owned envelope, then reads the batch-email request schema for the adapter's next step. Save it as tenant-contract.ts. Install ajv, ajv-formats, and tsx, then run npx tsx tenant-contract.ts. Set INFRAI_API_ORIGIN to the API origin in your service configuration and INFRAI_API_KEY to your key. Discovery is public; the example demonstrates environment-based authorization for an adapter that will also make authenticated requests. The assertions exercise the local contract, including two strings that are valid JSON but invalid recipients.

The E.164 syntax limit is 15 digits after the plus sign. This pattern checks shape; it doesn't validate national numbering plans.

import assert from "node:assert/strict";
import Ajv from "ajv";
import addFormats from "ajv-formats";

const schema = {
  type: "object",
  additionalProperties: false,
  required: ["schemaVersion", "category", "queue", "email", "phone", "variables"],
  properties: {
    schemaVersion: { const: 1 },
    category: { enum: ["plumbing", "billing"] },
    queue: { enum: ["maintenance", "accounts"] },
    email: { type: "string", format: "email" },
    phone: { type: "string", pattern: "^\\+[1-9][0-9]{1,14}$" },
    variables: {
      type: "object",
      additionalProperties: false,
      required: ["tenantName", "ticketId", "queueName"],
      properties: {
        tenantName: { type: "string", pattern: "\\S" },
        ticketId: { type: "string", pattern: "\\S" },
        queueName: { enum: ["maintenance", "accounts"] }
      }
    }
  }
} as const;

const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
const validate = ajv.compile(schema);

type Contact = {
  schemaVersion: 1;
  category: "plumbing" | "billing";
  queue: "maintenance" | "accounts";
  email: string;
  phone: string;
  variables: {
    tenantName: string;
    ticketId: string;
    queueName: "maintenance" | "accounts";
  };
};

function parseContact(raw: string): Contact {
  const value: unknown = JSON.parse(raw);
  if (!validate(value)) {
    const paths = (validate.errors ?? []).map(
      error => `${error.instancePath || "/"}: ${error.keyword} ${error.message}`
    );
    throw new Error(paths.join("; "));
  }
  const contact = value as Contact;
  const expected = contact.category === "plumbing"
    ? "maintenance" : "accounts";
  if (contact.queue !== expected || contact.variables.queueName !== expected) {
    throw new Error("Queue does not match the contact category");
  }
  return contact;
}

const fixture = {
  schemaVersion: 1,
  category: "plumbing",
  queue: "maintenance",
  email: "tenant@example.com",
  phone: "+12025550123",
  variables: {
    tenantName: "Alex",
    ticketId: "DEMO-1042",
    queueName: "maintenance"
  }
};

assert.equal(parseContact(JSON.stringify(fixture)).queue, "maintenance");
assert.throws(() => parseContact("{"));
assert.throws(() => parseContact(JSON.stringify({ ...fixture, email: "invalid" })));
assert.throws(() => parseContact(JSON.stringify({ ...fixture, phone: "2025550123" })));
assert.throws(() => parseContact(JSON.stringify({
  ...fixture, variables: { ...fixture.variables, tenantName: " " }
})));
assert.throws(() => parseContact(JSON.stringify({ ...fixture, queue: "accounts" })));
console.log("Six contract checks passed; no notification sent.");

async function readRequestContract(): Promise<unknown> {
  const origin = process.env.INFRAI_API_ORIGIN;
  const key = process.env.INFRAI_API_KEY;
  if (!origin || !key) throw new Error("Set the API origin and API key");
  const url = new URL("/v1/discovery/email.batch.send", origin);
  if (url.protocol !== "https:") throw new Error("HTTPS is required");
  for (let attempt = 0; attempt < 3; attempt++) {
    const response = await fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${key}` }
    });
    if (response.status === 429 && attempt < 2) {
      const retry = response.headers.get("Retry-After");
      const seconds = retry === null ? NaN : Number(retry);
      const date = retry === null ? NaN : Date.parse(retry);
      const requested = Number.isFinite(seconds) ? seconds * 1000
        : Number.isFinite(date) ? date - Date.now() : 0;
      const delay = Math.max(1000 * 2 ** attempt, requested, 0);
      await response.text();
      await new Promise(resolve => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) {
      throw new Error(`Discovery ${response.status}: ${await response.text()}`);
    }
    const manifest: unknown = await response.json();
    if (!manifest || typeof manifest !== "object" || !("params" in manifest)) {
      throw new Error("Discovery response has no request contract");
    }
    return manifest.params;
  }
  throw new Error("Discovery retry budget exhausted");
}

readRequestContract().then(contract => {
  console.log(JSON.stringify(contract, null, 2));
}).catch(error => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

The sample requires both channels because this fixture represents an acknowledgment prepared for email and SMS. A form that offers only one channel needs a contract expressing that choice. Don't add a dummy phone number to satisfy the validator. The phone fixture above is illustrative, not a delivery target.

Six assertions establish narrow behavior. They don't measure provider performance. To benchmark the developer experience, time a fresh checkout from dependency installation to the first passing fixture, then record how long a template rename takes to diagnose. For runtime evaluation, measure validation separately from network calls and keep provider, channel, and test conditions with the results. There are no measured latency results here.

After validation, map the envelope into the chosen provider's documented request shape. Preview the email with the same fixture variables. Give a logical notification a stable application identifier, use the provider's documented idempotency mechanism where supported, and preserve that identity across retries. Handle HTTP 429 with backoff and honor Retry-After; reject malformed input instead of retrying it. The example makes at most 3 discovery attempts, with a 1000 ms initial backoff floor that doubles on each retry; that is a local retry budget, not a service performance claim. Acceptance and delivery remain separate states.

When provider-owned templates are the better choice

Application-owned rendering is the default choice when developers own acknowledgment copy and want changes reviewed with the routing contract. Provider-owned presentation is the runner-up when support needs to revise wording independently. It wins when a deployment for every copy edit costs more coordination than maintaining a template release check.

SendGrid Dynamic Templates fits an email-centered workflow where the hosted email template is the artifact editors maintain. Twilio Content Templates fits a messaging-centered workflow where content and its supplied variables need to agree. Amazon SES templates fits a team that wants its email templates managed through SES and can put rendering checks into its release process. These are different ownership arrangements, not evidence that one service validates the tenant's business rules better. Keep the maintenance-versus-accounts decision in the application for all three.

A template rename is the concrete trap. Suppose an editor changes queueName to supportQueue while the handler still sends the old variable. JSON parsing succeeds. Recipient syntax checks succeed. The release should still fail its rendering fixture before the new template becomes active. Keep an application registry of approved template versions and their required variable sets; use it as a release artifact rather than expecting a provider's template inventory to define your contract.

Keep authentication separate, too. A contact-form acknowledgment is an event notification, not proof of mailbox ownership or a fallback sign-in flow. If the property portal needs verification, specify and evaluate that workflow separately. Cross-channel timing, sender setup, recipient consent, and regional delivery requirements also need their own acceptance criteria; a successful preview settles none of them.

Choose the owner first. Then benchmark how quickly a developer can diagnose an invalid recipient and how reliably an editor can ship a variable rename. Those two exercises tell this form team more than an unmeasured promise about sending speed.

References

The template documentation below supports the ownership comparison. Google covers sender requirements; NIST covers the separate authentication question. Neither is a substitute for the application's payload contract.

Sources

Top comments (0)