Integrations

An integration is an external service the app talks to: a shop platform, a payment provider, a mail API. Declare it once with defineIntegration and the framework derives what used to be repeated by hand: the settings reader and its error, the externalOrigins entry, the .env.example lines, the deploy checklist, the development mock switch, and a client that times out, hides secrets in errors and survives an outage.
ts
// src/server/fourthwall.ts
import { defineIntegration, parseSetting } from "@dash/server";

export const fourthwall = defineIntegration({
  name: "fourthwall",
  baseUrl: "https://storefront-api.fourthwall.com/v1", // where the credential may go
  settings: {
    token: {
      env: "FOURTHWALL_STOREFRONT_TOKEN",
      secret: true,
      required: true,
      description: "Storefront API token.",
    },
    checkoutDomain: {
      env: "FOURTHWALL_CHECKOUT_DOMAIN",
      required: true,
      parse: parseSetting.hostname,
    },
    currency: {
      env: "FOURTHWALL_CURRENCY",
      default: "USD",
      parse: parseSetting.isoCurrency,
    },
    webhookSecret: {
      env: "FOURTHWALL_WEBHOOK_SECRET",
      secret: true,
      list: true,
    },
  },
  auth: { type: "query", name: "storefront_token", value: "token" },
  origins: (s) => [`https://${s.checkoutDomain}`],
});
ts
// dash.config.ts
import { fourthwall } from "./src/server/fourthwall";
export default {
  integrations: [fourthwall],
} satisfies DashAppConfig;
ts
// anywhere on the server
const { currency } = fourthwall.settings();
const products = await fourthwall.client().get<Product[]>("/shops/x/products", {
  query: { currency },
});

// a webhook route (see createWebhookRoute): the list covers a secret rotation
export const POST = createWebhookRoute({
  name: "fourthwall",
  secret: () => fourthwall.settings().webhookSecret,
  // …
});

Settings

Each entry of settings names one environment variable.
Field
Meaning
envUPPER_SNAKE_CASE variable the value is read from (required).
secretA credential. Never in errors, logs or the generated files; goes to the platform's secret store.
requiredsettings() fails when it is unset and has no default.
defaultText used when unset; parsed like any other value. Not combinable with required.
listComma-separated values; the setting is an array (empty when unset).
parse(raw: string) => value. Throw SettingError (its message is shown, so it must not contain the value).
descriptionShown in .env.example and next to a missing variable.
Ready-made parsers live on parseSetting: hostname, isoCurrency, httpsOrigin, integer, boolean, oneOf(...). Empty text counts as unset.Lazy. defineIntegration reads nothing. settings() reads process.env on first use and re-reads only when a value changed. That matters because a Worker has no environment until its first request (the Worker entry copies its vars and secrets into process.env first) and because codegen imports app modules with no environment at all. Do not call settings() at module scope.One error. A missing or invalid variable throws IntegrationConfigError:
text
Integration "fourthwall" is not configured:
  - FOURTHWALL_STOREFRONT_TOKEN is not set (Storefront API token.)
  - FOURTHWALL_CHECKOUT_DOMAIN is invalid (expected a bare hostname such as shop.example.com, …)
Set them in the environment (see .env.example). Values are never shown.
The error names variables only. A parser's own exception text is dropped (only a SettingError message is shown), and the returned object keeps secret values on its prototype, so console.log(settings), JSON.stringify and { ...settings } do not show them.

Origins

origins(settings) returns the origins of the service's hosted pages (a checkout, a billing portal). The app lists the integration in dash.config.ts integrations and the framework adds those origins to externalOrigins when the SSR server boots, merged with any explicit externalOrigins. This is why origins is a function of the settings and dash.config.ts needs no get externalOrigins() getter: a Worker builds its app on the first request, after the environment exists. An integration whose settings are missing fails that boot with the error above. Do not derive origins from a secret setting.

Development stand-in

