Docs/Web & UI/Multi-domain & hosting

Multi-domain & hosting

Serve separate brand domains, parameterized subdomains, and wildcard hosts from one Fletch binary with forwarded headers, per-site assets, and local HTTPS.

github.com/fletchhq/fletch/router

fletch/routerpkg.go.devfletchpkg.go.dev

Updated 2026-12-06 fletch docs show hosting 8 min read

On this page

A single Fletch binary can serve separate brand domains, tenant subdomains, and wildcard custom domains side by side. Host routing lives in github.com/fletchhq/fletch/router, while per-site asset resolution and admin host mounting live in the root github.com/fletchhq/fletch package.

Introduction

Running separate deployments for a marketing site, an admin panel, and tenant subdomains adds operational overhead you often do not need. Fletch lets you group routes by host pattern inside the same router, attach host-specific middleware, and resolve per-site asset bundles per request.

Apps that never call r.Host stay host-blind and pay zero routing overhead. When you do need customer-owned custom domains with DNS verification and on-demand TLS, pair Fletch's wildcard Host("*") group with the standalone domains ecosystem module.

Core concepts

Host patterns

r.Host(pattern, mw...) returns a child *router.Router whose routes and mounts match only requests for that host pattern. Fletch supports three pattern forms in one app.

// 1. Static separate domains
brand := r.Host("brand-a.com")
brand.Handle(http.MethodGet, "/", brandHome)

admin := r.Host("admin.platform.com")
admin.Handle(http.MethodGet, "/", adminHome)

// 2. Parameterized subdomains (plain, constrained, or multi-label)
sites := r.Host("{site}.platform.com", tenantMW)
sites.Handle(http.MethodGet, "/posts/{slug}", showPost)

strict := r.Host("{site:[a-z0-9-]{3,40}}.platform.com", tenantMW)
regional := r.Host("{site}.{region}.platform.com", tenantMW)

// 3. Catch-all wildcard for dynamic or customer-owned domains
custom := r.Host("*", customDomainMW)
custom.Handle(http.MethodGet, "/", customHome)

Each host parameter matches one whole DNS label. Host parameter names and path parameter names in the same route must differ, and you cannot nest Host inside another Host group (doing so panics at boot).

Normalization and matching precedence

When at least one Host group is registered, the router normalizes every incoming Host header with router.NormalizeHost(h). Normalization strips any port and a single trailing dot, lowercases ASCII characters, and rejects invalid or non-ASCII values with 400 Bad Request.

You may also call router.NormalizeHost directly when normalizing host values stored in configuration or a database:

host, ok := router.NormalizeHost(rawHost)
if !ok {
	return errors.New("invalid host")
}

Matched hosts resolve in a fixed order:

  1. Exact host (admin.platform.com).
  2. Parameter patterns ({site}.platform.com), ranked by more static labels first, then more constrained parameters, then registration order. Ambiguous patterns of the same shape (such as {site}.platform.com and {tenant}.platform.com) panic at boot.
  3. Wildcard (*).

IP literals match only exact patterns or *. They never match {param} patterns.

Fallthrough and unknown hosts

By default, a request whose host matches a Host group falls through to host-agnostic (root) routes when the group itself has no matching route or mount. This keeps shared infrastructure endpoints (/healthz, /readyz, /metrics, /assets/, /_fletch/live, and /_fletch/tls/ask) reachable on every host without duplicate registrations.

To make every Host group strict so it answers 404 or 405 from its own routes only, disable fallthrough with router.WithHostFallthrough(false). When a request's host matches no Host group (and there is no * group) and no root route matches either, the router invokes the handler set by router.WithNotFoundHost (default http.NotFound).

app := fletch.New(
	fletch.WithRouterOptions(
		router.WithHostFallthrough(false),
		router.WithNotFoundHost(http.HandlerFunc(unknownHostPage)),
		router.WithURLScheme("https"),
	),
	fletch.WithRoutes(routes),
)

Reading hosts and building absolute URLs

