Deploy and purge¶
The repository builds two Workers -- the site worker (src/index.ts) and the
media worker (src/media/index.ts) -- across six Wrangler environments. This
page covers the environment layout, the deploy and dry-run scripts, the secrets
each env needs, and the cache-purge endpoint including the hostname-scoped
purge.
Source:
wrangler.toml,package.json,.github/workflows/ci.yml,src/admin/purge.ts,src/cache/index.ts.
Environment layout¶
wrangler.toml defines six [env.*] blocks. Four run the site worker, two
run the media worker. The site worker is the same code for every env --
what differs per env is the route, the KV namespace, and whether CMS_SITE_ID
pins the worker to one CMS site or leaves it unset so the worker resolves the
site from the request Host (see
Routing).
| Env | Worker name | Worker | Route | CMS_SITE_ID |
Notes |
|---|---|---|---|---|---|
site-stage |
cms-cf-worker-stage |
site | stg.wantskicks.com/* (zone) |
WK (override) |
Stage site worker, KV-backed. |
site-stage-mk2 |
cms-cf-worker-stage-mk2 |
site | stg2.wantskicks.com (custom_domain) |
WK (override) |
P1 generic-engine canary on stg2, styled from the DB styles registry. |
site-dev |
cms-cf-worker-dev |
site | dev.fashionradar.net (custom_domain) |
(unset) | Multi-site host-resolution proof for AISD-157 -- resolves FRDEV by host, exercising the same code path a production multi-tenant deploy would use. |
site-prod |
cms-cf-worker-prod |
site | wantskicks.com/* (zone) |
WK (override) |
Production site worker. |
media-stage |
cms-cf-media-stage |
media | stg.wantskicks.com/cmp-media/*, stg2.wantskicks.com/cmp-media/*, dev.fashionradar.net/cmp-media/* (zone) |
-- | Serves stage, stg2, and dev media from the stage S3 bucket. |
media-prod |
cms-cf-media-prod |
media | wantskicks.com/cmp-media/* (zone) |
-- | Production media worker. |
A few details worth calling out:
CMS_SITE_IDis an override, not a requirement.site-stage,site-stage-mk2, andsite-prodall pin toWKtoday, so each still behaves as a single-tenant deploy in practice.site-devis the one env that leaves it unset, which is what makes the worker resolve the site from the request host instead. Any env can be switched from pinned to host-resolved (or vice versa) purely by adding or removing the var -- no code change.site-stage-mk2is the stg2 canary. It deploys the data-driven engine in parallel with the legacy stage worker, on acustom_domainrather than a zone route.custom_domain = truelets Wrangler provision the stg2 DNS record and TLS cert without a manual edit on the prod zone. Its CSS comes from the DB-backed styles registry rather than any per-worker override -- see Styles and CSS.site-devis the host-resolution proof target. It cannot reusesite-stage-mk2's config because that env'sCMS_SITE_ID = "WK"pin must stay (stg2 has to keep servingWK); a single wrangler env value cannot be both "stg2 via override" and "dev via host" at once, so AISD-157 added a dedicated env instead. It currently reuses the mk2 stg KV namespace; a dedicateddevKV namespace can be created later withwrangler kv:namespace createand swapped into its binding.account_idis pinned on every stage-account env (site-stage,site-stage-mk2,site-dev,media-stage). The stage deploy token (CLOUDFLARE_API_TOKEN) lacks theUser Details:Readpermission that Wrangler needs to resolve the account automatically via/memberships, so the account id is hardcoded inwrangler.tomlinstead.site-prodandmedia-proddeploy with a separate token (CLOUDFLARE_API_TOKEN_PROD) and do not need the pin.- The media worker route is more specific than a site custom domain. A
worker route at
stg2.wantskicks.com/cmp-media/*(ordev.fashionradar.net/cmp-media/*) beats the site worker's custom domain for that subpath, somedia-stageserves stg2's and dev's media from the same stage bucket as stg. A newly scaffolded site on a custom domain needs its own/cmp-media/*route added tomedia-stageso its media resolves same-origin (path keys carrysite-<id>); without that route the media requests fall through to the site worker instead of the media worker. - Only the site worker uses KV. Each site env binds a
KVnamespace (with per-env namespace ids inwrangler.toml). The media worker is stateless -- edge Cache API only, no KV.
Site worker env vars¶
Each site env sets non-secret vars in its [env.*.vars] table:
CMS_API_BASE_URL (the CMS public v2 API base -- cms-api-stg.skyneto.com for
stage/stg2/dev, cms-api-prd.skyneto.com for prod), the optional CMS_SITE_ID
override described above, and PAGE_TYPE_TTLS (per-page-type cache TTLs). Every
site env -- site-stage included -- now resolves its stylesheet from the
DB-backed styles registry (active_style); the former SKIP_STYLES_REGISTRY
opt-out is no longer set on any env (see Styles and CSS).
Media worker env vars¶
Each media env sets S3_BUCKET (cms-media-stg-891708857119 for stage,
cms-media-891708857119 for prod), S3_REGION (us-east-1), and
MEDIA_CACHE_TTL (604800, 7 days).
Deploy and dry-run scripts¶
package.json wraps wrangler deploy --env <env> in npm scripts:
"deploy:site-stage": "wrangler deploy --env site-stage",
"deploy:site-prod": "wrangler deploy --env site-prod",
"deploy:media-stage": "wrangler deploy --env media-stage",
"deploy:media-prod": "wrangler deploy --env media-prod",
"dry-run:site-stage": "wrangler deploy --dry-run --env site-stage",
"dry-run:site-prod": "wrangler deploy --dry-run --env site-prod",
"dry-run:media-stage": "wrangler deploy --dry-run --env media-stage",
"dry-run:media-prod": "wrangler deploy --dry-run --env media-prod"
Each dry-run:* script builds and validates the bundle for that env without
publishing -- use it as a pre-flight check before the matching deploy:*.
There is also a deploy:site-stage-mk2 script (wrangler deploy --env
site-stage-mk2). site-dev has no npm script yet -- deploy it directly with
npx wrangler deploy --env site-dev (see
Standing up a new dev host below).
The lint and test scripts (npm run lint, npm test) do not read docs/ and
are unaffected by the documentation package.
By hand vs CI¶
Every env can be deployed by hand with npx wrangler deploy --env <env> (or
the matching npm script). CI (.github/workflows/ci.yml) automates:
- Every push/PR to
masterorstagerunslint-test: lint, unit tests, and awrangler deploy --dry-runforsite-devandmedia-stageas a build sanity check. It never publishes anything. - A push to
stageadditionally runsdeploy-stage, which deployssite-dev(genericdev.*multi-tenant worker) andmedia-stage, authenticated with theCLOUDFLARE_API_TOKENsecret. Legacysite-stage/site-stage-mk2workers are retired from CI (see cleanup-legacy-workers.md). - A push to
masterrunsdeploy-prodinstead, deployingsite-prodandmedia-prodwith a separate secret,CLOUDFLARE_API_TOKEN_PROD. This is deliberate: the staging token can never touch the production domain, and untilCLOUDFLARE_API_TOKEN_PRODis configured in the repo, a push tomasterfails at that step instead of silently deploying prod.
Dev hosts used for verification today: dev.fashionradar.net (FR) and
dev.wantskicks.com (WK), both served by site-dev via host resolution.
Standing up a new dev host¶
site-dev is the pattern to copy when a new host needs to prove out (or
permanently run) host-based multi-site resolution rather than a
CMS_SITE_ID-pinned single site:
- Confirm the domain resolves to a site in cms-api --
resolveSitelooks it up asGET /public/v2/sites/{host}/settings, so the site must exist there under that exact host (or cms-api's domain-match equivalent) before the worker can serve it. - Add a new
[env.<name>]block inwrangler.tomlwith aroutesentry for the host. Usecustom_domain = true(assite-devandsite-stage-mk2do) when the domain is not already on a zone Wrangler manages by pattern -- it provisions the DNS record and TLS cert automatically. - Bind a
KVnamespace -- either a fresh one viawrangler kv:namespace create, or an existing namespace reused the waysite-devcurrently sharessite-stage-mk2's. - Set
CMS_API_BASE_URLin[env.<name>.vars]and do not setCMS_SITE_ID-- an absent override is what makes the env resolve by host. CopyPAGE_TYPE_TTLSfrom an existing env. - If the new env's account uses a token without
User Details:Read, pinaccount_idas the stage envs do. - Deploy by hand:
npx wrangler deploy --env <name>. Add it to CI only once it is meant to auto-deploy on every push, the waysite-stagedoes. - Enable Tiered Cache on the zone -- once per zone, not per host:
hq/.venv/bin/python hq/scripts/enable_zone_caching.py --zone <apex> --apply
Do this whenever a zone is brought online or transferred in. Each Cloudflare colo caches independently, and a colo holding no entry does not revalidate our documents -- it re-renders them through the worker, measured at 700-900ms. Tiered caching makes it fetch from an upper-tier colo instead.
It is easy to skip because the symptom hides: the site is fast from wherever you test it and slow from every colo you have not warmed, which is exactly where synthetic runs (PageSpeed, uptime checks) and first-in-region visitors land. The script is idempotent, so re-running it on a zone that already has it costs nothing.
The token in /common/cloudflare needs Zone -> Cache Settings -> Edit;
with purge-only rights the script reports FORBIDDEN and exits 3 rather
than appearing to succeed.
Required secrets¶
Secrets are never placed in the vars table or committed to source. They are
set per env with wrangler secret put <NAME> --env <env>:
| Secret | Used by | Purpose |
|---|---|---|
CMS_API_KEY |
site | Bearer token for the CMS public v2 API (cmsFetch). |
ADMIN_PURGE_SECRET |
site | Bearer token for POST /__cms/purge and the ?_preview= bypass. |
AWS_ACCESS_KEY_ID |
media | S3 credentials for media reads. |
AWS_SECRET_ACCESS_KEY |
media | S3 credentials for media reads. |
The KV namespace ids in wrangler.toml are environment-specific; create them
with wrangler kv:namespace create on first deploy and fill in the ids per env.
Cache purge: POST /__cms/purge¶
Purge clears cached pages and settings so a change becomes visible without
waiting out a TTL. The endpoint takes absolute priority in handleRequest (step
1) and bypasses every cache layer.
handlePurge (src/admin/purge.ts) requires POST and an
Authorization: Bearer <ADMIN_PURGE_SECRET> header, and host is always
required in the body. It accepts three body shapes.
Single URL¶
curl -X POST https://stg.wantskicks.com/__cms/purge \
-H "Authorization: Bearer $ADMIN_PURGE_SECRET" \
-H "content-type: application/json" \
-d '{"host": "stg.wantskicks.com", "url": "/some-article"}'
List of URLs¶
curl -X POST https://stg.wantskicks.com/__cms/purge \
-H "Authorization: Bearer $ADMIN_PURGE_SECRET" \
-H "content-type: application/json" \
-d '{"host": "stg.wantskicks.com", "urls": ["/a", "/b", "/c"]}'
A single url and a urls list are both routed to purge
(src/cache/index.ts), which deletes each (host, pathname) entry from both the
Cache API and KV. URLs are normalized to their pathname (query stripped) to match
the page cache key.
Hostname-scoped (site-wide)¶
curl -X POST https://stg.wantskicks.com/__cms/purge \
-H "Authorization: Bearer $ADMIN_PURGE_SECRET" \
-H "content-type: application/json" \
-d '{"host": "stg.wantskicks.com", "site": true}'
site: true routes to purgeSite (src/cache/index.ts), which clears the whole
host at once:
export async function purgeSite(host: string, env: SiteEnv): Promise<string[]> {
const prefix = `${host}:`;
const purged: string[] = [];
let cursor: string | undefined;
do {
const listing = await env.KV.list({ prefix, cursor });
for (const k of listing.keys) {
await env.KV.delete(k.name);
purged.push(k.name);
}
cursor = listing.list_complete ? undefined : listing.cursor;
} while (cursor);
await env.KV.delete(`site:${host}`);
purged.push(`site:${host}`);
// ... also deletes the site-settings Cache API entry
}
It enumerates every KV page entry under the <host>: prefix and deletes it, then
deletes the KV site-settings entry (site:<host>) and the Cache API
site-settings entry. KV is authoritative here; per-page Cache API entries are
best-effort because Cloudflare does not expose a list or tag API to a Worker for
deleting them in bulk.
Why hostname-scoped purge is needed to switch CSS site-wide¶
A rendered page has its stylesheet <link> baked into the cached HTML. When the
design changes (for example switching a site's template_style_id pairing or
bumping a style's S3 version), the future renders link the new stylesheet,
but every already-cached page keeps the old link until it expires. Purging a
single URL fixes only that page. The hostname-scoped site: true purge clears
every KV page for the host in one call. Note this purge is one step of the full
propagation recipe -- it clears KV but not the isolate memMap or the CF edge
cache; see Caching -> the propagation recipe
and Styles and CSS.
Health: POST-free /__cms/health¶
/__cms/health (handled in step 1, src/admin/health.ts) is the lightweight
liveness endpoint, also cache-bypassing. Use it for uptime checks; use the purge
endpoint for cache invalidation.