Domain and email
Slices (b) and (c) of Domain and email: the shared ownership TXT, the Site track (tenant, storefront, bucket CORS) and the Email track (EU subuser, DKIM, required DMARC, test email): how they're built, what to configure and in what order.
Status: built on branch feat/custom-domain-wizard (05/10/2026), not released. Owner-approved spec of 05/10 ("Domain and email", points 1–8). Plan: docs/CUSTOM_DOMAIN_EMAIL_PLAN.md (L1, L9, §9, §11, §12, §17 D2). Slice (a), sender and reply-to, is on its own branch: Email sender and reply-to. User guide: Domain and email. Paths are relative to backend/ and web-next/.
1. Shape
One settings section, two independent tracks on the same school domain, each with its own records, verification and status, activable at different times; a summary on top (domainSummary: "Site: … · Email: …").
| Part | Records | Status |
|---|---|---|
| Ownership (shared) | TXT _aladia.<domain> = aladia-verify=<token> | verified once, valid for both tracks; without it neither track calls Vercel or SendGrid |
| Site | CNAME app (or the chosen subdomain) → the project CNAME from Vercel, or A on @ for the bare domain with a www CNAME; _vercel TXT only when Vercel asks. Several domains per workspace: §1 bis | pending → verifying → active; 7 days broken → misconfigured; 30 days → removed from Vercel |
3 SendGrid CNAMEs on mail.<domain> (em…, s1._domainkey.mail, s2._domainkey.mail); DMARC required | account_pending, pending, verifying, verified, failed |
- Token:
sha256("aladia-custom-domain:<orgId>:<root>"), 32 hex. Deterministic, so the previews show the real value without writing. No secret needed: whoever reads it still can't write it into someone else's DNS, and each workspace gets a different value. - Sender:
<Academy name> <notification@mail.<domain>>. Themailsubdomain is the default and stays fixed unless changed from the advanced option; never the root; never a no-reply local part. - DMARC is required for the Email track:
_dmarc.mail.<domain>, or the root_dmarc.<domain>whosesp=(orp=) covers the subdomain, with a valid policy (at leastp=none). When missing, the exact TXT to add is shown (v=DMARC1; p=none; rua=mailto:<reply-to>;). - Reserved:
aladia.io,vercel.app,vercel.comalways;aladia.aiandistitutoformativoaladia.itonly for the workspaces inCUSTOM_DOMAIN_RESERVED_OWNERS; mailbox providers (gmail, outlook, libero…).
1 bis. Site domains: bare domain and "Change domain"
Owner decision of 08/10/2026. Branch feat/custom-domain-apex-change.
Model. The old customDomain (one domain) is replaced by organizations.siteDomains[] (OrganizationCustomDomainDocument with a role): same fields as before (records, status, Vercel, SSL, 7/30 days, backoff) plus:
| Field | What |
|---|---|
role | active = the site domain (at most one; until its status is active the site stays on <slug>.aladia.io); next = the new domain of a change, being verified (at most one); redirect = redirects to the site domain |
apex | bare domain (school.com): A record on @ (IP from recommendedIPv4 of /v6/domains/:d/config, fallback 76.76.21.21) instead of the CNAME |
companionOf | www.<domain>, ALWAYS connected with the bare domain (redirect role, www CNAME); comes and goes with its domain |
vercelRedirect | the redirect set on Vercel (read back on every domain GET): the sync is idempotent |
redirectingSince | since when it redirects (after the swap) |
ownership | the ownership (_aladia TXT) of ITS root when it isn't domainOwnership's: change to another domain with the email left on the first one |
Pure rules in apps/profile/…/site-domains.rules.ts: promoteNext (the swap), redirectTarget/desiredRedirect (every redirect ALWAYS points to the active domain, only once it's on Vercel: Vercel only accepts a project domain as target), arrangeOwnerships (domainOwnership = email root if any, else the site domain's, else the new one's; other roots on the domains using them; redirects need none; a verified ownership moves, never gets recreated: the token is deterministic), removableAlone.
Flow.
- First connection (
PUT …/custom-domain { domain, subdomain?, apex? }with the site not live): the chosen domain isactive; withapexalsowww.<domain>asredirect(companionOf). The previous one, never live, leaves Vercel. - Change domain (same route, with the
activedomain alreadyACTIVEand a different host): the new one comes in asnext(plus its www when bare) NEXT TO the old one, which stays the site. On another root ownership is verified again (the new root's TXT inownership); the email stays on its own. A previous change to another host is cancelled; a redirecting host can becomenextagain. - Check (
check, cron and "Check again"): ownership of every root → due domains in the orderactive,next,redirect(a redirect goes on Vercel only after its target:POST /v10/projects/:p/domains { name, redirect, redirectStatusCode: 308 }) → swap when thenextisACTIVE(DNS + Vercel verified + TLS probe): thenextbecomesactive, the old oneredirect→ sync of the Vercel redirects (PATCH /v9/projects/:p/domains/:d { redirect, redirectStatusCode: 308 },nullfor those that must not redirect). No DELETE and re-create. Idempotent: a second run makes no Vercel writes. - When the new one goes live: "… is live" email to the Owner (as today) and
WorkspaceOriginsNotifier.domainActive: bucket CORS and Stripe payment method domain (Apple Pay/Google Pay) registered on the academy account.redirects send no email; after 30 days of broken DNS they leave Vercel and the list. - Removals:
DELETE …/custom-domain/hosts/:hostremoves aredirect(any time) or thenextwith its www (cancels the change); theactivedomain → 409.DELETE …/custom-domainremoves everything (the site goes back to<slug>.aladia.io).
What follows the site domain (the live active domain):
| Where | What |
|---|---|
Tenant resolution (workspace-address.service.ts resolveCustomDomain) | the active answers with its host; a redirect answers redirectTo = site domain with redirectStatus: 308, the next with 307 (temporary, never cached by browsers: it becomes the site soon). proxy.ts (tenantRedirect in lib/tenant.ts) redirects keeping path and query: it covers the time before the Vercel redirect is set |
Trusted origins (activeDomains) | only the live active; the /_api proxy answers 404 on a redirecting domain |
Canonical, OG, previews (lib/tenant-metadata) | tenant.host = site domain |
Email links and sender (mail-identity.ts, MailTenantService) | siteHost = active domain; from a redirecting domain the host is the redirectTo |
| Stripe Apple Pay/Google Pay, bucket CORS | domainActive of the new one at the swap |
Product SSO (workspaceHosts) | accepted aud: <slug>.aladia.io, the site domain and, while they exist, the redirecting domains (not the www ones) |
Email domain (mail.<root>) | does NOT change; if the site root changes the Email track flags it (emailOnOtherRoot) until it's set up again |
Session. Cookies (__Host-accessToken) are per domain: after the swap people signed in on the old one sign in once more on the new one. A one-time cross-domain session handoff doesn't exist yet (the auth.aladia.io one-time code is in plan §5.2, not built): documented limit, shown in the wizard.
UI (custom-domain-section.tsx): rows with a "⋯" menu (DropdownMenu): site domain (Change domain, Open, Remove the custom domain), new domain ("New domain" badge, Cancel the change, with its steps and records), redirecting domains ("Redirects to …" badge, Open, Delete); a ConfirmDialog for every removal. Wizard with a "Main domain" / "Subdomain" RadioGroup, a warning about the website being replaced (existing from the preview) and, on a change, the consequences (redirect, signing in again, product SSO if on, email sender).
Migration scripts/migrations/2026-10-site-domains.js (PHASE=plan, then PHASE=apply): customDomain → siteDomains: [{ ...customDomain, role: 'active' }], partial multikey unique index siteDomains.domain_unique, sparse siteDomains.nextCheckAt and siteDomains.status, then the customDomain.* indexes are dropped. Stops if a host is in two workspaces. Behaviour unchanged.
Tests: tests/unit/custom-domain-change.spec.ts (rules; bare domain with www 308; change from app. to the bare domain with swap, PATCH and idempotence; change to another root with new TXT and email left behind; cancel; deleting a redirect; refusal on the site domain; email links on the new one), workspace-address.spec.ts (308/307 for domains that aren't the site), lib/tenant.test.mjs (tenantRedirect), lib/custom-domain.test.mjs (siteRows, canChange, removableAlone). Vercel and DNS are always fake.
2. Code
| File | What |
|---|---|
apps/profile/src/app/organization-branding/custom-domain.rules.ts | pure rules: validation, token, records, DNS evaluation with seenValue, DMARC, status, backoff, 7/30 days, limits, zone file |
apps/profile/…/custom-domain.service.ts | ownership, Site (preview, set, remove), Email (preview, set, remove, test), check of the three parts, instructions, sweep |
apps/profile/…/site-domains.rules.ts | pure rules of the site domains: roles, swap, redirect target, ownership per root (§1 bis) |
apps/profile/…/custom-domain.sweep.ts | @Cron every 5 min with Murlock (custom-domains:sweep), 25 workspaces per run |
apps/profile/…/dns-checker.ts | dns.promises.Resolver on 1.1.1.1 and 8.8.8.8, TLS probe with SNI |
apps/profile/…/vercel-domains.client.ts | Vercel REST: GET /v6/domains/:d/config?projectIdOrName before adding, add, get, verify, remove |
apps/profile/…/sendgrid-domains.client.ts | @sendgrid/client, EU host, on-behalf-of: <subuser>: subusers probe and creation, domain authentication, validation, test send |
libs/common/src/common/custom-domain/dns-providers.ts | provider from NS + deep link (Squarespace, Aruba, Register.it, GoDaddy, Cloudflare, Google Cloud DNS, OVH, Namecheap, Vercel) |
libs/common/src/common/custom-domain/trusted-custom-domains.ts | active domains as trusted origins (CORS, Origin check, websocket), reloaded every minute by the gateway |
apps/gateway/…/organization-branding/custom-domain.controller.ts | organizations/:id/custom-domain and organizations/:id/email-domain, flag custom-domain, assertFeature (custom_domain, school_email_domain) |
apps/gateway/…/course/marketplace/marketplace-storefront.controller.ts | public storefront of the site's workspace |
apps/storage/src/app/buckets/buckets.service.ts (ensureOwnerOrigins) | site origin in the CORS of every bucket of the workspace |
web-next/components/settings/domain/custom-domain-section.tsx | the section (track prop: Site in Settings > Domain, Email in Settings > Email), the two tracks and the wizard |
web-next/lib/tenant.ts, lib/tenant-resolve.ts, proxy.ts | tenant on verified custom domains (resolveTenant, per-instance cache 60/30 s) |
web-next/app/brand-icon/[file]/route.tsx | per-host favicon (favicon.png, 64 px) and apple-touch-icon.png (180 px): the workspace logo cropped square (PNG/JPEG redrawn with next/og, other formats passed through), otherwise 307 to Aladia's /icon.svg; one-hour Cache-Control, Vercel's cache keys on host. The path has a dot, so proxy.ts skips it |
web-next/components/tenant/ (tenant-mark, auth-brand, tenant-title), components/shell/guest-shell.tsx | workspace brand in the guest header, sign-in and invitations; tab title (tenantTitle: "· Aladia" → name). The root layout stays static: no headers() |
3. Routes
| Route | What |
|---|---|
POST …/custom-domain/preview { domain, subdomain, apex? } | ownership TXT, A/CNAME (and www CNAME with the bare domain), provider, change (it's a change), existing (what the host answers today); no writes |
PUT …/custom-domain { domain, subdomain, apex? } | save the Site (and the ownership if new), first check; with the site already live on another host it's "Change domain" (§1 bis) |
POST …/custom-domain/verify | "Check again": ownership + both tracks, 10/h, asks Vercel to verify |
POST …/custom-domain/instructions { to, track?, domain? } | "Send to your IT", 5/day, from the saved track or the preview |
DELETE …/custom-domain | remove every site domain (always allowed) |
DELETE …/custom-domain/hosts/:host | remove a redirecting domain or cancel the change (the new one with its www); the site domain → 409 |
POST …/email-domain/preview { domain, sender, subdomain? } | sender, ownership, DMARC, accountReady |
PUT …/email-domain | save the Email track, first check |
POST …/email-domain/test { to } | "Send a test email" from the subuser, 5/h, only when verified |
POST …/email-domain/verify, …/instructions, DELETE …/email-domain | as for the Site |
GET /v2/public/tenants/resolve?host= | also resolves ACTIVE custom domains (same lock and brand as <slug>.aladia.io) |
GET /v2/public/storefront, /public/storefront/categories | the site's published showcase and visible categories, for guests too |
POST /courses/search on a site (x-aladia-tenant) stays in that workspace's catalog, for guests and non-members.
4. Email track and SendGrid
- One subuser per academy (
aladia-<orgId>), created whenGET /v3/subusersanswers, on the dedicated IP (SENDGRID_SUBUSER_IPSif set, else the first ofGET /v3/ips). The IP region is read fromGET /v3/send_ips/ips/:ip?include_region=true: the subuser is created only on an EU IP; ausIP or a region SendGrid doesn't report staysaccount_pendingwith the reason shown (never guessed). A 401/403 means account review pending or a key withoutsubusers.*:account_pendingtoo. - IP warmup: before the first subuser, if
is_auto_warmupis false, it's turned on withPATCH /v3/send_ips/ips/:ip {is_auto_warmup: true}, but only when the parent doesn't send from that IP (is_parent_assignedfalse): warming up a shared IP would throttle every Aladia email. With a shared IP the log says so and the step is manual:SENDGRID_AUTO_WARMUP=force, or Settings > IP Addresses > the IP > Automated warmup in SendGrid. - Hosts: account calls (subusers, IPs) on
api.sendgrid.com; subuser calls (domain authentication, test send) on the host of the subuser's region (api.eu.sendgrid.comfor EU, stored inemailSending.subuserRegion). To confirm on the first live subuser: that the parent key withon-behalf-ofis accepted on the EU host. - The domain
mail.<domain>is authenticated on the subuser (on-behalf-of), not on the parent: who signs and who sends is the same user, otherwise DKIM is not aligned and DMARC fails. Default SendGrid selectors and return path: they live undermail.and can't collide with a SendGrid the school already uses on the root. verifiedrequires SendGrid validation and DMARC. A domain that stops validating goes back toverifyingat once.- With a verified track, the test email and every inline academy email (reset, code, welcome, invitations…) leave from
notification@mail.<domain>, throughMailSenderResolverand the subuser; SendGrid templates stay on aladia.io with the academy name (Email sender and reply-to §7).
5. Session, sign-in and websockets
Branch release/custom-domain-session (slimmed-down L4, plan §4 and §5). The session is the httpOnly cookie __Host-accessToken (Secure, Path=/, no Domain, SameSite=None), set by whoever answers the sign-in.
| Where | HTTP calls | Session cookie | Websockets (socket.io, Hocuspocus) |
|---|---|---|---|
app.aladia.io, beta.aladia.io | direct to api.aladia.io/v2 | api.aladia.io's, same site | direct, with the cookie |
<slug>.aladia.io | direct to api.aladia.io/v2 | the same as app.aladia.io, same site | direct, with the cookie |
app.school.com (verified domain) | same-origin proxy app.school.com/_api/v2/* | first-party on app.school.com, separate from the aladia.io one | direct to api.aladia.io with a single-use ticket |
/_api/v2 proxy. web-next/proxy.ts (proxyApi) runs NextResponse.rewrite to NEXT_PUBLIC_API_BASE_URL only when the host is a custom domain (isCustomDomainHost in lib/tenant.ts) and resolves to a live workspace; anywhere else /_api/* answers 404. No Vercel caching (x-vercel-enable-rewrite-caching: 0). The matcher has its own entry (/_api/:path*) because API paths can contain dots. In the browser apiBaseUrl() (lib/config.ts) is /_api/v2 on those domains and the direct URL elsewhere: apiFetch and the assistant chat (assistantChatUrl()) use it. Server side stays direct.
- Vercel forwards method, body, cookies and
Set-Cookie; the Host towards the VPS isapi.aladia.io, the Origin stayshttps://app.school.com. - The gateway accepts that Origin because
activedomains already are trusted origins (trusted-custom-domains.ts, reloaded every minute): CORS withcredentials(never*),BearerOnlyMiddleware(also the CSRF check), websockets. Same-origin GETs arrive without an Origin and with Hostapi.aladia.io, which is allowed. - Signed proxy→gateway header, optional (since 06/10): with
ALADIA_EDGE_SECRETset,proxyApiaddsx-aladia-edge-secretandx-aladia-tenant-host(ALADIA_EDGE_SECRET). Without the secret the gateway uses the Origin of the active domain. The gateway uses the host only for the sender and links of account emails (Email sender and reply-to §7); request context still comes fromx-aladia-tenant, which grants nothing by itself (tenant-context.ts: member → academy, otherwise personal context). - Client IP: the gateway already reads the first
x-forwarded-forvalue, which Vercel sets to the visitor's IP.
Websocket ticket. Vercel doesn't forward websockets, and on api.aladia.io the browser of app.school.com has no cookie. POST /v2/auth/realtime-ticket (through the proxy, with the cookie) returns { ticket, expiresIn: 60 }:
rt_+ 32 random bytes; Redis only holdsrealtime-ticket:<sha256>→ session token,EX 60;- redeemed with
GETDELinSocketGateway.authenticateandHocuspocusSocketGateway.authenticate(RealtimeTicketService.resolve): it works once, then the usual checks run (signature, expiry, token inuser.tokens), so a sign-out invalidates it; - the JWT never reaches JavaScript; with an API key (no web session) the route answers 401;
- client:
lib/realtime/socket.tspassesauthas a function (socket.io calls it on every reconnection); the editor getsticketed: trueinINITand asks the parent forREALTIME_TICKETon every connection (HocuspocusProvider'stokenas a function).
Nothing changes on the hub and on <slug>.aladia.io: no ticket, cookie as before.
Sign-out and exits (lib/session-exit.ts):
| Event | Hub | Workspace site (<slug>.aladia.io or domain) |
|---|---|---|
Sign out (site-header.tsx) | https://aladia.io | same host: / (storefront) or /login with Members-only access |
Session expired (401 on /profiles/me, use-me.ts) | /login?redirect=<page> | same, on the same host, sign-in with the academy's brand |
Switch account on an invitation (email-invite-client.tsx) | /login?redirect=<invitation> | same, on the same host |
authApi.logout() sends { devices: 'current' }: it revokes only the current token. It used to send {}, which the gateway validation rejected (400): the local flag went away but the token stayed valid and the cookie wasn't cleared. On <slug>.aladia.io the cookie is the hub's one, so signing out there also signs you out of app.aladia.io in that browser. On a custom domain the sessions are separate: two devices of the same account (plan §5.2 point 5). Assistant links to app.aladia.io or beta.aladia.io stay on the workspace site (keepOnSite).
Google. GIS only accepts origins registered by hand in the OAuth client, so on custom domains the "Continue with Google" button (and One Tap) is hidden (useGoogleSignIn in google-auth.tsx); email and password, sign-up, code, reset and invitation links remain. A Google-only account reads it in the error message and sets a password from "Forgot password?". On <slug>.aladia.io the button stays, but GIS takes no wildcards: it works only for addresses registered one by one in the OAuth client (to check on accademia-leonardo.aladia.io). Google sign-in on domains comes with the auth.aladia.io relay and the single-use code (plan §5.2): DNS record auth CNAME to Vercel, auth.aladia.io on the app-aladia-io project, origin https://auth.aladia.io in the OAuth client's Authorized JavaScript origins, a /relay page, an auth/exchange route.
Tests: web-next/lib/tenant.test.mjs (host → proxy yes/no, base URL, hub links), lib/session-exit.test.mjs (destinations); backend tests/unit/custom-domain-session.spec.ts (single-use ticket with hash and 60 s, CORS and BearerOnlyMiddleware from the verified domain through the proxy, socket.io handshake with the ticket, logout body), websocket-origin.spec.ts.
To check with the pilot domain (Safari iOS and macOS, Firefox, Chrome): password sign-in, Set-Cookie of __Host-accessToken on app.school.com (DevTools > Application > Cookies), /profiles/me through /_api/v2, real-time chat and notifications, document editor, uploads, streaming assistant chat, sign-out (stays on the domain, token revoked), expired session, and that app.aladia.io in the same browser stays as it was.
6. Limits and rate
| Action | Limit |
|---|---|
| Save (either track) | 5/h per workspace |
| Check again | 10/h per workspace |
| Send to your IT | 5/day per workspace |
| Test email | 5/h per workspace |
Background checks never call Vercel verify (50/h per team): only GET. Additions happen only after the ownership TXT (100/h per team). Backoff: every 10 min for 2 h, hourly up to 72 h, then daily; live tracks daily.
7. Configuration, in order
- Vercel token on the VPS:
VERCEL_API_TOKEN, a token of thealadia-projectsteam with scope limited to that team, used on projectapp-aladia-io(prj_tjo3HlReufLi7kkgg3ymFcAnsB5l): project domains read/write (POST /v10/projects/:p/domains,GET|PATCH|DELETE /v9/projects/:p/domains/:d,POST …/verify; PATCH for the "Change domain" redirects) and domain config read (GET /v6/domains/:d/config). Without it the Site stops at "ownership verified, waiting for Aladia". - Deploy backend, then
scripts/migrations/2026-10-custom-domain-wizard.js(PHASE=plan, thenPHASE=apply): sparse indexes oncustomDomain.nextCheckAt,customDomain.status,emailSending.nextCheckAt; removal of custom domains in the old format. Then, right after the deploy that contains §1 bis,scripts/migrations/2026-10-site-domains.js(PHASE=plan, thenPHASE=apply): between the deploy and the apply the site on the custom domain doesn't resolve. - Deploy web-next.
- SendGrid: nothing new is required. The key is
SENDGRID_ADMIN_API_KEY, elseSENDGRID_API_KEY(today's Full Access key, withsubusers.*,ips.read,whitelabel.*,mail.send). Optional:SENDGRID_SUBUSER_IPSto pick the IP,SENDGRID_AUTO_WARMUP=forceto warm up an IP shared with the parent. First check: the region of159.26.179.2(GET /v3/send_ips/ips/159.26.179.2?include_region=true) must beeu. - Optional:
CUSTOM_DOMAIN_RESERVED_OWNERS="istitutoformativoaladia.it=<orgId>"for our own domains. The pilot test domain is not in the code: the e2e readsCUSTOM_DOMAIN_PILOT.
8. Tests
- Backend unit:
tests/unit/custom-domain-change.spec.ts(§1 bis),tests/unit/custom-domain.spec.ts(rules, DMARC, providers, resolver, SendGrid with mocks, Site flow with fake Vercel/DNS/TLS, 7/30 days, Email flow with account pending, subuser creation, authentication on the subuser, required DMARC, test email, shared ownership, limits, instructions, sweep, trusted origins, emails),bucket-cors.spec.ts,marketplace-storefront.spec.ts,workspace-address.spec.ts,workspace-entitlements.spec.ts. - web-next:
node --test lib/custom-domain.test.mjs lib/tenant.test.mjs lib/session-exit.test.mjs. - E2E, read-only on production:
node web-next/e2e/help/flows/run.mjs settings/custom-domain(owner of Accademia Leonardo, test domain fromCUSTOM_DOMAIN_PILOT, writes blocked and counted).--shotswrites desktop and 375 px, light and dark, intodocs/public/help/settings/custom-domain/.
9. Phase 2 (not now)
Replies into the Aladia chat: a reply subdomain (reply.mail.<domain>) with an MX to SendGrid Inbound Parse; the Reply-To of a conversation email becomes r+<token>@reply.mail.<domain>, the parse webhook turns the reply into a chat message for the right thread. Needs the Event/Parse webhook endpoint (signed), a token per thread and spam filtering.
10. Market references
How comparable platforms handle custom domains and sending domains (help centers read on 05/10/2026):
- Kajabi, Connect a custom domain: CNAME for a subdomain, nameservers for the root; the target shown in the admin is the source of truth because it differs per account (as our CNAME read from Vercel). Connect a custom email domain is a separate flow.
- Thinkific, Custom Domains: a subdomain and a CNAME are required, with per-provider guides (GoDaddy, Cloudflare…).
- LearnWorlds, Custom domains and CNAME in popular providers: subdomain recommended, provider-specific instructions.
- Docebo, Domain management, DNS and SSL requirements and DKIM: email sender domains configured separately from the platform domain, and not reusing the platform's custom domain for the sender (CNAME and SPF can't coexist on the same name), which is why our sender is on
mail.. - Postmark, Setting up DKIM and How DMARC and a custom Return-Path work together: DKIM plus a custom Return-Path for DMARC alignment.
- SendGrid, domain authentication and subusers: automated-security CNAMEs, subusers to isolate reputation.