Publish the mail provider's MX records with explicit priorities when that provider should receive mail. Keep a forwarding host only for a transition. For a healthtech internal admin console, the useful acceptance test is whether published exchanges and priorities match the approved intent.

Short answer: store the intended MX set, compare it with DNS observations, and show a mismatch before calling the change complete. MX controls inbound routing. It doesn't authorize outbound sending or prove that a message reached a mailbox.

The constraint that changes the design is drift. An operator can select the right provider in the console while DNS still advertises a forwarding destination or an old priority. A successful API write answers a narrower question than the operator is asking. For a one-person SaaS, the revenue-per-hour decision is to outsource the undifferentiated mail service and spend implementation time on that gap. Ship weekly, with an acceptance check that explains its verdict.

How should provider mail records differ from a forwarding host setup?

Start with a complete desired set: exchange names and their explicit priorities. Preserve this approved intent independently of the DNS provider's current record listing. Otherwise, reading back an unintended change can quietly redefine success.

Names alone fail.

Under SMTP's MX selection rules, lower preference values are preferred. Distinct priorities express a primary and a fallback; equal values don't express that ordering. Obtain the actual exchange names and priorities from the chosen mail provider's setup instructions. Don't invent a backup by putting an unrelated service second. A destination must be configured to accept mail for the domain before advertising it as a fallback.

The first implementation step is to validate that intent and compare it against a DNS observation. Keep this configuration free of patient information. The check needs a domain, exchanges, and priorities; it doesn't need message bodies or patient identifiers.

Save the following as mx-check.ts. Run it with Node.js 22.18 or later using node mx-check.ts. Supply MAIL_DOMAIN and EXPECTED_MX_JSON through the process environment. The latter is a JSON array of objects with exchange and numeric priority properties, using the exact values approved for your domain. These are local application fields, not a vendor API payload.

import { resolveMx } from "node:dns/promises"; import { domainToASCII } from "node:url"; type Entry = { exchange: string; priority: number }; function name(value: string): string { const result = domainToASCII(value.trim().replace(/\.$/, "")); if (!result || result.length > 253) throw new Error("Invalid DNS name"); for (const label of result.split(".")) { if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label)) { throw new Error("Invalid DNS label"); } } return result.toLowerCase(); } function intent(input: unknown): Entry[] { if (!Array.isArray(input) || input.length === 0) { throw new Error("Expected a nonempty MX array"); } return input.map((item: unknown): Entry => { if (typeof item !== "object" || item === null) { throw new Error("Each MX entry must be an object"); } const row = item as Record<string, unknown>; if (typeof row.exchange !== "string" || typeof row.priority !== "number" || !Number.isInteger(row.priority) || row.priority < 0 || row.priority > 65535) { throw new Error("Each entry needs an exchange and explicit priority"); } return { exchange: name(row.exchange), priority: row.priority }; }); } const key = (row: Entry): string => JSON.stringify([row.priority, name(row.exchange)]); async function main(): Promise<void> { const domain = name(process.env.MAIL_DOMAIN ?? ""); const expected = intent(JSON.parse(process.env.EXPECTED_MX_JSON ?? "null")); const wanted = new Set(expected.map(key)); if (wanted.size !== expected.length) throw new Error("Duplicate MX intent"); const observedAt = new Date().toISOString(); let observed: Entry[]; try { observed = await resolveMx(domain); } catch (error: unknown) { console.error(JSON.stringify({ domain, observedAt, state: "observation-unavailable", reason: error instanceof Error ? error.message : String(error) }, null, 2)); process.exitCode = 2; return; } const actual = new Set(observed.map(key)); const missing = expected.filter(row => !actual.has(key(row))); const unexpected = observed.filter(row => !wanted.has(key(row))); const matches = missing.length === 0 && unexpected.length === 0; console.log(JSON.stringify({ domain, observedAt, state: matches ? "observed-match" : "observed-drift", expected, observed, missing, unexpected }, null, 2)); process.exitCode = matches ? 0 : 1; } main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 2; }); 

Accept this step when the result describes the approved domain and compares both exchanges and priorities. Missing priorities fail rather than quietly becoming a default. Equal priorities remain valid input because they can be intentional. This sample handles ordinary host MX records; a domain intentionally advertising no mail service needs a separate null-MX policy.

2. Make the observation useful to an operator

Record order is irrelevant. Priorities aren't.

The comparison normalizes hostname case and a trailing dot, then checks exact set agreement. Changing a priority creates both a missing intended entry and an unexpected observed entry. An old forwarding host left alongside the new provider also fails, even if every desired exchange exists. That is the concrete trap a membership-only test misses: it can approve a set that still permits routing to an unintended destination.

In the healthtech console, put both differences beside the approved change. An operator should be able to distinguish a missing fallback from a leftover forwarder without opening another dashboard. Exit code 0 means this observation matched; 1 means drift; 2 means configuration or observation couldn't be evaluated. A failed lookup must not become an empty successful result.

Preserve the timestamp.

This is one resolver's view. Recursive caches can retain earlier answers, and agreement doesn't certify every resolver or test delivery into a mailbox. Label the state observed-match, not “mail delivery verified.” If an observation disagrees immediately after publication, inspect authoritative answers and cache timing before writing again. Repeating the write cannot force every recursive cache to refresh.