Inside a handler, read the matched host metadata from router.Ctx or the standard *http.Request:

  • c.Host() returns the normalized host (or "" on a host-blind router).
  • c.HostPattern() returns the matched Host group pattern (such as "{site}.platform.com" or "*", or "" for a root route).
  • c.Param("site") or r.PathValue("site") reads a host parameter.

To generate full links across hosts, use rt.AbsURL(name, pairs...) for named routes in exact or parameterized Host groups, or rt.AbsURLOn(host, name, pairs...) for wildcard (*) and root routes. Both use the scheme set by router.WithURLScheme (default "https").

// Named route in r.Host("{site}.platform.com")
postURL, err := rt.AbsURL("posts.show", "site", "acme", "slug", "launch")
// https://acme.platform.com/posts/launch

// Named route in r.Host("*") served on a customer domain
customURL, err := rt.AbsURLOn(tenant.PrimaryHost, "posts.show", "slug", "launch")

Never build email or background-job links from an incoming r.Host. Store a primary host on each tenant record and pass it to rt.AbsURLOn instead.

Common tasks

Trusting proxy headers

The router does not trust X-Forwarded-Host or X-Forwarded-Proto by default. When running behind a reverse proxy or load balancer, configure trusted proxy CIDRs with router.WithForwarded.

app := fletch.New(
	fletch.WithRouterOptions(
		router.WithForwarded(
			router.PrivateRanges,
			router.WithForwardedProto(),
		),
	),
	fletch.WithRoutes(routes),
)
app := fletch.New(
	fletch.WithRouterOptions(
		router.WithForwarded(
			router.PrivateRanges,
			router.WithForwardedProto(),
			router.WithForwardedHost(),
		),
	),
	fletch.WithRoutes(routes),
)

router.WithForwarded runs inside ServeHTTP before host matching, so WithForwardedHost() takes effect before Host groups are evaluated. If you only need forwarded headers inside downstream middleware or handlers (after host matching), you may use the router.ForwardedHeaders(cidrs, opts...) middleware instead.

For comma-separated or repeated headers, Fletch reads the rightmost non-empty value (the entry written by the proxy closest to your server). Client-injected values on the left are ignored. router/secure emits HSTS only when r.TLS != nil or router.TrustedProto(r) returns "https".

Serving per-site asset bundles

When separate brands in one binary ship different stylesheets or scripts, pass fletch.SiteAssets(byHost, fallback) as middleware. It normalizes the map keys with router.NormalizeHost and swaps the request's asset resolver for assets.FromContext, Crest's asset() helper, and any Live views mounted by that request.

app.Use(fletch.SiteAssets(map[string]assets.Resolver{
	"brand-a.com": resA,
	"brand-b.com": resB,
}, nil))

app.Router().Host("brand-a.com").Mount("/assets/", resA.Handler())
app.Router().Host("brand-b.com").Mount("/assets/", resB.Handler())

fletch.SiteAssets only controls asset resolution; mount each bundle's Handler() on its host group as shown above. Hosts absent from byHost use fallback, or keep the app's default resolver when fallback is nil. Passing an invalid host key, duplicate normalized keys, or a nil resolver panics at boot.

Isolating an admin panel on its own host

Use fletch.MountAdminHost to expose admin panels only on a dedicated host. Every other host receives 404 for the panel's paths.

if err := fletch.MountAdminHost(app, "admin.platform.com", panel); err != nil {
	log.Fatal(err)
}

Protecting Live views and sessions across hosts

