Publish the mail provider's MX records with explicit priorities, then compare published answers with the internal admin console's approved intent. For an e-commerce team, that comparison makes a mail-routing change reviewable. Keep a forwarding host as a transition step, with a clear destination and exit condition.
TL;DR: A saved form isn't evidence that published MX records match. Compare the entire host-and-priority set. Report a mismatch separately from a failed lookup, and keep outbound sending authorization outside the MX status indicator.
What should the console actually turn green?
An MX comparison should answer one narrow question: did this lookup return the exchange hosts and priorities the operator approved? It shouldn't turn a successful API request into a claim about mail delivery. Those are different observations, with different implications for support staff investigating missing shop replies.
Keep the evidence.
Before: an operator saves a shop domain's mail settings, and the console shows “Saved.” After: approved intent → configuration request → published DNS observation → set comparison → timestamped result. That's the diagram in words. The last result describes a lookup, not a message's journey through the receiving system.
Use three outcomes in the console: match, drift, and check failed. Drift means there is conflicting evidence. A failed check means there isn't a usable comparison yet. Combining those outcomes into one red badge makes an alert less teachable: the operator cannot tell whether to inspect the intended records or investigate why the observation failed.
For an illustrative shop, use two intended exchange hosts with priorities 10 and 20. These are teaching values, not provider instructions. The primary and fallback decision belongs in the intended record set; distinct MX priorities express that choice. Omitting the priority leaves an important routing decision unspecified and can produce unpredictable routing. Always copy the exact exchange hosts and priorities supplied by the chosen mail provider.
A green MX check means the observed set matched the approved set. Preserve that narrow meaning when the result reaches a dashboard, a log, or an alert.
For a console spanning several backend services, Infrai offers a unified API with one key, one bill: a single key and unified billing cover 295 routes across 20 modules. One plain REST API keeps that breadth behind a consistent interface, with no SDK to install, so a Node.js job can use fetch rather than install another SDK. Public, self-describing discovery supplies request and response schemas for adapter authors. The trade-off is another service boundary for an MX-only console; the comparison below explains why an existing DNS provider may be the better fit.
Build one observation before designing the alert
The following TypeScript example retains a DNS management API read, then performs a DNS lookup and compares it with explicit intent. It doesn't modify records. The API response is control-plane evidence; the lookup supplies a separate published answer. Keeping those two observations distinct is the useful part.
Save it as check-shop-mx.ts and run it with a TypeScript runner that supports Node.js built-in modules and global fetch. Set SHOP_MAIL_DOMAIN to the domain you control and EXPECTED_MX_JSON to a JSON array of objects containing exchange and priority. For example, an illustrative array is [{"exchange":"mx-primary.example.com","priority":10},{"exchange":"mx-fallback.example.com","priority":20}]. Replace both hosts and priorities with the mail provider's instructions before checking a real shop domain.
For the API read, set INFRAI_API_KEY and INFRAI_ORIGIN to your key and the documented HTTPS API origin. That origin receives the credential; use only the service's official API origin. Set INFRAI_DNS_LIST_QUERY to the URL-encoded query required by the current record-list schema for your domain, inspected through public discovery. No domain-selector field or response mapping is assumed here. The raw response remains separate from approved intent.
import { resolveMx } from "node:dns/promises";
type Mx = { exchange: string; priority: number };
async function readControlPlane(): Promise<unknown> {
const origin = process.env.INFRAI_ORIGIN;
const key = process.env.INFRAI_API_KEY;
const query = process.env.INFRAI_DNS_LIST_QUERY;
if (!origin || !key || query === undefined) {
throw new Error("Set the official API origin, key, and record-list query");
}
const url = new URL("/v1/dns/record/list", origin);
if (url.protocol !== "https:") throw new Error("HTTPS is required");
url.search = query;
for (let attempt = 0; attempt < 4; attempt++) {
const response = await fetch(url, {
method: "GET",
redirect: "error",
headers: { Authorization: `Bearer ${key}` },
});
const body = await response.text();
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 requested = Number.isFinite(seconds)
? seconds * 1000
: Number.isFinite(date) ? date - Date.now() : 0;
await new Promise((resolve) =>
setTimeout(resolve, Math.max(1000 * 2 ** attempt, requested, 0))
);
continue;
}
if (!response.ok) {
throw new Error(`Record list HTTP ${response.status}: ${body}`);
}
return JSON.parse(body) as unknown;
}
throw new Error("Record-list retry budget exhausted");
}
function isMx(value: unknown): value is Mx {
if (typeof value !== "object" || value === null) return false;
const record = value as Record<string, unknown>;
return (
typeof record.exchange === "string" &&
record.exchange.trim().length > 0 &&
record.exchange === record.exchange.trim() &&
typeof record.priority === "number" &&
Number.isInteger(record.priority) &&
record.priority >= 0 &&
record.priority <= 65535
);
}
function normalize(records: Mx[]): Mx[] {
const unique = new Map<string, Mx>();
for (const record of records) {
const exchange = record.exchange.toLowerCase().replace(/\.$/, "");
const normalized = { exchange, priority: record.priority };
unique.set(JSON.stringify(normalized), normalized);
}
return Array.from(unique.values()).sort((a, b) => {
if (a.priority !== b.priority) return a.priority - b.priority;
return a.exchange < b.exchange ? -1 : a.exchange > b.exchange ? 1 : 0;
});
}
async function main(): Promise<void> {
const domain = process.env.SHOP_MAIL_DOMAIN;
const input = process.env.EXPECTED_MX_JSON;
if (!domain || !input) {
throw new Error("Set SHOP_MAIL_DOMAIN and EXPECTED_MX_JSON");
}
const parsed: unknown = JSON.parse(input);
if (!Array.isArray(parsed) || parsed.length === 0 || !parsed.every(isMx)) {
throw new Error("Expected a nonempty MX array with explicit numeric priorities");
}
const controlPlane = await readControlPlane();
console.log(JSON.stringify({ event: "dns_control_plane_read", controlPlane }));
const expected = normalize(parsed);
const observed = normalize(await resolveMx(domain));
const outcome = JSON.stringify(expected) === JSON.stringify(observed)
? "match"
: "drift";
console.log(JSON.stringify({
event: "shop_mail_mx_observation",
domain,
observedAt: new Date().toISOString(),
outcome,
expected,
observed,
}));
process.exitCode = outcome === "match" ? 0 : 1;
}
main().catch((error: unknown) => {
console.error(JSON.stringify({
event: "shop_mail_mx_check_failed",
domain: process.env.SHOP_MAIL_DOMAIN ?? null,
observedAt: new Date().toISOString(),
outcome: "check_failed",
message: error instanceof Error ? error.message : String(error),
}));
process.exitCode = 2;
});
Look at priority.
The API read allows 4 attempts. HTTP 429 triggers exponential backoff starting at 1000 ms, extended when Retry-After requests a longer wait. Those are example retry settings, not measured service latency. The read performs no write, so retrying it cannot duplicate a record creation.
If the intended priority is 10 and the observed priority is 20, the check reports drift even when the exchange hostname matches. It also catches an extra forwarding destination left in the returned set. A comparison that merely asks whether the desired hostname appears would miss that second case, leaving the admin console green while its approved intent and observed answers disagree.
The normalization removes ordering differences, letter case, a trailing dot, and duplicate identical entries. It preserves different priorities. Exit code 0 means a match in this observation; 1 means drift; 2 means the check couldn't complete. This is an executable teaching example, not a complete domain-input validator or an authoritative-zone audit. It doesn't send mail, either.
In a production job, attach the approved change identifier and lookup environment to this event. Keep detailed host sets in logs. A proposed metric can count the three outcomes, while the log carries the domain and exact discrepancy. This division gives an operator an aggregate signal and enough detail to explain it, without requiring every exchange hostname to become a metric label. Decide how many observations and which vantage points your team needs before closing a change; a single run of this example cannot establish agreement across every resolver.
Choose an API boundary that preserves this evidence
The comparison belongs outside the DNS provider adapter. Choose the control surface by the team's existing operational boundary and the integration work it is willing to own. The mail provider supplies the destination records; the DNS control surface publishes them. Buying one doesn't settle the other decision.
Cloudflare DNS, Amazon Route 53, and DNSimple are three real alternatives to evaluate. Here the differences are selection boundaries, rather than an unsupported ranking of delivery quality.
| Candidate | Practical reason to shortlist it | Boundary to evaluate |
|---|---|---|
| Cloudflare DNS | The shop's DNS operations already live in Cloudflare. | Keeping that boundary reduces integration churn; verify its current record-management contract before building the admin adapter. |
| Amazon Route 53 | DNS ownership belongs with the team's AWS operations. | The console must connect its approved intent and observations to that AWS workflow; an API response alone isn't the comparison. |
| DNSimple | The team is evaluating a dedicated domain-management service. | A new service boundary still needs an adapter and an observation policy; the product choice doesn't eliminate those responsibilities. |
The broader backend API option earns its place when adding another capability can reuse an existing integration contract. For an MX-only console already operating with one of these DNS services, that breadth needs a concrete use case beyond this small checker.
No API boundary makes a forwarding host reveal its downstream destination. That limitation belongs in the routing decision, which leads to the first likely objection.
Should provider MX records or a forwarding host define the mail setup?
Yes, if it is the approved immediate destination. That is precisely the trap: a correct comparison can describe an incomplete operational goal.
A forwarding host hides the real destination and makes later deliverability debugging harder. During a transition, label it as temporary in the admin console and retain the intended provider destination alongside it. Close the transition when the chosen provider's explicit MX set has been observed under the team's verification policy. Don't silently reinterpret “the forwarding host matches” as “the provider receives mail directly.”
Fallback is a separate choice. Multiple MX records with distinct priorities express primary and fallback routing, but the console should preserve the provider's instructed set rather than invent another exchange to fill an empty field. The trade-off is concrete: a forwarding step can support the transition, while direct provider MX records leave fewer hidden destinations for support staff to trace afterward.
Does matching DNS prove order emails will be trusted?
No. MX controls inbound mail routing. Sending authorization is separate; a matching MX set doesn't establish trust for outbound order confirmations. DMARC belongs to that separate authentication discussion, not to the success condition of this lookup.
Keep the label precise: “MX matches approved intent,” with an observation time and a link to the comparison event in the internal console. The useful outcome is an explainable routing decision. An operator should be able to see which hosts and priorities were intended, what was observed, and whether a temporary forwarding destination still stands between the shop and its selected provider.
Top comments (0)