Docs/Ecosystem/Domains: Multi-Tenant Custom Domains

Domains: Multi-Tenant Custom Domains

Manage tenant custom domains in Go with bounded LRU host resolution, _fletch-verify DNS checks, lifecycle transitions, and Caddy on-demand TLS.

github.com/fletchhq/domains

domainspkg.go.dev

Updated 2026-12-06 fletch docs show domains/domains 10 min read

On this page

Domains handles customer-owned hostnames attached to tenants at runtime in Go and Fletch applications. It normalizes tenant input, resolves request hosts through bounded caches, checks DNS ownership and routing, advances each domain through a five-state lifecycle, and answers Caddy's on-demand TLS ask endpoint.

Introduction

Static host groups work well when you know every hostname ahead of time, such as app.example.com and admin.example.com. Multi-tenant apps also need customers to bring their own domains like shop.acme.com or acme.com without restarting the server or pushing lookup logic into ad-hoc middleware.

github.com/fletchhq/domains solves the runtime host layer without locking you into a database or web framework. Your application owns persistence behind a two-method interface (Store and Writer), while domains takes care of host normalization, cache isolation against random-host scans, DNS verification, and fail-closed certificate approval.

If you only need static first-party host routing (router.Host), session cookie domains, or cross-host sign-in handoff, see the Hosting guide.

Installation

Install the module with go get:

go get github.com/fletchhq/domains@v0.1.0

Import the root package alongside memstore for local development or tests, or wire your own database store for production:

import (
	"github.com/fletchhq/domains"
	"github.com/fletchhq/domains/memstore"
)

Unlike the other six Fletch ecosystem root packages, github.com/fletchhq/domains is not pure stdlib-only. It depends directly on golang.org/x/net (for idna and publicsuffix) and pulls in golang.org/x/text indirectly. It has zero dependency on any Fletch framework module and builds with CGO_ENABLED=0.

When github.com/fletchhq/domains is in your go.mod, fletch ax sync and fletch docs index its embedded guide and skill automatically.

Core concepts

Normalization and zone protection

Pass every hostname a tenant types through domains.Normalize(input). It trims whitespace, strips a pasted scheme, path, query, or fragment, converts Unicode labels to ASCII A-labels with the x/net/idna Lookup profile, lower-cases the host, and drops a trailing dot. It returns the normalized host, whether the host is an apex domain (its own eTLD+1), and an error wrapping domains.ErrInvalidHost when the input is empty, contains user info, includes a port or wildcard, parses as an IP literal, has a single label, or names a bare public suffix such as com or co.uk.

Before accepting a tenant claim, check domains.IsUnderZone(host, zone) so customers cannot claim names under your platform's own domain:

host, apex, err := domains.Normalize(input)
if err != nil {
	return err
}
if domains.IsUnderZone(host, "sites.platform.com") {
	return errors.New("cannot claim a platform hostname")
}

IsUnderZone compares case-insensitively and ignores a trailing dot on either argument.

Domain records and storage

A domains.Domain holds the normalized Host, TenantID, State, Apex flag, ownership Token, lifecycle timestamps (CreatedAt, VerifiedAt, CheckedAt, DegradedAt), Failures counter, and LastProblem code. Two helper methods control serving and TLS behavior:

  • d.Serving() returns true for StateActive and StateDegraded.
  • d.Issuable() returns true for StateVerified, StateActive, and StateDegraded.

Persistence belongs to your application. Implement domains.Store (Lookup(ctx, host) (Domain, error)) for request serving, and domains.Writer (Save(ctx, d) error) for background verification jobs. Unknown hosts must return domains.ErrNotFound.

For tests, local development, or single-process apps that load domains at startup, github.com/fletchhq/domains/memstore provides a concurrency-safe *memstore.Store with New, Lookup, Save, Delete, and List.

Bounded resolver cache

Wrap your Store with domains.NewResolver(store, opts...) to cache host lookups and collapse concurrent misses for the same host into one Store.Lookup call. The resolver keeps found domains and unknown hosts in two separate bounded LRUs, so a scan of random hostnames can fill the negative cache without evicting active customer domains.

