VoiceDash 白標 SaaS 加入自訂網域:應用程式假設自身主機的各個環節
Custom Domains for My White-Label SaaS: Every Place My App Assumed Its Own Host
VoiceDash 為白標 SaaS 加入自訂網域支援,並梳理應用程式假設所有請求都來自自身主機所造成的問題。Auth.js 會把 req.url 改寫為應用程式設定的來源,令自訂網域訪客重新導向至 VoiceDash 網域;作者改用 Host 標頭建立重新導向,並讓登出後在目前網域跳轉。
VoiceDash is a white-label portal for agencies that resell Retell voice agents: the agency's clients log in, see their calls, transcripts and analytics, and never see the word VoiceDash. That last part is the whole product. In October, agencies told me their white-label settings barely showed, and the biggest missing piece was custom domains. An agency wanted portal.theiragency.com, not a link on my domain with a ?w= workspace id in the query string.
I shipped it in one afternoon, then spent the next eighty minutes finding all the places my app quietly assumed it lived on exactly one host. This is that list, with the real code from the repo.
The data model is the easy part
A custom domain is a row that maps a host name to a workspace, and optionally to a single client:
model CustomDomain {
id String @id @default(cuid())
/// Lower-case host name, without scheme, port or path.
domain String @unique
workspaceId String
/// Set when the domain is one client's portal: only that client's members
/// can sign in on it. Otherwise it serves all the agency's clients.
clientId String?
createdAt DateTime @default(now())
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
client Client? @relation(fields: [clientId], references: [id], onDelete: Cascade)
@@index([workspaceId])
}
So portal.agency.com can serve all of an agency's clients, and acme.agency.com can be one client's portal. The @unique on domain is what actually stops two accounts from claiming the same host. Everything after this is about the request, not the table.
Assumption 1: "a host I don't recognise is an error"
Before this feature, an unknown Host header was not something the app ever thought about. Now it is the main signal. I flipped the question around: instead of listing customer domains, I list my own and treat everything else as a customer's.
/** VoiceDash's own domains; their subdomains are ours too. */
const OWN_DOMAINS = ["voice-dash.com", "vercel.app"];
export function hostName(host: string | null | undefined): string {
return (host || "").trim().toLowerCase().replace(/:\d+$/, "").replace(/\.$/, "");
}
export function isAppHost(host: string | null | undefined): boolean {
const name = hostName(host);
if (!name || name === "localhost" || name === "127.0.0.1" || name === "[::1]") return true;
if (name === hostName(urlHost(process.env.NEXT_PUBLIC_APP_URL))) return true;
return OWN_DOMAINS.some((d) => name === d || name.endsWith(`.${d}`));
}
Two small things in there earned their place. hostName strips the port and a trailing dot, because Portal.Agency.com. and portal.agency.com:443 are the same site to a browser and different strings to findUnique. And *.localhost deliberately counts as a custom domain, so I could test the whole flow on acme.localhost:3000 without touching DNS.
This file has no database imports on purpose. The proxy (Next.js middleware) imports it, and I wanted the "is this mine?" check to be pure string work, with the database lookup happening later in the pages that need it.
Assumption 2: "req.url is the URL the browser asked for"
This one cost me the most time, and it is the reason for a second commit 80 minutes after the first.
On a custom domain, the proxy sends agency pages to the client sign-in and unauthenticated visitors to /client/login. My first version did what every middleware example does:
return NextResponse.redirect(new URL("/client/login", req.url));
It worked locally. On the deployed app, a client who opened portal.agency.com got bounced to my own domain. The cause: my proxy is wrapped in Auth.js's auth(), and Auth.js rewrites req.url to the configured AUTH_URL / NEXTAUTH_URL origin. So req.url was my app's origin, not the one in the address bar, and every redirect built from it left the agency's domain.
The fix was to build redirects on custom domains from the Host header the browser actually sent:
const host = req.headers.get("host");
if (!isAppHost(host)) {
// Auth.js rewrites req.url to AUTH_URL / NEXTAUTH_URL (the app's own
// domain), so redirects are built from the host the browser asked for.
const proto = req.headers.get("x-forwarded-proto") || req.nextUrl.protocol.replace(":", "");
const stayHere = (path: string) => NextResponse.redirect(new URL(path, `${proto}://${host}`));
// ...
if (pathname.startsWith("/client") && !session) {
return stayHere("/client/login");
}
}
This is safe in my setup because the host only gets here if Vercel routed it to this project, which means it is either one of mine or a domain an agency added through the flow below. The redirect never points anywhere the visitor was not already standing.
The lesson I took away is broader than Auth.js: once a request object has passed through a library, check whether the library normalised it. "The URL" might already be someone's idea of the canonical URL.
Assumption 3: "sign-out goes to my login page"
Same bug, different door. Client sign-out used Auth.js's callbackUrl, which resolved against the app's own origin. A client on portal.agency.com clicked "Log out" and landed on my login page, with my logo, on my domain. For a white-label product that is the worst possible screen to show them.
The client layout now works out where sign-out should land, and the sidebar does the redirect itself:
// client/layout.tsx
let signOutTo = isPreview ? "/login" : "/client/login";
// on VoiceDash's own domain the branded login needs the workspace id
if (!isPreview && !onCustomDomain) signOutTo = defaultClientLoginPath(client.workspaceId);
// ClientSidebar.tsx
signOut({ redirect: false }).then(() => window.location.assign(signOutTo))
A relative path assigned in the browser resolves against whatever host the client is on, which is exactly the behaviour I wanted. On a custom domain the login page needs no ?w= at all, because the domain itself says whose portal it is.
Assumption 4: "the login form is global"
On my own domain, any client of any agency can sign in at /client/login, and the session decides what they see. On a custom domain that is wrong. portal.agency-a.com should not accept a login from agency B's client, even though the credentials are valid. And a single-client domain should only accept that client's members.
So the credentials provider reads the host too:
const host = request?.headers?.get("host");
if (!isAppHost(host)) {
const portal = await prisma.customDomain.findUnique({ where: { domain: hostName(host) } });
if (
!portal ||
portal.workspaceId !== clientMember.client.workspaceId ||
(portal.clientId && portal.clientId !== clientMember.clientId)
) {
return null;
}
}
I wrote about how fiddly that one login form already was in The Hardest Part of a White-Label SaaS Was One Login Form. Custom domains added a third input to it, next to the email and the login type.
Assumption 5: "the browser tab can say my name"
Even with the domain, logo and colour right, the browser tab still said "VoiceDash" with my favicon, and a link pasted into Slack or WhatsApp unfurled with my card. The portal and its sign-in now generate their metadata from the workspace: the agency's title, its favicon or logo, and if it has neither, its initial drawn as an inline SVG on its brand colour. The Open Graph and Twitter blocks get the agency's title with images: [], so a link preview never falls back to mine.
Talking to Vercel without a transaction
Adding a domain means two systems agree: Vercel has to route the host to the project and issue the certificate, and my database has to know which workspace it belongs to. There is no transaction across those, so I ordered the calls and made the first one idempotent.
The route calls Vercel's project domains API first and only writes the row if that succeeds. If the save fails afterwards, the agency just tries again, and the retry hits domain_already_in_use. Instead of treating that as an error, I check whether the domain is already on my own project:
if (code === "domain_already_in_use" && (await vercel(`/v9/projects/:project/domains/${domain}`)).ok) {
return { ok: true };
}
The status check is not read-only either. If Vercel answers 404 for a domain I have a row for (say someone removed it in the dashboard), getDomainStatus adds it back and reports from there. It also re-runs Vercel's verify call each time a domain is still unverified, because the agency may have added their TXT record since the last look. The Domains tab then shows the exact DNS record to create, a CNAME for a subdomain or an A record for a root domain, with the host field relative to the apex, because most DNS providers ask for portal, not portal.agency.com.
Two configuration lessons came out of the same afternoon:
-
Do not name your own env vars
VERCEL_*. Vercel uses that prefix for its system variables. My first version readVERCEL_API_TOKENandVERCEL_TEAM_ID; they are nowDOMAINS_VERCEL_TOKENandDOMAINS_VERCEL_TEAM_ID, and onlyVERCEL_PROJECT_IDcomes from the platform. -
Validate secrets before they reach a header. A token pasted with extra text around it made every request throw
Cannot convert argument to a ByteString, and the Domains tab swallowed the resulting 500. The token is now trimmed and checked against a plain-characters pattern first, a bad one is logged, and the tab shows a message when adding a domain fails.
On a preview deployment the domain is attached to that branch via gitBranch, so testing on dev with a real domain serves the dev build instead of production.
What I would tell myself before starting
The feature itself is a table, a settings tab and a few API calls. The work was finding every line that assumed one host: middleware redirects, the auth library's idea of the URL, sign-out, the credentials check, page metadata. My checklist next time is to grep for req.url, callbackUrl, redirect( and every hard-coded product name before writing any domain code, and to test on something.localhost from the first hour.
If you are building the same thing, I also wrote about the wider multi-tenant setup in What I learned building a white-label, multi-tenant SaaS from scratch, and the product itself lives at voice-dash.com.
How did you handle the auth library side of custom domains? I am curious whether anyone found a cleaner way than reading the Host header in middleware.
來源:DEV Community · dev.to