heulen-shop uses it so the platform can manage its store (domains, catalogue, secrets, theme). We give each customer their own deployment of the shop, so in practice a deployment serves one store; the pooled model below is what the framework allows, not how the shop is run.Tenancy is opt-in. An app without tenancy in its config behaves exactly as before.id. The app keeps its own record (name, slug, brand) and returns it from resolve.TenantRequiredError, 500), never another tenant's rows.tenancyexport const orders = defineCollection({
slug: "orders",
tenancy: true, // or { field: "storeId" }
fields: [
{ name: "id", type: "id" },
{ name: "tenantId", type: "text", required: true }, // you declare it
// …
],
});ownerId), and must differ from the ownership field. With tenancy on, the Local API:find, findById, update and delete (ANDed with the access rule's where, and passed to the adapter as one atomic condition, so an id from another tenant is simply not found);create, ignoring a tenantId in the data;update (it is managed and immutable, like the owner field);overrideAccess: true. overrideAccess skips access rules, not tenancy.<table>_tenant_idx on the tenant field (SQLite and Postgres).tenanted(collection, field = "tenantId") returns a copy of a framework-defined collection with tenancy on. Apply it to sessionCollection and webhookEventCollection so sessions and webhook idempotency are per store:(tenanted(sessionCollection), tenanted(webhookEventCollection));import { runInTenant, runAcrossTenants, currentTenantId } from "@dash/data";
await runInTenant("acme", () => data.find({ collection: "orders" }));
await runAcrossTenants(() => data.find({ collection: "tenants" }));runInTenant is what the server binds per request. runAcrossTenants is the one way out: the registry that maps a host to a tenant, operator jobs, platform consoles. It is deliberately loud so a search finds every place that can see across tenants. A create inside it must name the tenant in the data. Code that runs outside a request, such as seed, has no tenant and must use one of the two.createTenancy// dash.config.ts
import { createTenancy, hostOf } from "@dash/server";
export default {
tenancy: createTenancy<ShopTenant>({
async resolve(req) {
const host = hostOf(req);
return findStoreByHost(host); // a record with an `id`, or null
},
settings: (tenant, integration) => vault.read(tenant.id, integration),
cacheSeconds: 30,
isPublic: (req) => new URL(req.url).pathname === "/api/operator",
}),
} satisfies DashAppConfig;fetch of both the API and the SSR app, before sessions and rate limiting. For every request it:resolve runs across tenants, so it can read the registry);notFound to change that), so a stray Host header reaches no store;@dash/data (runInTenant) and for getTenant() / requireTenant();active store is routed; a pending one gets a 503 instead, with the app's errorPages[503] page (see below) or a short default notice (JSON under /api/), never cached. A suspended one is as good as unknown (404). Nothing behind the gate runs for a store that is not open.pending and the platform makes it active (Admin → the store → Go live); the application never decides it is ready, and no request code guards against "not live yet" because it never runs for such a store. Management calls (runAs, the Connections and profile forms) are not gated: a pending store is exactly the one being set up. The status is part of the registry row the platform pushes, so it is cached per instance for cache seconds like the rest of the store's record; a CMS or integrations write drops the cache of the instance that handled it.What the application contributes is what a store needs, declared where the needs already are:defineIntegration({ required: true, … }): the store must have connected it (a catalogue supplier, say);required in the tenancy.tenant.profile collection: the store must have filled it in.readiness management service (operation check, role platform) that lists what a store still lacks, one line each (Fourthwall is not connected; a required profile field would read Store profile: legal name is required). The platform calls it when an operator makes a store active and refuses, with that list, while it is not empty; Admin shows the same list as a checklist beside the button. Reinstating a suspended store returns it to pending first (an application does not answer for a suspended store) and is then asked the same way. Declaring a need is the whole job: the app has no ready option and no flag of its own.A store that is live and later loses a required connection is not closed automatically; its requests fail loudly (catalogue() throws) until it reconnects or the platform suspends it. See Handling edge cases./healthz and anything isPublic accepts belong to no tenant. Match only hostnames the platform has registered and verified: the Host header is the visitor's to choose.Caching. The resolved tenant and its settings are kept per host for cacheSeconds (default 30, bounded to 500 hosts; a lookup under way is never shared between requests, see Cloudflare; unknown hosts are remembered too so a crawler guessing names costs one lookup per interval). tenancy.invalidate(id?) drops them at once in that isolate. The API and SSR bundles and every Worker instance have their own cache, so a change made in one is visible elsewhere within cacheSeconds. Suspending a store, changing its brand or domain takes up to that long to reach every instance. A console that edits a tenant should read its own values from the database, not from the cached record, so a saved form never shows stale values.defineIntegration(...).settings() reads the tenant's settings instead of process.env once a tenant is bound. It never falls back to the environment: a tenant that has not connected an integration gets an IntegrationConfigError (with tenant: true), not the platform's own credentials. App code that must work for an unconnected store asks integration.connected() instead of catching; to keep an unconnected store from going live at all, mark the integration required: the platform refuses to open the store until it is connected.integration.validate(values) checks a map keyed by setting key and returns problems with key, so a connection form can show them next to the field. The integration's origins, the externalOrigins allow-list for navigate, is evaluated per request in tenancy mode; externalOrigins may be a function there, and an unconnected tenant contributes none.const vault = createSettingsVault({ data }); // add tenantSettingsCollection to the appDASH_VAULT_KEYS: base64 of 32 random bytes, comma-separated, newest first. New payloads are sealed with the first; any listed key still opens its own. To rotate, put a new key in front, deploy, and re-save (or re-seal) settings; remove the old key once nothing is sealed with it. Payloads are v1.<keyId>.<iv>.<ciphertext> and the key id is a digest prefix, not the key.access: {}: nothing reaches it over HTTP.vault.read(tenantId, integration) is what createTenancy({ settings }) wants. vault.forTenant(tenantId) is for consoles:Method | |
|---|---|
| describe(integration) | each setting: key, secret, required, set, and value for a non-secret one. A secret is never returned, only whether it is set. |
| isConnected(integration) | every required setting present and valid |
| update(integration, patch) | merge and store. A string sets, null or empty removes, undefined keeps. Unknown keys are dropped, invalid results store nothing and return { ok: false, problems } |
| disconnect(integration) | removes the row |
requireTenant().id and checks who is signed in first. A secret field is write-only: leaving it empty in a form keeps the stored value.seo.site takes the store's name, URL, description and share picture from fields of the tenant record (const store = tenantRefs<Store>(), then store.name): an empty field is left out, and what head sets as well wins. themeEditor() (a plugin from @dash/theme-editor/server) adds the editor to management, the CSS of the store's default theme to the tenant record (themeCss) and that CSS to every document's head, so the theme is mentioned once in the config.head in the app config may be a function evaluated per request: head: () => ({ url, name, description, image, css }).SiteHead.css renders as an inline <style data-site> after the app stylesheets, so it overrides the built-in tokens. It is refused if it contains </style>, <script or <!--.themeCss(theme) from @dash/theme-editor/css validates a theme and returns its token block; defaultThemeCss(registry) does so for the registry's default theme. Values pass the editor's own safety check (no URLs, no escaping out of a declaration).createDataThemeStore({ data }) is a ThemeStore for the theme editor kept in the theme_catalogs collection (add themeCatalogCollection), one catalogue per tenant, with the same revision checking as the file store.loadPublishedThemes() on the client apply the saved registry once it loads.// the application
const tenancy = createTenancy<Store>({
resolve: (req) => storeByHost(hostOf(req)),
byId: (id) => storeById(id), // new: how a call names a tenant
settings: (tenant, integration) => vault.read(tenant.id, integration),
});
export const management = createManagementProvider({
applicationId: "shop",
services: [themes, integrations],
tenancy,
integrations: [fourthwallIntegration],
});// the gateway
createGateway({
applications: [
{
id: "shop",
name: "Shop",
provider,
canAccess: (user) => isSignedIn(user),
tenants: async (user) => membershipsOf(user), // [{ id, name, role }]
},
],
getUser,
});createTenancy({ byId }) adds tenancy.runAs(tenantId, fn, { integrations }): data scope, tenant record and settings are bound as for a request. A tenant byId does not return is a NotFoundError; a tenancy without byId cannot runAs. Lookups are cached like hosts, and invalidate(id) also drops a tenant remembered as unknown.createManagementProvider({ tenancy, integrations }) runs a call that names a tenant through runAs, and operations see context.tenantId. A provider without a tenancy refuses such a call rather than run it unscoped. A call that names no tenant runs with nothing bound, so tenanted collections refuse it (TenantRequiredError) until the operation uses runInTenant or runAcrossTenants itself.ManagedApplication.tenants(user) makes an application tenant-aware. The gateway calls it on every invoke, refuses a tenant that is not in the answer as "not found" (so existence is not revealed), and passes the provider a user whose role is the one held in that tenant. For a tenant-aware application the gateway's own canAccess (administrators by default) does not apply, since clients belong there; the application's canAccess and each service's canAccess decide. Without a tenant-aware application nothing changes: the gateway is for administrators.ManagedApplicationInfo) gains tenants: [{ id, name, role, services }]: for each tenant the caller may act in, the services their role there may use. createGatewayClient().invoke(app, call, { tenantId }) names the tenant.createRemoteManagementProvider, createGatewayAppHandler) the tenant is part of the signed identity (tenant), so it cannot be added, changed or removed in transit, and a token without one verifies as before. The remote application trusts it for its own tenants only; the gateway is the only place that mints it, after the membership check.GATEWAY_APPLICATIONS does not support tenants yet; tenant-aware applications use a gateway composed in code (the platform's Admin).createIntegrationsService({ integrations, vault, tenancy }) is the management service behind a "Connections" screen. It knows no integration by name: whatever the application declares with defineIntegration is listed, and each form is generated from the integration's manifest. Operations act for the tenant the call names (a call without one is refused).Operation | |
|---|---|
| list | every integration: connected, verifiable, and each setting's key, secret, required, description, set, and value for a non-secret. No secret is ever returned. |
| update { integration, values } | a string sets a setting, null or an empty string removes it, a key left out keeps what is stored (so a secret need not be retyped). Nothing is stored unless the merged result is valid; otherwise { ok: false, problems } names each key. The instance's cache is invalidated. |
| disconnect { integration } | removes the settings |
| test { integration, values? } | tries the stored settings with values applied over them, without storing: { ok, verified } or { ok: false, message } |
admin) or a tenant's owner; pass canAccess to change it.An integration can declare how to prove its settings work:export const fourthwall = defineIntegration({
name: "fourthwall",
…,
verify: async (self) => {
// `self.settings()` and `self.client()` are bound to the values being tried
await self.client().get("/shop");
},
});verify runs within ten seconds. Throw VerificationError("The token was refused") for a message worth showing; a ServiceError shows its safe message; anything else is reported only as "could not be verified", so a failure cannot echo a secret. integration.checkConnection(values) is the function the service uses; an integration without verify answers verified: false.dash.config: the tenancy and management sectionsconst store = tenantRefs<Store>(); // type Store = TenantOf<StoreProfileRecord>
export default defineConfig({
// The stores' own themes: the editor as a management service, its CSS in the tenant
// record, and that CSS on every page.
plugins: [themeEditor()],
tenancy: {
platformDomain: env("PLATFORM_DOMAIN"),
vault: { keys: env("DASH_VAULT_KEYS") },
cache: "30s",
// What a request knows about its store: the registry's row and address, and the
// fields of its own one-row profile collection. Its required fields are part of
// what a store needs before the platform opens it.
tenant: { profile: "store_profile" },
},
// The app's own page for an error status: a page route of the app, rendered as the
// store (its theme, the visitor's language) with that status and never cached. It
// answers a browser's request for a page: a path nothing matches (404), a page that
// failed (500) or a request the server refused before routing (503, a store the
// platform has not opened yet). API and data requests keep their JSON answers.
errorPages: { 503: "/not-open" },
// What each store's pages say about it in search results and link previews.
seo: {
site: {
url: store.url,
name: store.name,
titleTemplate: "{title} · {name}", // `Cart · Acme`; a title that is the name stays
description: store.description,
image: store.shareImageUrl,
},
},
management: {
id: "shop",
secret: env("DASH_GATEWAY_SECRET"),
access: ["admin", "owner"],
services: [
registryService(),
integrationsService(),
cmsService({ collections: ["store_profile"] }),
],
},
integrations: [fourthwall],
});tenancy builds the registry, the vault and the Tenancy (host → store from the
registry, byId for management calls, settings from the vault). tenant is what a
request knows about its store (requireTenant(), a head), cached with the store:{ profile, with } needs no code. The record is the registry row (id, slug,
name, status) and url (the store's verified custom domain, else
<slug>.<platformDomain>, else the address the request came in on), plus every field
of the profile collection (a tenanted collection with one row per store; the id, the
tenant field and timestamps are left out; a store with no row yet gets "", 0 or
false by the field's type), plus each field of with, which another package
computes (themeCss() from @dash/theme-editor/server, which themeEditor() adds for you:
the CSS of the store's default theme, "" for the built-in look). The registry's fields win over a profile's.({ tenant, url, registry, vault }) => record for anything else; it runs
inside the store's data scope, so it can read the store's own rows.
Type the record with TenantOf<StoreProfileRecord> (the generated record type of the profile
collection, plus { themeCss: string }-style With fields): DefaultTenant is the registry row and
url, and TenantOf adds the profile's fields, none of them optional (requireTenant<Store>()). public lists extra paths that belong to no store. Pass a
createTenancy(...) of your own instead of the options for full control.management is plain options: the application's id, the shared secret, who accesses
it and the services, each described by the package that owns it (registryService,
integrationsService from @dash/server, themeService from @dash/theme-editor/server,
cmsService from @dash/cms/server). The channel's own code (signed-request check,
replay protection, the handler) is in @dash/server, so no extra import is needed. The
server mounts it at its path (default
/api/gateway), treats that path as belonging to no store, and builds it on the first
request, because the secret is in the environment. access is the list of roles
that may use the services that do not decide for themselves (the registry service
keeps its own rule: the platform's identity only). The nonce store needs
gatewayNonceCollection in the app's collections.env(...) references of both sections are what dash-cli deploy cloudflare
checks against the deploy settings, so a store deployment without DASH_VAULT_KEYS
or DASH_GATEWAY_SECRET stops before it builds.createTenantRegistry({ data, platformDomain }) is the application's half. Add registryTenantsCollection and registryDomainsCollection (neither is tenant-scoped, and nothing reaches them over HTTP), then:const registry = createTenantRegistry({
data,
platformDomain: () => process.env.PLATFORM_DOMAIN,
});
const tenancy = createTenancy({
resolve: (req) => registry.byHost(hostOf(req)),
byId: (id) => registry.byId(id),
});
createManagementProvider({
applicationId: "shop",
tenancy,
services: [registry.service({ onChange: (id) => tenancy.invalidate(id) })],
});byHost resolves a verified custom domain, else <slug>.<platformDomain>; an unverified domain and a suspended tenant are not served. The registry service takes pushes from the platform's service identity (role platform; an operator's admin role is deliberately not enough): upsertTenant, removeTenant (also removes its hostnames), upsertDomain, removeDomain, and snapshot for the platform's reconcile. Every push is idempotent. A slug or hostname cannot be taken from another tenant by upsert, and a domain can only be pushed after its tenant.unique field is unique across tenants. Per-tenant uniqueness (a composite of tenant and field) is not supported yet.supportedLocales is one list for the deployment, not per tenant.cacheSeconds before another instance sees a change.tenancy; wrap framework collections in tenanted.registryTenantsCollection and registryDomainsCollection (not tenanted) and the tenancy section (or createTenantRegistry, read only inside resolve and byId of createTenancy).DASH_VAULT_KEYS as a secret and add tenantSettingsCollection (and themeCatalogCollection, if the store has a theme).management section (by hand: createGatewayAppHandler at /api/gateway with consumeNonce: createDataNonceStore(data) (add gatewayNonceCollection), a provider built with tenancy and integrations, and /api/gateway in isPublic. Build the handler on the first call on Workers, since the secret is read from the environment).registry.service(), createIntegrationsService, the theme-editor service over createDataThemeStore, and the CMS service for the collections a store edits. Restrict who may use each (canAccess). Keep a store's own brand in an ordinary tenanted collection.verify so Admin can offer "Test".tenanted(sessionCollection)), so a cookie replayed on another store's host finds no session.