Configure TTLs, cache bounds, or a test clock with ResolverOption values:

resolver := domains.NewResolver(
	store,
	domains.WithPositiveTTL(60*time.Second),
	domains.WithNegativeTTL(30*time.Second),
	domains.WithMaxEntries(100_000, 10_000),
)

Call resolver.Resolve(ctx, host) when you need a cached lookup outside HTTP middleware. It normalizes case and trailing dots, rejects invalid names or IP literals with ErrInvalidHost without touching the store, and never caches transient store errors. When a domain changes state or is deleted, call resolver.Invalidate(host) to evict it from both caches immediately and prevent in-flight lookups from repopulating stale data.

Domain lifecycle

Every custom domain moves through a five-state machine managed by domains.Lifecycle:

  1. pending_dns (StatePendingDNS) to verified (StateVerified): ownership TXT and DNS routing checks both pass. Domains still unverified after PendingExpiry (default 14 days) are marked Expired so your job can delete them.
  2. verified (StateVerified) to active (StateActive): an HTTPS probe to https://<host>/ completes a trusted TLS handshake (Verifier.ProbeHTTPS).
  3. active (StateActive) to degraded (StateDegraded): FailureThreshold consecutive failed routing rechecks (default 3) move the domain to degraded. Traffic continues to serve, and a passing recheck restores active.
  4. degraded (StateDegraded) to suspended (StateSuspended): if routing does not recover within DegradedGrace (default 7 days), the domain suspends and stops serving traffic and TLS issuance.
  5. suspended (StateSuspended) to verified (StateVerified): the customer re-verifies ownership TXT and routing from scratch.

Ownership TXT is checked only when claiming or re-claiming (pending_dns and suspended). Periodic rechecks of active and degraded domains check routing only.

Common tasks

Serving custom domains on a Fletch router

Mount resolver.Middleware on a catch-all router.Host("*") group so requests whose Host resolves to an active or degraded domain receive the domains.Domain on their context. Read it downstream with domains.FromContext(ctx):

custom := r.Host("*", resolver.Middleware(
	domains.WithNotFound(domainNotFoundHandler),
))

custom.Get("/", func(w http.ResponseWriter, req *http.Request) {
	d, ok := domains.FromContext(req.Context())
	if !ok {
		http.NotFound(w, req)
		return
	}
	renderStorefront(w, req, d.TenantID, d.Host)
})

Unknown, invalid, pending_dns, verified, and suspended hosts go to your WithNotFound handler (plain 404 by default). If the underlying Store returns a non-ErrNotFound error, the middleware responds with 503 Service Unavailable.

Creating a domain claim

When a tenant submits a custom domain, normalize it, reject platform zones, generate a 128-bit ownership token with domains.GenerateToken(), and save the row in StatePendingDNS:

host, apex, err := domains.Normalize(req.FormValue("host"))
if err != nil {
	return err
}
if domains.IsUnderZone(host, "sites.platform.com") {
	return errors.New("reserved platform zone")
}

token, err := domains.GenerateToken()
if err != nil {
	return err
}

d := domains.Domain{
	Host:      host,
	TenantID:  tenantID,
	State:     domains.StatePendingDNS,
	Apex:      apex,
	Token:     token,
	CreatedAt: time.Now().UTC(),
}
return store.Save(ctx, d)

Show the customer the required DNS records based on d.Apex:

Domain type Required DNS records Notes
Subdomain (shop.acme.com) TXT _fletch-verify.shop.acme.com = <token> and CNAME shop.acme.com -> sites.platform.com Fallback: all A/AAAA answers must match your ingress IPs.
Apex (acme.com) TXT _fletch-verify.acme.com = <token> and A acme.com -> <ingress-ipv4> CNAME is invalid at the apex (RFC 1034). Add AAAA only if IPv6 ingress works end-to-end.

Two DNS mistakes come up regularly during tenant onboarding:

  • Stray AAAA records: ACME validators prefer IPv6. An old AAAA record pointing elsewhere fails verification with ProblemAAAAElsewhere ("aaaa_elsewhere"), even if the HTTP probe succeeds.
  • Proxied CDNs: Proxied mode (such as Cloudflare orange cloud) hides your ingress IP and breaks verification. Customers must use DNS-only records.