Same-origin checks work automatically across dynamic hosts as long as your reverse proxy preserves Host. For tenant isolation across multiple domains, combine three controls:

  • Pass live.WithHostBinding() to every Live handler so a session created on one tenant host cannot be rejoined from another.
  • Pass live.WithOriginCheck(fn) when a Live view needs a custom cross-origin policy across WebSocket, SSE, and POST transports.
  • Keep session cookies host-only (Fletch's default) and prefix names with __Host- for custom domains. If you want shared SSO cookies across *.platform.com, opt in with auth.WithCookieDomain or auth.WithCookieDomainFunc, returning "" for custom domains so they stay host-only.

For OAuth sign-in on customer-owned domains, keep the callback on one platform host (such as auth.platform.com/oauth/callback) and use auth/handoff to redirect the user back with a short-lived, single-use, host-bound token. For dynamic custom domain storage, DNS verification, and on-demand TLS ask endpoints, see the Custom domains guide.

Local HTTPS development with multiple hosts

Fletch supports wildcard host testing locally without editing /etc/hosts by hand.

Use fletch dev --https when one app needs subdomains under .localhost. Fletch mints a trusted local certificate for *.<app>.localhost after you run fletch tls trust once.

For .test domains across one or more apps (https://<site>.test, https://tenant.<site>.test, and https://dashboard.<site>.test), run the local DNS responder and HTTPS reverse proxy:

fletch tls trust
sudo fletch dns setup

# Inside your app directory
fletch dev
fletch link

# In another terminal
sudo fletch proxy

fletch proxy routes tenant.<site>.test to your linked <site> app by falling back to <site>.test while preserving the incoming Host header, so your Host groups and subdomain parameters behave just as they do in production.

Inspecting host routes and running checks

Inspect how Fletch compiles and matches your host groups from the CLI:

fletch routes
fletch routes --host acme.platform.com
fletch ax inspect hosts
fletch check

When host routes exist, fletch routes adds a HOST column, and --host <h> runs your route table through the real host matcher. fletch ax inspect hosts outputs host groups and host-routing metadata as structured JSON for tooling and agents.

Reference

Router options and helpers

Symbol Package Behavior
(*Router).Host(pattern, mw...) *Router router Creates a host-scoped router for an exact host, {param} pattern, or "*".
NormalizeHost(h string) (string, bool) router Strips port and trailing dot, ASCII-lowercases, and validates a host string.
WithHostFallthrough(on bool) Option router Controls fallback from a matched Host group to root routes. Default true.
WithNotFoundHost(h http.Handler) Option router Handler for unmatched hosts when no "*" group or root route matches. Default http.NotFound.
WithURLScheme(scheme string) Option router Scheme used by AbsURL and AbsURLOn. Default "https".
(*Router).AbsURL(name, pairs...) (string, error) router Builds an absolute URL for a named route in an exact or parameterized Host group.
(*Router).AbsURLOn(host, name, pairs...) (string, error) router Builds an absolute URL for any named route on an explicit host.
WithForwarded(cidrs, opts...) Option router Applies trusted X-Forwarded-Proto / X-Forwarded-Host before host matching.
ForwardedHeaders(cidrs, opts...) router Middleware applying trusted forwarded headers after host matching.
PrivateRanges router CIDR list covering loopback, RFC 1918, and IPv6 unique-local networks.
TrustedProto(r *http.Request) (string, bool) router Returns the scheme reported by a trusted proxy via X-Forwarded-Proto.
SiteAssets(byHost, fallback) fletch Middleware choosing a per-host assets.Resolver for each request.
MountAdminHost(app, host, panels...) error fletch Mounts admin panels on a single host only.

Host diagnostics (W0800–W0804)

Code Severity Meaning Fix
W0800 Error Invalid host pattern, wildcard inside a label (such as shop.*.com), ambiguous parameter pattern, or a host parameter colliding with a path parameter in the same route. Fix the pattern syntax, disambiguate parameter shapes, or rename the colliding parameter.
W0801 Warning Non-infrastructure route registered on the root router while Host groups exist and fallthrough is on. Move the route into a Host group, or pass router.WithHostFallthrough(false).
W0802 Error On-demand TLS ask endpoint (/_fletch/tls/ask or domains.AskHandler) registered inside a Host group. Register the ask endpoint on the root router so loopback proxy checks match.
W0803 Error domains.AskHandler registered without a caller guard (even if WithAllowHost or WithInsecureNoGuard is passed). Pass domains.WithAskToken(...) or domains.WithAskPeers(...). See /docs/ecosystem/domains.
W0804 Warning Live handler (fletch.MountLive, fletch.Live, or live.New) created without live.WithHostBinding() in an app with Host groups. Pass live.WithHostBinding() so Live sessions stay bound to their originating host.