The integration owns where its credential may go: baseUrl (an https:// URL). In production nothing else is ever used. Outside production the variable <NAME>_BASE_URL replaces it, NAME being the integration name upper-cased (fourthwall → FOURTHWALL_BASE_URL, stripe-test → STRIPE_TEST_BASE_URL):
bash
bun scratch/mock-fourthwall.ts &      # any HTTP server speaking the service's API
FOURTHWALL_BASE_URL=http://127.0.0.1:4010 dash-cli start
  • Honored only when NODE_ENV is not production. A Worker sets NODE_ENV=production itself, so a stray variable on a deployed Worker is ignored (and dash-cli integrations check --deploy warns about it).
  • The framework logs one warning when it is in use. The credential is sent to the stand-in (it is your mock), which is why the override stops at production.
  • App code has no test-only branch: integration.baseUrl() and the client apply the rule.
  • Only http(s) URLs without credentials or query are accepted.

Generated files and checks

dash-cli codegen writes .dash/integrations.json: the name, base URL and, per setting, the variable, secret, required, list, default and description. It never holds a value. dash-cli reads it (indirectly, by loading dash.config.ts in a child process) for:
bash
dash-cli integrations                  # list the settings
dash-cli integrations env-example      # print the .env.example lines
dash-cli integrations env-example --write   # update the generated block of .env.example
dash-cli integrations env-example --check   # fail when that block is stale (CI)
dash-cli integrations check            # would the integrations load from this environment?
dash-cli integrations check --deploy   # … from what a deploy gives the Workers?
env-example --write maintains a block between # >>> dash integrations and # <<< dash integrations; the rest of .env.example is yours.<a id="deploy-check"></a> Deploy check. A Cloudflare deploy gives the Workers only extra_vars (plain) and extra_secrets (secret): the EXTRA_VARS_JSON and EXTRA_SECRETS_JSON inputs of the CI workflow, which reach OpenTofu as TF_VAR_extra_vars and TF_VAR_extra_secrets. The check judges exactly those, and fails when a required variable is missing, a list has no item, a plain value does not parse, or a secret setting is in the plain variables. It prints variable names only, lists every problem at once, and exits non-zero.dash-cli deploy cloudflare (also with --plan) runs it first, before the build and before any request to Cloudflare; a missing storefront token stops the deploy instead of showing up at the first request. --skip-integration-check turns it off for an app that deliberately provides a setting some other way. The same check is available by itself:
bash
bunx dash-cli integrations check --deploy
What runs, and with which values. The app's dash.config is app code, so it never sees the deploy's secrets or a credential:
  • A child process loads dash.config to write .dash/integrations.json (names, secrecy, required, list, default of every setting; always regenerated, so it is never a stale copy from an earlier codegen). Its environment is the deploy's own minus everything the deploy configures (no API token, state keys, JWT secret, TF_VAR_*, AWS_*, CLOUDFLARE_*, no Worker secrets), the same environment the build gets.
  • A second child runs each integration's check. It receives, on stdin, only the variables the integrations declare, and a secret setting's value is replaced by a placeholder (x, one per non-blank list item) that the parser is told to skip (integration.check(source, { unparsed })). So "is it set" and the shape of a list are decided by the same code that decides it at runtime, a plain setting's own parser (parseSetting.hostname, ...) runs on its real value (it is not secret, and it already travels as a plain Worker variable), and a secret's own parse does not run: a malformed credential is found by the service, not by the deploy. A parse that checks a secret's format is therefore a runtime check only.
  • Child output is redacted of every secret the deploy knows, and findings print the variable name and the parser's own message (which must never echo the value), never a value.
The deploy runs both children with the build's placeholder DATABASE_URL and DASH_GATEWAY_SECRET, for modules that insist on a value while being imported. A dash.config that fails to load is reported as a problem (--skip-integration-check gets past it). Both children need @dash/cli, @dash/deploy and @dash/server of the same release.@dash/cli exports checkDeployIntegrations and checkDeployConfig, which @dash/deploy runs. The workflow header and the README need not list an integration's variables by hand: run dash-cli integrations.

Service client

integration.client(options) (or createServiceClient(integration, options)) calls the integration's API.
ts
const api = fourthwall.client({ timeout: 8000, ttl: 60_000, maxStale: 6 * 3600_000 });
await api.get<T>("/shops/x/products", { query: { currency: "USD" } });
await api.post<T>("/carts", { items });                // also put, patch, delete
const { data, stale } = await api.request<T>("GET", "/shops/x/products");
Option (client)
Default
Meaning
timeout8000 msWhole request, headers and body. A call can override it.
ttl60 sHow long a GET answer is served without asking. 0 disables caching; a call can override it.
maxStale24 hHow old a cached GET answer may be and still be served when the service fails.
Per call: query (undefined values skipped), headers, timeout, ttl. A body that is not a string, bytes, FormData, Blob or URLSearchParams is sent as JSON.Streams. api.stream(path, { method?, body?, headers?, query?, timeout?, signal? }) returns the Response itself, for a body read as it arrives (server-sent events, a long download). Only connecting, up to the response headers, is under timeout; signal ends the rest, cancelling the upstream request. It is never cached, and a failed status throws the same ServiceError as the other calls. A live resolver reading an upstream's events is the usual caller:
ts
const response = await pi.client().stream("/v1/observability/live", { signal });
Authentication is the integration's auth, naming settings: { type: "bearer", token }, { type: "header", name, value, prefix? }, { type: "query", name, value }, { type: "basic", username, password }. A list sends every entry, for a service behind a gateway that wants a credential of its own (Cloudflare Access's two headers, then the service's token); two entries may not set the same header or query parameter:
ts
auth: [
  { type: "header", name: "CF-Access-Client-Id", value: "accessId" },
  { type: "header", name: "CF-Access-Client-Secret", value: "accessSecret" },
  { type: "header", name: "X-Pi-Gateway-Token", value: "token" },
],
A service with two APIs on different hosts (Fourthwall's storefront and platform APIs) is two integrations.Errors. Every failure is a ServiceError { service, status, code, retryable, safeMessage, upstreamCode? }; message equals safeMessage, and both are fixed text built from the code, with no upstream body, URL, credential or upstreamCode, so they are safe to log or show.
code
status
retryable
timeout504 (or 408)yes
unreachable502yes
rate_limited429yes
upstream_error5xx (not 501)yes
invalid_response502yes
unauthorized401no
forbidden403no
not_found404, 410no
rejectedother 4xxno
redirected3xxno
Redirects are not followed: a custom credential header would otherwise travel to whichever host the response names. A configuration problem is not a ServiceError; it is the IntegrationConfigError above.<a id="upstream-error-codes"></a> The service's own error code. code says what kind of failure it was; a service that answers a 4xx with a machine code in its JSON body (CART_QUANTITY_TOO_HIGH) lets the app say something a shopper can act on. Declare where the code sits, once, on the integration (or per client, which wins):
ts
export const fourthwall = defineIntegration({
  // ...
  errorCode: "code", // a path into the JSON body: "code", "error.code", "errors.0.code"
  // or a function: errorCode: (body, { status }) => (body as any)?.error?.type,
});

const shopperMessages: Record<string, string> = {
  CART_QUANTITY_TOO_HIGH: "There is not enough stock for that quantity",
  CART_OFFER_NOT_PURCHASABLE_ERROR: "This item is not available",
  CART_OFFER_NOT_FOUND: "Product not found",
  OFFER_VARIANT_NOT_FOUND_ERROR: "Product not found",
  CART_INCOMPLETE_BUNDLE_ERROR: "This bundle can't be added to the cart",
};

try {
  await fourthwall.client().post("/carts/x/items", { items });
} catch (error) {
  if (error instanceof ServiceError && error.code === "rejected")
    return {
      error:
        shopperMessages[error.upstreamCode ?? ""] ??
        "The store could not complete that request",
    };
  throw error;
}
The app maps a code to its own wording; the framework never forwards the upstream's text. Hard limits, so a hostile or malformed body cannot put anything into a log, a trace or a screen:
  • The result is kept as ServiceError.upstreamCode only when it is 1 to 64 characters of A-Z a-z 0-9 _ . - (a safe integer also counts, as its digits). A longer code, a URL, a sentence, any other type is dropped, not cut. A code that contains the integration's credential (an upstream that echoes it back) is dropped too.
  • Only the code is kept. The body is never stored, cached, logged or attached to the error. It is read only when errorCode is set, and only the first 16 KiB of it: a larger body, one that is not JSON, or one that cannot be read simply yields no code. The extractor sees the parsed JSON and { status }, nothing else.
  • A path never reads __proto__, constructor or prototype and only follows own properties.
  • An extractor that throws, or returns a promise, is ignored: the plain error is thrown.
  • It applies to any failed response (4xx and 5xx). A failed response is never cached as an answer, and stale-if-error is unchanged (a retryable failure still serves the last good answer; the code is added to the warning and to the span as service.upstream_code).
Cache and stale-if-error. Only GETs are cached. A response younger than ttl is returned directly. Otherwise the client asks the service; if that fails with a retryable error and an answer no older than maxStale exists, that answer is returned (request() says stale: true, and a warning with the error code is logged). A 404 or a rejected credential is never papered over with old data. For ten seconds after a failure, requests that have a stale answer to give skip the service instead of each waiting out the timeout. Identical GETs in flight share one request.Where it is kept: on Cloudflare Workers the Cache API (caches.default), shared by every isolate in the data center and surviving restarts, with a bounded in-memory map in front of it; on Bun, Deno and in development only the map. Writes go through runInBackground, so the Worker entry hands them to waitUntil. Responses over 1 MiB are not kept. The Cache API is per data center, and unavailable on workers.dev hostnames (the map still works there).The cache key is one SHA-256 over the integration name, method, URL without its credential, per-call headers and a digest of the credential. It holds no secret, and two apps with different credentials that share a cache never read each other's responses.

Not covered

  • Request retries and circuit breaking beyond the ten-second backoff above.
  • Uploading or streaming request bodies, and streaming responses (the client reads text).
  • Webhooks: inbound events are createWebhookRoute; an integration only supplies its secret (webhookSecret above).
  • Consumer apps: where dash.config.ts sits in an app.
  • Navigate action: what origins feeds.
  • Cloudflare: Workers vars and secrets, and deploying from CI.