Verifying DNS and advancing state

Configure a domains.Verifier with your CNAME target and ingress IP addresses. Calling verifier.Verify(ctx, d) returns a domains.Result with Owned, Routed, and structured Problems (Code and Detail) that you can render on a tenant's setup screen.

To step a domain through its lifecycle in one call, pass the verifier (or any domains.Checker) to Lifecycle.Advance:

verifier := &domains.Verifier{
	Target:    "sites.platform.com",
	IPv4:      []netip.Addr{netip.MustParseAddr("203.0.113.10")},
	HTTPProbe: &http.Client{Timeout: 10 * time.Second},
}

lifecycle := domains.Lifecycle{} // 3 failures, 7d grace, 14d pending expiry
outcome, err := lifecycle.Advance(ctx, verifier, d, time.Now().UTC())
if err != nil {
	return err
}
if outcome.Expired {
	return store.Delete(ctx, outcome.Domain.Host)
}
if err := store.Save(ctx, outcome.Domain); err != nil {
	return err
}
if outcome.Changed {
	resolver.Invalidate(outcome.Domain.Host)
}

If you run verification and HTTPS probes separately, apply individual transitions with lifecycle.Claimed(d, res, now), lifecycle.HTTPSReady(d, probeErr, now), and lifecycle.Rechecked(d, res, now). Calling a step on a domain in the wrong state returns an error wrapping domains.ErrInvalidState.

When Verifier.HTTPProbe is set and DNS alone does not prove routing (for example behind a flattened CNAME), Verify fetches http://<host>/.well-known/fletch-domain/<token>. Mount domains.WellKnownHandler(resolver) on a host-agnostic route outside resolver.Middleware so pending domains can answer that probe:

r.Handle(domains.WellKnownPrefix, domains.WellKnownHandler(resolver))

Wiring Caddy on-demand TLS

Mount domains.AskHandler(resolver, opts...) on a host-agnostic route such as /_fletch/tls/ask. Never place it inside a host group, because Caddy queries it over loopback or an internal proxy address with ?domain=<name>.

r.Handle("/_fletch/tls/ask", domains.AskHandler(
	resolver,
	domains.WithAskToken(cfg.AskToken),
	domains.WithAskPeers("127.0.0.1/32", "::1/128"),
	domains.WithAllowHost(func(host string) bool {
		return host == "sites.platform.com"
	}),
))

Every configured guard must pass before the handler evaluates the requested domain:

  • WithAskToken(token) checks the X-Ship-Ask-Token (domains.AskTokenHeader) header in constant time. Passing an empty token panics.
  • WithAskPeers(cidrs...) checks req.RemoteAddr against trusted proxy CIDRs (IPv4-mapped IPv6 addresses match IPv4 CIDRs). Passing an invalid CIDR panics.
  • WithAllowHost(fn) approves static platform hosts alongside store-backed domains. It approves hostnames, not callers, so it does not act as a guard.

AskHandler answers 200 OK (empty body) for approved platform hosts and for verified, active, and degraded domains. It returns 404 for IP literals, invalid names, unknown hosts, pending_dns, and suspended domains, 405 for methods other than GET or HEAD, and 503 when the Store fails.

Integrating with Nock, Quiver, PubSub, and Sight

Because domains stays independent of Fletch's database, queue, and admin packages, you wire them together inside your application:

  • Nock: Implement domains.Store and domains.Writer over your tenant domains table, using domains.Domain columns. Validate your store against the domainstest contract suite.
  • Quiver: Schedule a recurring job (for example every 6 hours for active/degraded rechecks, and a faster poll for pending_dns/verified claims) that calls Lifecycle.Advance, saves outcome.Domain (or deletes it on outcome.Expired), and broadcasts changes.
  • PubSub (multi-node): When outcome.Changed is true or an admin edits a domain, publish the hostname on a broadcast topic (such as domains.changed) so every node calls resolver.Invalidate(host) immediately instead of waiting for WithPositiveTTL or WithNegativeTTL to expire.
  • Sight: If operators need to view domain states, inspect LastProblem, or trigger re-verification, expose your Nock-backed domain table as a Sight resource with a custom action calling Lifecycle.Advance.

