Skip to content

Email for professionals and teams

fix(domains): confirm and retry on MX conflict when adding domain

rome-xi34a1733c6ca9
diff --git a/src/app/(admin)/domains/api.ts b/src/app/(admin)/domains/api.ts
index c5fc98b..1c23992 100644
--- a/src/app/(admin)/domains/api.ts
+++ b/src/app/(admin)/domains/api.ts
@@ -27,9 +27,16 @@ type SetupResponse = { error?: string; code?: string; records?: { content: strin
/** Whether a response is a 409 MX_CONFLICT the user agreed to resolve by replacing the listed MX records. */
export function confirmMxReplacement(response: Response, data: SetupResponse): boolean {
- if (response.status !== 409 || data.code !== "MX_CONFLICT") return false;
+ if (response.status !== 409 || (data.code !== "MX_CONFLICT" && data.code !== "MX_RECORDS_CONFLICT")) return false;
const list = (data.records ?? []).map((record) => ` ${record.priority} ${record.content}`).join("\n");
- return window.confirm(`${data.error}\n\n${list}\n\nReplace them? Mail will stop going to the current service.`);
+ const details = list ? `\n\n${list}` : "";
+ return window.confirm(`${data.error}${details}\n\nReplace them? Mail will stop going to the current service.`);
+}
+
+export function isMxConflictError(error: unknown): boolean {
+ if (!(error instanceof ApiError) || !error.data || typeof error.data !== "object") return false;
+ const code = (error.data as { code?: unknown }).code;
+ return code === "MX_CONFLICT" || code === "MX_RECORDS_CONFLICT";
}
/**
@@ -54,3 +61,38 @@ export async function runReceivingSetup(domainId: string, provider: "cloudflare"
if (!response.ok) throw new Error(data.error ?? defaultTranslator("domains.setupFailed"));
return true;
}
+
+export type CreateDomainInput = {
+ hostname: string;
+ enableRouting?: boolean;
+ enableSending?: boolean;
+ replaceMxRecords?: boolean;
+ skipDns?: boolean;
+ sendingProvider?: "none" | "cloudflare" | "resend" | "ses";
+ receivingProvider?: "none" | "cloudflare" | "resend" | "ses";
+};
+
+export type DomainCreateResponse = SetupResponse & { domain?: unknown; [key: string]: unknown };
+
+/**
+ * Creates a domain. On a 409 MX conflict, confirms replacement with the user
+ * and retries with replaceMxRecords set.
+ */
+export async function createDomain(input: CreateDomainInput): Promise<DomainCreateResponse> {
+ const call = async (replaceMxRecords: boolean) => {
+ const response = await authFetch("/api/domains", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(replaceMxRecords ? { ...input, replaceMxRecords: true } : input),
+ });
+ const data = (await response.json()) as DomainCreateResponse;
+ return { response, data };
+ };
+
+ let { response, data } = await call(false);
+ if (confirmMxReplacement(response, data)) {
+ ({ response, data } = await call(true));
+ }
+ if (!response.ok) throw new ApiError(data.error ?? defaultTranslator("mailboxes.failed"), data);
+ return data;
+}
diff --git a/src/app/(admin)/domains/page.tsx b/src/app/(admin)/domains/page.tsx
index 1f04acd..dd473a7 100644
--- a/src/app/(admin)/domains/page.tsx
+++ b/src/app/(admin)/domains/page.tsx
@@ -23,7 +23,7 @@ import type { DnsAuthRecord, DnsStatusSummary, Domain, DomainDnsCache, DomainDns
import DomainItemCard from "./DomainItemCard";
import { SectionRowSkeleton } from "@/components/page-skeletons";
import { checkDomain } from "./utils";
-import { confirmMxReplacement } from "./api";
+import { confirmMxReplacement, createDomain, isMxConflictError } from "./api";
export default function DomainsPage() {
const { t } = useLanguage();
@@ -77,20 +77,13 @@ export default function DomainsPage() {
}
if (!checkedDomain) throw new Error(t("onboarding.domainCheckFailed"));
- const res = await authFetch("/api/domains", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- hostname: checkedDomain.hostname,
- enableRouting: true,
- skipDns,
- sendingProvider,
- receivingProvider,
- }),
+ return createDomain({
+ hostname: checkedDomain.hostname,
+ enableRouting: true,
+ skipDns,
+ sendingProvider,
+ receivingProvider,
});
- const json = (await res.json()) as { error?: string };
- if (!res.ok) throw new Error(json.error ?? t("mailboxes.failed"));
- return json;
},
onSuccess: () => {
setHostname("");
@@ -403,19 +396,21 @@ export default function DomainsPage() {
{create.isError && (
<div className="space-y-3 rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">
<p>{(create.error as Error).message}</p>
- <div className="space-y-2">
- <p className="font-medium">
- {t("domains.tokenPermissions")}
- </p>
- <ul className="list-disc space-y-1 pl-5">
- <li>
- {t("domains.tokenAccounts")}
- </li>
- <li>
- {t("domains.tokenZones")}
- </li>
- </ul>
- </div>
+ {!isMxConflictError(create.error) && (
+ <div className="space-y-2">
+ <p className="font-medium">
+ {t("domains.tokenPermissions")}
+ </p>
+ <ul className="list-disc space-y-1 pl-5">
+ <li>
+ {t("domains.tokenAccounts")}
+ </li>
+ <li>
+ {t("domains.tokenZones")}
+ </li>
+ </ul>
+ </div>
+ )}
</div>
)}
<Button
diff --git a/tests/domain-add-retry.test.mjs b/tests/domain-add-retry.test.mjs
new file mode 100644
index 0000000..4c5d623
--- /dev/null
+++ b/tests/domain-add-retry.test.mjs
@@ -0,0 +1,281 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import test, { after } from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { build } from "esbuild";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+globalThis.localStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const outDir = mkdtempSync(join(root, "tests", ".tmp-domain-add-retry-"));
+after(() => rmSync(outDir, { recursive: true, force: true }));
+
+await build({
+ entryPoints: [join(root, "src/app/(admin)/domains/api.ts")],
+ outfile: join(outDir, "api.mjs"),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node24",
+ tsconfig: join(root, "tsconfig.json"),
+ packages: "external",
+ alias: { "@": join(root, "src") },
+ logLevel: "silent",
+});
+
+const apiModule = await import(pathToFileURL(join(outDir, "api.mjs")).href);
+const { confirmMxReplacement, ApiError } = apiModule;
+const defaultCreateDomain = async (input) => {
+ const res = await globalThis.fetch("/api/domains", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ });
+ const json = await res.json();
+ if (!res.ok) throw new (ApiError ?? Error)(json.error ?? "Failed", json);
+ return json;
+};
+const createDomain = apiModule.createDomain ?? defaultCreateDomain;
+const isMxConflictError = apiModule.isMxConflictError ?? (() => false);
+
+function createMockFetch(responses) {
+ const calls = [];
+ let index = 0;
+ const fetchMock = async (url, options = {}) => {
+ const callIndex = index++;
+ const spec = responses[callIndex] ?? responses[responses.length - 1];
+ const parsedBody = options.body ? JSON.parse(options.body) : undefined;
+ calls.push({ url: String(url), options, body: parsedBody });
+ return {
+ status: spec.status ?? 200,
+ ok: spec.ok ?? ((spec.status ?? 200) >= 200 && (spec.status ?? 200) < 300),
+ headers: new Headers(spec.headers ?? { "Content-Type": "application/json" }),
+ async json() {
+ return typeof spec.data === "function" ? spec.data(parsedBody) : (spec.data ?? {});
+ },
+ async text() {
+ return JSON.stringify(typeof spec.data === "function" ? spec.data(parsedBody) : (spec.data ?? {}));
+ },
+ };
+ };
+ return { fetchMock, calls };
+}
+
+test("confirmMxReplacement returns true for 409 MX_RECORDS_CONFLICT when confirmed", () => {
+ let prompt = null;
+ globalThis.window = {
+ confirm(message) {
+ prompt = message;
+ return true;
+ },
+ };
+ const res = new Response(null, { status: 409 });
+ const data = {
+ code: "MX_RECORDS_CONFLICT",
+ error: "Existing MX records currently deliver mail to another provider. Continue to delete them and replace them with Cloudflare Email Routing.",
+ };
+ const result = confirmMxReplacement(res, data);
+ assert.equal(result, true);
+ assert.equal(
+ prompt,
+ "Existing MX records currently deliver mail to another provider. Continue to delete them and replace them with Cloudflare Email Routing.\n\nReplace them? Mail will stop going to the current service.",
+ );
+});
+
+test("on 409 MX_RECORDS_CONFLICT (no records), when user confirms, retries with replaceMxRecords: true and succeeds", async () => {
+ const { fetchMock, calls } = createMockFetch([
+ {
+ status: 409,
+ ok: false,
+ data: {
+ error: "Existing MX records currently deliver mail to another provider.",
+ code: "MX_RECORDS_CONFLICT",
+ },
+ },
+ {
+ status: 200,
+ ok: true,
+ data: { domain: { id: "dom_123", hostname: "example.com" } },
+ },
+ ]);
+ globalThis.fetch = fetchMock;
+
+ let confirmPrompt = null;
+ globalThis.window = {
+ confirm(message) {
+ confirmPrompt = message;
+ return true;
+ },
+ };
+
+ const input = {
+ hostname: "example.com",
+ enableRouting: true,
+ skipDns: false,
+ sendingProvider: "cloudflare",
+ receivingProvider: "cloudflare",
+ };
+
+ const result = await createDomain(input);
+ assert.deepEqual(result, { domain: { id: "dom_123", hostname: "example.com" } });
+ assert.equal(calls.length, 2, "must make initial request and one retry request");
+ assert.equal(calls[0].url, "/api/domains");
+ assert.equal(calls[0].body.replaceMxRecords, undefined);
+ assert.equal(calls[0].body.hostname, "example.com");
+ assert.equal(calls[0].body.enableRouting, true);
+ assert.equal(calls[0].body.skipDns, false);
+ assert.equal(calls[0].body.sendingProvider, "cloudflare");
+ assert.equal(calls[0].body.receivingProvider, "cloudflare");
+ assert.equal(calls[1].url, "/api/domains");
+ assert.equal(calls[1].body.replaceMxRecords, true);
+ assert.equal(calls[1].body.hostname, "example.com");
+ assert.equal(calls[1].body.enableRouting, true);
+ assert.equal(calls[1].body.skipDns, false);
+ assert.equal(calls[1].body.sendingProvider, "cloudflare");
+ assert.equal(calls[1].body.receivingProvider, "cloudflare");
+ assert.equal(
+ confirmPrompt,
+ "Existing MX records currently deliver mail to another provider.\n\nReplace them? Mail will stop going to the current service.",
+ );
+});
+
+test("on 409 MX_RECORDS_CONFLICT, when user declines, does not retry and throws ApiError", async () => {
+ const { fetchMock, calls } = createMockFetch([
+ {
+ status: 409,
+ ok: false,
+ data: {
+ error: "Existing MX records currently deliver mail to another provider.",
+ code: "MX_RECORDS_CONFLICT",
+ },
+ },
+ ]);
+ globalThis.fetch = fetchMock;
+
+ let confirmed = false;
+ globalThis.window = {
+ confirm() {
+ confirmed = true;
+ return false;
+ },
+ };
+
+ const input = {
+ hostname: "example.com",
+ enableRouting: true,
+ skipDns: false,
+ sendingProvider: "cloudflare",
+ receivingProvider: "cloudflare",
+ };
+
+ await assert.rejects(
+ async () => createDomain(input),
+ (err) => {
+ assert.ok(err instanceof ApiError);
+ assert.equal(err.message, "Existing MX records currently deliver mail to another provider.");
+ assert.equal(isMxConflictError(err), true);
+ return true;
+ },
+ );
+
+ assert.equal(confirmed, true, "user must be prompted to confirm");
+ assert.equal(calls.length, 1, "must not retry when user declines replacement");
+});
+
+test("supports 409 MX_CONFLICT with records list for per-domain flows", async () => {
+ const { fetchMock, calls } = createMockFetch([
+ {
+ status: 409,
+ ok: false,
+ data: {
+ error: "This domain has MX records for another mail service.",
+ code: "MX_CONFLICT",
+ records: [
+ { priority: 10, content: "mail.legacy.test" },
+ { priority: 20, content: "mail2.legacy.test" },
+ ],
+ },
+ },
+ {
+ status: 200,
+ ok: true,
+ data: { domain: { id: "dom_456", hostname: "custom.test" } },
+ },
+ ]);
+ globalThis.fetch = fetchMock;
+
+ let confirmPrompt = null;
+ globalThis.window = {
+ confirm(message) {
+ confirmPrompt = message;
+ return true;
+ },
+ };
+
+ const result = await createDomain({ hostname: "custom.test" });
+ assert.deepEqual(result, { domain: { id: "dom_456", hostname: "custom.test" } });
+ assert.equal(calls.length, 2, "must retry with replace flag");
+ assert.equal(calls[1].body.replaceMxRecords, true);
+ assert.ok(confirmPrompt && confirmPrompt.includes(" 10 mail.legacy.test\n 20 mail2.legacy.test"));
+});
+
+test("on non-MX 409 or other errors, does not prompt and throws without retry", async () => {
+ const { fetchMock, calls } = createMockFetch([
+ {
+ status: 409,
+ ok: false,
+ data: {
+ error: "Domain is already registered",
+ code: "DOMAIN_EXISTS",
+ },
+ },
+ ]);
+ globalThis.fetch = fetchMock;
+
+ globalThis.window = {
+ confirm() {
+ throw new Error("confirm must not be called for non-MX conflicts");
+ },
+ };
+
+ await assert.rejects(
+ async () => createDomain({ hostname: "example.com" }),
+ (err) => {
+ assert.ok(err instanceof ApiError);
+ assert.equal(isMxConflictError(err), false);
+ return true;
+ },
+ );
+ assert.equal(calls.length, 1, "must not retry non-MX conflict");
+
+ // 500 error
+ const serverErrorMock = createMockFetch([
+ {
+ status: 500,
+ ok: false,
+ data: { error: "Internal Server Error" },
+ },
+ ]);
+ globalThis.fetch = serverErrorMock.fetchMock;
+
+ await assert.rejects(
+ async () => createDomain({ hostname: "example.com" }),
+ (err) => {
+ assert.ok(err instanceof ApiError);
+ assert.equal(isMxConflictError(err), false);
+ return true;
+ },
+ );
+ assert.equal(serverErrorMock.calls.length, 1, "must not retry on 500 error");
+});
+
+test("isMxConflictError helper correctly detects MX conflict errors for UI checklist suppression", () => {
+ assert.equal(isMxConflictError(new ApiError("conflict", { code: "MX_CONFLICT" })), true);
+ assert.equal(isMxConflictError(new ApiError("conflict", { code: "MX_RECORDS_CONFLICT" })), true);
+ assert.equal(isMxConflictError(new ApiError("forbidden", { code: "FORBIDDEN" })), false);
+ assert.equal(isMxConflictError(new ApiError("other", {})), false);
+ assert.equal(isMxConflictError(new Error("standard error")), false);
+ assert.equal(isMxConflictError(null), false);
+ assert.equal(isMxConflictError(undefined), false);
+});