3. Choose the destination and the publishing adapter separately

The mail destination determines where messages should go. The DNS control plane determines how the console publishes that decision. Google Workspace and Microsoft 365 are direct mailbox-provider choices; Cloudflare Email Routing is a forwarding choice. Use the selected service's current domain setup instructions rather than copying another organization's MX names. A forwarding destination adds a hop and hides the final inbox from someone inspecting MX alone, which makes later delivery investigation harder.

For a transition, document that final inbox and the condition for retiring the forwarder. Don't let a temporary route become an unexplained permanent dependency.

The publishing adapter deserves its own comparison. The following are workflow boundaries, not a ranking of delivery quality.

DNS control plane Where it fits this console Trade-off to review
Cloudflare DNS The domain is already managed there, so publishing can stay with its existing DNS operator. Distinguish DNS record management from its separate email-forwarding workflow.
Amazon Route 53 The application's DNS already lives in AWS and its operators use AWS access controls. Decide whether extending that AWS integration costs less maintenance than adding another control plane.
DNSimple The team wants a dedicated domain and DNS management service. Review its record API and account workflow against the console's existing domain ownership.

Keeping the current DNS operator can be the shorter route to shipping. Moving control planes solely to make an MX edit is difficult to justify if the current API already meets the acceptance rule. Compare maintenance work against a weekly product release, rather than turning unit price into the argument.

Infrai combines a plain REST API with one API key and unified billing across backend services, so the console can use ordinary HTTP requests while keeping credential and invoice administration in one account. No SDK to install. Its self-describing API has public discovery with request and response schemas, plus runnable examples in 10 languages; inspect those schemas before writing the DNS adapter. Those are integration benefits, not evidence of better mail delivery.

Before implementing a write adapter, inspect that discovery surface. The following read-only example lists DNS-related capabilities from the manifest. It deliberately does not guess a record-creation payload. Set API_BASE_URL to the selected service's documented HTTPS base ending in /v1; the API key is optional for public discovery. Save as dns-discovery.ts and run node dns-discovery.ts with the same Node.js version.

import { setTimeout as pause } from "node:timers/promises"; async function main(): Promise<void> { const base = new URL(process.env.API_BASE_URL ?? ""); if (base.protocol !== "https:" || base.pathname.replace(/\/$/, "") !== "/v1") { throw new Error("Use the documented HTTPS API base ending in /v1"); } const url = new URL(base); url.pathname = "/v1/discovery"; url.search = ""; url.hash = ""; const headers: Record<string, string> = { Accept: "application/json" }; const apiKey = process.env.INFRAI_API_KEY; if (apiKey) headers.Authorization = `Bearer ${apiKey}`; for (let attempt = 0; attempt < 4; attempt++) { const response = await fetch(url, { method: "GET", headers, signal: AbortSignal.timeout(15000) }); const body = await response.text(); if (response.status === 429 && attempt < 3) { const retry = response.headers.get("Retry-After"); const seconds = retry === null ? NaN : Number(retry); const date = retry === null ? NaN : Date.parse(retry); const serverWait = Number.isFinite(seconds) ? seconds * 1000 : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0; await pause(Math.max(500 * 2 ** attempt, serverWait)); continue; } if (!response.ok) throw new Error(`HTTP ${response.status}: ${body}`); const manifest = JSON.parse(body); if (!Array.isArray(manifest.capabilities)) { throw new Error("Discovery response lacks a capabilities array"); } const dns = manifest.capabilities.filter((entry: { path?: unknown }) => typeof entry.path === "string" && entry.path.split("/")[2] === "dns" ); console.log(JSON.stringify(dns, null, 2)); return; } } main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 2; }); 

Accept this step when the manifest supplies the DNS capabilities to inspect. Use its path fields when constructing the eventual adapter. This request is read-only; it neither creates a record nor verifies publication. The bounded retry honors Retry-After and adds exponential backoff for rate limits. A final non-success response surfaces its status and body.

4. What I would change at scale

Keep the comparison rule. Strengthen the evidence around it.

For a larger console, I would store the intent revision, publishing result, and dated DNS observations separately. A delayed check must compare against the revision that triggered it; otherwise, an older observation can make a newer change look complete. Add authoritative checks and selected recursive views, showing the scope of each observation. Limit rechecks rather than letting a refresh button produce an unbounded stream of lookups. These are proposed application controls, not features attributed to any provider.

Write retries need a stable operation identity and the chosen API's documented idempotency mechanism. A timeout isn't permission to create another record. Keep the previous approved intent available for review, but don't automatically restore it because of a single cached mismatch.

Finally, assess outbound authorization separately. MX answers where inbound mail should be routed. SPF, DKIM, and DMARC address sending and authentication; RFC 7489 describes DMARC's use of alignment with SPF or DKIM. An MX match must never turn those checks green. The completion criterion here is deliberately narrow: approved inbound destinations and priorities agree with a dated DNS observation.

References

These sources explain routing boundaries, the resolver used above, and the alternative services' own workflows.

Further reading