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.// 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}`],
});// dash.config.ts
import { fourthwall } from "./src/server/fourthwall";
export default {
integrations: [fourthwall],
} satisfies DashAppConfig;// 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 names one environment variable.Field | Meaning |
|---|---|
| env | UPPER_SNAKE_CASE variable the value is read from (required). |
| secret | A credential. Never in errors, logs or the generated files; goes to the platform's secret store. |
| required | settings() fails when it is unset and has no default. |
| default | Text used when unset; parsed like any other value. Not combinable with required. |
| list | Comma-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). |
| description | Shown in .env.example and next to a missing variable. |
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: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.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(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.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):bun scratch/mock-fourthwall.ts & # any HTTP server speaking the service's API
FOURTHWALL_BASE_URL=http://127.0.0.1:4010 dash-cli startNODE_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).integration.baseUrl() and the client apply the rule.http(s) URLs without credentials or query are accepted.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: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:bunx dash-cli integrations check --deploydash.config is app code, so it never sees the
deploy's secrets or a credential: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.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.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.integration.client(options) (or createServiceClient(integration, options)) calls the
integration's API.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 |
|---|---|---|
| timeout | 8000 ms | Whole request, headers and body. A call can override it. |
| ttl | 60 s | How long a GET answer is served without asking. 0 disables caching; a call can override it. |
| maxStale | 24 h | How old a cached GET answer may be and still be served when the service fails. |
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:const response = await pi.client().stream("/v1/observability/live", { signal });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: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" },
],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 |
|---|---|---|
| timeout | 504 (or 408) | yes |
| unreachable | 502 | yes |
| rate_limited | 429 | yes |
| upstream_error | 5xx (not 501) | yes |
| invalid_response | 502 | yes |
| unauthorized | 401 | no |
| forbidden | 403 | no |
| not_found | 404, 410 | no |
| rejected | other 4xx | no |
| redirected | 3xx | no |
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):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;
}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.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.__proto__, constructor or prototype and only follows own properties.service.upstream_code).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.createWebhookRoute; an integration only supplies its
secret (webhookSecret above).dash.config.ts sits in an app.origins feeds.