Advanced usage

Local development without DNS

Wrap your store with domains.DevAlwaysVerified(store) in development so any host Normalize accepts resolves as StateActive. Existing rows keep their TenantID and other fields, while unknown valid hosts like brand-a.shop.localhost resolve as active without DNS records:

if isDev {
	store = domains.DevAlwaysVerified(store)
}

Never wrap a production store with DevAlwaysVerified.

Testing custom stores with domainstest

github.com/fletchhq/domains/domainstest verifies that your database-backed Store or StoreWriter matches the exact contract domains expects: exact host matching, ErrNotFound on misses, replacement semantics on Save, zero-time round trips, and concurrent read/write safety.

func TestNockDomainStore(t *testing.T) {
	domainstest.RunWriterSuite(t, func(t *testing.T) domainstest.StoreWriter {
		return newTestDomainStore(t)
	})
}

Use domainstest.RunStoreSuite if your implementation is read-only.

Cross-host architecture in Fletch

When serving both platform hosts and customer domains from one Fletch application, keep these boundaries in mind (covered in detail in the Hosting guide and demonstrated in examples/multisite):

  • Keep session cookies host-only on custom domains; only set a parent cookie domain for first-party platform hosts.
  • Keep OAuth callbacks on one platform host and transfer the user to their custom domain via auth/handoff, checking domains.FromContext(ctx) against the handoff token's tenant.
  • Bind Live sessions to a host with live.WithHostBinding().
  • Store a canonical primary host per tenant instead of constructing mail or job links from an incoming Host header.

Reference

Lifecycle states and sentinel errors

Symbol Value / meaning
StatePendingDNS "pending_dns" — claimed, awaiting TXT ownership and routing
StateVerified "verified" — DNS verified, eligible for TLS issuance (Issuable())
StateActive "active" — HTTPS live, serving traffic (Serving(), Issuable())
StateDegraded "degraded" — failing routing rechecks, still serving during grace window
StateSuspended "suspended" — grace period elapsed, traffic and TLS stopped
ErrNotFound Returned by Store.Lookup and Resolver.Resolve for unknown hosts
ErrInvalidHost Returned by Normalize, Resolver.Resolve, ProbeHTTPS, and memstore.Save
ErrInvalidState Returned by Lifecycle methods called on an incompatible state

Resolver, middleware, and ask options

Option Target Default / behavior
WithPositiveTTL(d) NewResolver 60s cache TTL for found domains
WithNegativeTTL(d) NewResolver 30s cache TTL for unknown hosts
WithMaxEntries(pos, neg) NewResolver 100,000 positive, 10,000 negative (0 disables that cache)
WithClock(now) NewResolver time.Now for cache expiration
WithNotFound(h) Resolver.Middleware Plain 404 Not Found handler
WithAskToken(token) AskHandler Constant-time check against X-Ship-Ask-Token (AskTokenHeader)
WithAskPeers(cidrs...) AskHandler Restricts RemoteAddr to listed CIDR prefixes
WithAllowHost(fn) AskHandler Approves static platform hosts (not a caller guard)
WithInsecureNoGuard() AskHandler Disables fail-closed guard requirement for local dev

Verification problem codes

Constant Code Cause
ProblemTXTMissing "txt_missing" Missing or non-matching TXT _fletch-verify.<host> record
ProblemCNAMEMismatch "cname_mismatch" Subdomain CNAME points to a host other than Verifier.Target
ProblemAMismatch "a_mismatch" A record points outside Verifier.IPv4
ProblemAAAAElsewhere "aaaa_elsewhere" AAAA record points outside Verifier.IPv6
ProblemNoAddress "no_address" Host has no A or AAAA records
ProblemDNSError "dns_error" DNS resolver lookup failed
ProblemHTTPProbeFailed "http_probe_failed" Fallback /.well-known/fletch-domain/<token> probe failed