Deployment
Deploy CMS to production with Docker, migrations, health checks, and runtime configuration.
CMS is a framework, not a deployable app. You ship a consumer project — your cms.config.ts, a package.json that depends on @cms/engine, your committed migrations, and a Dockerfile. In production the engine runs with cms start, serving the API and (optionally) the admin SPA on a single port.
This guide covers the engine itself. Storage, CORS, and email are configured in your cms.config.ts from whatever environment variables you choose. Only cms start and cms dev check that the ones the server needs are set — see Runtime variables in cms.config.
Docker
A minimal reference Dockerfile to drop next to your cms.config.ts:
FROM node:24-alpine
WORKDIR /app
RUN npm install -g pnpm # switches to the version in package.json's packageManager
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
COPY . .
RUN pnpm cms build # builds the admin SPA to .cms/admin-dist/
EXPOSE 4000
CMD ["pnpm", "cms", "start"]
Build and run:
docker build -t my-cms .
docker run -p 4000:4000 --env-file .env my-cms
A few rules:
- Use
--frozen-lockfileso the build fails fast ifpackage.jsonand the lockfile have drifted. - Don’t apply migrations on container startup —
cms startnever does. Runcms migration applyas a separate pre-deploy step (see Database migrations). - For headless instances, set
ADMIN_UI=false.cms buildbecomes a no-op and the admin SPA is never mounted, so the same image serves an API-only deployment without code changes. - The admin’s hashed files under
/admin/_assets/are sent withCache-Control: public, max-age=31536000, immutable, and every admin page withno-store, so the next load after a deploy, a restored tab included, always starts the new build. A missing asset is a404. A CDN in front of the engine should keep these headers.
Smaller production images
The minimal image above ships the full dependency tree, including build tooling. To trim it, build the admin SPA in a throwaway stage, then run a fresh pnpm install --prod in the runtime stage so only production dependencies remain. Two things to keep in mind:
tsxand every@cms/*package must be runtimedependencies, notdevDependencies. The engine compilescms.config.tson boot through tsx, and the config imports the@cms/*packages, so--prodhas to keep them all.- Never
COPYnode_modulesbetween stages. pnpm lays outnode_modulesas a symlink farm over a virtual store, and the engine’s config loader depends on that exact layout. A cross-stage copy breaks it, and config load fails withERR_MODULE_NOT_FOUND. Always let each stage build its own tree with a nativepnpm install.
Copy only what the runtime needs: the built admin (/app/.cms), your config and its source, your migrations, and the tsconfig.json tsx uses for path resolution. Keep custom admin components self-contained so the image never has to ship frontend code.
Run dumb-init (or tini) as PID 1 so docker stop’s SIGTERM reaches the engine and it drains cleanly:
RUN apk add --no-cache dumb-init
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "node_modules/@cms/engine/bin/cms.js", "start"]
Environment variables
These are read by the engine itself:
| Variable | Default | Description |
|---|---|---|
DATABASE_URL |
— | Postgres connection string. Required. |
CMS_SECRET |
— | At least 32 characters; generate one with openssl rand -base64 32. Required: cms dev and cms start refuse to boot without it. Keys what a read of the database alone mustn’t reveal (login codes). Read from the environment only, never from cms.config, which is bundled into the admin. Changing it invalidates login codes sent in the last 5 minutes, nothing else. |
PORT |
4000 |
HTTP listen port. |
NODE_ENV |
— | Set to production to enable secure cookies and JSON logs. |
ADMIN_UI |
true |
Set to false (or 0/off/no) to run headless. |
CMS_CONFIG_PATH |
auto-detected | Path to your config file. Override only if it isn’t at cwd/cms.config.ts (or .tsx). |
CMS_SEED_ADMIN_EMAIL |
admin@cms.local |
Email for the first admin, seeded on boot only when the _user table is empty. Auth is OTP-only — no password. |
LOG_LEVEL |
info |
Pino log level (debug, info, warn, error). |
MIGRATIONS_PATH |
./migrations |
Directory holding committed migration files. |
CMS_REMOTE_IP_HEADER |
unset | Header to trust for the client IP (e.g. x-forwarded-for), used by the rate limiter. Only set this if every request actually passes through a proxy that sets it — otherwise clients can spoof their own IP. Unset means the raw socket address is used. |
Everything else is consumer configuration. Storage credentials, CORS origins, and email settings are fields on the object you pass to config({ … }), typically read from process.env:
// cms.config.ts — s3() is imported from @cms/storage-s3, requiredEnv() from @cms/config
storage: s3({
bucket: process.env.S3_BUCKET,
region: process.env.S3_REGION,
// Credentials are optional — prefer leaving them unset so the deployment's
// own identity is used. See Storage credentials below.
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
endpoint: process.env.S3_ENDPOINT, // optional — MinIO / custom S3
}),
cors: {
origins: requiredEnv("CORS_ORIGINS").split(",").filter(Boolean),
},
Name these variables whatever you like.
Runtime variables in cms.config
Every command evaluates cms.config — cms build, cms migration generate, cms user create,
cms key create — and so does the admin bundle in the browser, where process.env is empty. Only
cms start and cms dev need the runtime values, so only they check them:
- Provider options check themselves.
s3(),ses()andsmtp()reject a missing or empty required option (bucket,region,from,hostname…) when the server boots, so passprocess.env.Xas is. The build never creates a provider, so it never needs these variables. - Anything else the server can’t run without — like the CORS origins above — reads through
requiredEnv("NAME")from@cms/config. It returns the value, or""when it’s unset, and never throws;cms startandcms devthen refuse to boot while any is unset. - Optional values stay plain
process.envreads.
A missing value fails the boot once, naming everything at the same time:
The server can't start: its configuration is incomplete.
- requiredEnv(): CORS_ORIGINS unset or empty
- storage: s3: bucket and region are required and must not be empty — check the environment variables it reads.
- email: smtp: from is required and must not be empty — check the environment variables it reads.
Don’t throw on a missing variable in cms.config itself, with ensureEnv or a helper of your own:
that fails cms build and CI, where nothing needs the value. If it happens, the build error says
so — the fix is requiredEnv(), never a placeholder value in the build environment.
Storage credentials
Prefer workload identity over static keys. A long-lived access key/secret pair is a shared secret: it has to be distributed to every environment, it sits in a secret store or CI variable indefinitely, and rotating it is a manual, coordinated change. Treat static keys as the exception, not the default.
Leave S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY unset. With both credential fields
absent, the SDK resolves credentials from the environment instead — the deployment
itself is authorized to reach the bucket, and no secret ships with it:
| Environment | Mechanism |
|---|---|
| EC2 | Instance role via IMDSv2 |
| ECS / Fargate | Task role via the container credentials endpoint |
| EKS | Service account via IRSA (OIDC web identity) |
| GKE, AKS, other Kubernetes | Service account federated into an AWS role via OIDC (AWS_ROLE_ARN + AWS_WEB_IDENTITY_TOKEN_FILE) |
| GitHub Actions and similar CI | OIDC job token exchanged for an AWS role |
| Local development | aws sso login, or AWS_PROFILE against the shared config file |
Every row resolves to short-lived, automatically rotated credentials. The last three matter outside AWS too: any platform that issues an OIDC token for a workload can federate into a role, so a non-AWS host still avoids a stored secret.
Grant the role s3:PutObject, s3:GetObject, and s3:DeleteObject on
arn:aws:s3:::<bucket>/*. The startup log line reports which mode is active:
Storage: s3 (credentials: default chain) or (credentials: static).
Setting only one of the two credential fields is treated as a misconfiguration and the process exits at boot rather than failing on the first upload.
When static keys are unavoidable
Object stores that aren’t AWS S3 — MinIO, Cloudflare R2, Backblaze B2 — implement the
S3 API but not its credential chain, so they require a key pair. Scope it to the one
bucket, keep it in a secret manager rather than a .env file committed anywhere, and
give it a rotation schedule.
Email credentials
Email follows the same rule. ses() from @cms/email-ses sends through the Amazon SES
API, and its accessKeyId/secretAccessKey are optional — omit both and credentials
resolve from the environment exactly as the table above describes:
// cms.config.ts — ses() is imported from @cms/email-ses
email: {
provider: ses({
from: process.env.EMAIL_SENDER,
region: process.env.AWS_SES_REGION,
}),
},
Grant the role ses:SendEmail, and verify the sending domain or address in that region.
The startup log reports the mode: Email: ses (eu-west-1, credentials: default chain).
The alternative, smtp() from @cms/email-smtp, normally needs a username and password —
SES SMTP credentials are themselves a long-lived IAM key pair, which is the thing the SES
API provider exists to avoid. Prefer ses() when sending through SES. Omit username and
password together to connect without authenticating, as a local mail catcher expects.
encryption decides how the connection is protected: "full-tls" (the default, port 465) is TLS
from the first byte, "starttls" (587) opens plaintext and makes the upgrade mandatory, and
"plaintext-insecure" (1025) is unencrypted — only for a local catcher with no cert. There is no
opportunistic mode, so the connection is never unencrypted because a negotiation failed.
Failures land at four distinct points. Invalid options — an empty from or hostname, an unknown
encryption, a port that isn’t a whole number in the TCP range — throw while the provider is
created, so the server fails to start rather than running undeliverable. The startup connection
check is best-effort: a failure is logged and the server keeps running. A login-code delivery
failure is returned to the caller as an error, because a success response with no email leaves the
editor waiting on the code screen forever. A ctx.email send rejects to its caller, which decides:
from an after-hook, the hook runner logs and reports it, and the write it follows stands.
Pass the options straight from process.env, as above: the provider checks them when the server
boots (see Runtime variables in cms.config). A helper that throws
on a missing variable would break cms build and the admin bundle, which evaluate the config without
the server’s environment.
Database migrations
cms start never auto-runs migrations. Treat applying them as an explicit operator step: generate locally, commit the SQL, then apply as a pre-deploy job before the new code rolls out.
cms migration generate add_excerpt # locally — review and commit the SQL
cms migration apply # in CI/deploy, against the production DB
cms start checks before it writes anything. It exits with Database unreachable if Postgres can’t be reached, and refuses to start while any migration in its migrations/ directory is pending, was left half-applied by a crashed apply, or was edited after it was applied — the error names the migrations and the command to run. Migrations the database has but the build doesn’t (a rollback to an older image) only log a warning, so the previous version keeps serving. A build without a migrations/ directory skips the check.
Run apply as a release step that finishes before any new instance starts: Fly’s release_command, a Kubernetes Job or init stage, or your platform’s equivalent. A failed migration then stops the release while the previous version keeps serving traffic. Chaining it into the entrypoint (cms migration apply && cms start) applies it at boot instead: the new instance has already replaced the old one when the migration fails, and several replicas booting together race to apply it. apply is idempotent and takes an advisory lock, so a race doesn’t double-apply, but it still turns a failed migration into an outage.
If an apply crashes partway through a -- migrate:no-transaction migration, it’s left recorded as started and every later apply and cms start refuses to run until you resolve it; see cms migration resolve. A diff that drops a table or column needs --accept-data-loss at generate time; see the CLI reference. The flag doesn’t cover a new required field on an entity that already has rows: give it a defaultValue, or add it as optional, backfill, and make it required in a later migration; see Adding a required field.
Migrations that change existing rows
A migration that transforms rows already in the database (a backfill, a value rewrite, a JSON reshape) is the one kind the empty development database can’t test. An UPDATE … WHERE that matches nothing never runs its SET, so a wrong expression applies cleanly against empty tables and only fails, or writes wrong values, in production. Before shipping one, apply it to a scratch database seeded with rows in the shape they have before the migration (a restored production dump, or rows you insert by hand), then read the rows back and check them.
Useful CI checks:
cms migration generate --check # PR-time: fails if a config change has no committed migration
cms migration check-drift # pre-deploy: fails if the live DB was ALTERed out of band
cms migration status # show which migrations are applied/pending (read-only)
Health checks
The engine exposes these out of the box:
| Endpoint | What it checks |
|---|---|
GET /api/health |
Process is up. |
GET /healthz |
Process is up. |
GET /healthz/version |
Returns APP_VERSION, or unknown if unset. |
GET /healthz/db |
Postgres is reachable. |
GET /healthz/admin |
The admin SPA asset is present. |
Each returns 200 OK (plain text) on success, or 503 Service Unreachable when the check fails. The body carries no further detail by design — a health check is a single up/down signal, not a diagnostics endpoint.
Point the platform’s liveness check (the one that restarts or stops routing to an instance) at GET /healthz. It answers as long as the process is up and never touches the database. A check on /healthz/db would fail on every instance at once during a database blip, and the platform would restart or take out the whole CMS when the database is all that needs to recover.
Use GET /healthz/db as the readiness gate in your deploy pipeline — it confirms the database is reachable before you move on, for example before deploying the frontend. Since cms start refuses to boot with pending migrations, an instance that answers at all is serving a migrated database. Configure checks in your platform’s deployment config, not the Dockerfile.
Graceful shutdown
The engine handles SIGTERM and SIGINT. In-flight requests drain, then the database pool closes, with a 5-second forced-exit timeout as a backstop. Set your platform’s kill timeout to at least that (e.g. kill_timeout = '10s') so drains complete cleanly.
Database timeouts
cms start and cms dev bound how long the server waits on Postgres, so one slow path can’t stall every request behind it:
| Option | Default | Effect |
|---|---|---|
connectionTimeoutMs |
10000 |
A request that can’t get a pooled connection in time fails with 503 SERVICE_UNAVAILABLE. A positive integer |
statementTimeoutMs |
30000 |
Postgres cancels a query that runs longer. An integer of at least 0; 0 disables it |
Both are optional, and an invalid value throws when the config loads. Set only the one you change, for example a project with long-running reports:
export default config({
// ...
database: { statementTimeoutMs: 120_000 },
});
CLI commands such as cms migration apply don’t use these; migrations set their own statement timeout.
Runtime configuration
Custom admin components sometimes need values that rotate without a rebuild — an API base URL, a public key, a feature flag. Build-time env (VITE_*) bakes these into the bundle, so changing one means rebuilding.
Instead, the engine exposes any process.env variable prefixed CMS_PUBLIC_ to the admin SPA at runtime, served from GET /admin/runtime-env.js with Cache-Control: no-store. A process restart is enough to pick up a new value. Read them with the @cms/client helpers:
import { env, ensureEnv } from "@cms/client";
const apiUrl = ensureEnv("CMS_PUBLIC_API_URL", "url"); // throws if missing/invalid
const flag = env("CMS_PUBLIC_BETA_BANNER"); // string | undefined
The prefix is never stripped, so the same name resolves identically in the browser and on the server. Only prefixed variables are exposed — secrets without the prefix stay server-side. Override the prefix with admin.publicEnvPrefix in cms.config.ts if you want to reuse an existing convention. A prefix that CMS_SECRET starts with (CMS_, CMS, …) is refused at boot, since it would serve the server secret to anyone; CMS_SECRET is never served whatever the prefix.
These helpers are for admin code that runs when a page loads, like a custom field input. In
cms.config itself, ensureEnv throws during cms build; read required values there with
requiredEnv().
A prefixed variable must be set on the CMS instance that runs the admin, not just on your frontend service. It’s a common mistake to set such a value on the frontend and forget the CMS — the component then fails because
ensureEnvthrows on the missing value.
Error monitoring (Sentry)
Install @cms/sentry and register it as a plugin; the engine and the admin
then report to Sentry. Core ships no Sentry SDK, so a project without the plugin loads none.
import { sentry } from "@cms/sentry";
export default config({
// ...
plugins: [
sentry({
dsn: process.env.SENTRY_DSN,
environment: process.env.APP_ENV,
release: process.env.APP_VERSION,
sourceMaps: { org: "my-org", project: "my-project" },
}),
],
});
cms.config is bundled into the admin, which has no process.env: options read from it are
undefined there, and the engine hands the admin the DSN, environment and release at runtime
through /admin/runtime-env.js. A literal option value would ship in the admin bundle, so read
them from process.env as above. None of them is a secret — the source-map upload reads
SENTRY_AUTH_TOKEN from the build environment, never from an option.
When it reports. cms start reports to dsn. cms dev never reports to Sentry; set
SENTRY_SPOTLIGHT=true to send server and admin events to a local
Spotlight sidecar instead.
Issues (defects):
- Unhandled request errors and 5xx errors, including anything a
before*hook or custom route throws that isn’t aHookError. after*hooks and fieldafterWritehooks that fail — the write committed, so nothing else would surface them.- Unhandled rejections, uncaught exceptions, and boot failures after
cms.configloaded. - In the admin: a page that fails to load or render (it now shows an error screen with the request id), and failed queries or mutations — except 4xx answers the editor already sees.
Logs. Every engine warn and error log line goes to Sentry Logs: email delivery failures,
image-transform fallbacks, thrown 4xx errors. The per-request access line is info for a 4xx
(a client asking about something missing is not a fault) and error for a 5xx. Only the message, the error’s name and code (never its
message — a driver error can echo a connection string), and a fixed set of fields (requestId,
method, path, status, ms, code, entity, hook, plugin) are sent. Addresses and credentials
in URLs are redacted from any text that leaves.
Not reported. HookErrors — they’re answers for the editor, not defects.
Context and privacy. Every event and log line carries service: cms, so a project shared with
a storefront can filter them. Events that come from a request also carry its request_id — the
same id on the admin error and the server event it came from — and share one trace derived from
it. Boot and process-level failures have no request, so they have neither. Editors are identified
by id, with the role as a tag; never email or name. Request bodies, headers, cookies and query
strings are never sent.
No performance tracing. The SDK starts after cms.config loads, too late to instrument the
engine’s own modules, so there are errors and logs but no timed spans.
Admin source maps. When sourceMaps.org and sourceMaps.project are set and SENTRY_AUTH_TOKEN is in the
environment of cms build, the admin bundle is built with hidden source maps, uploaded, and the
maps deleted before the image ships. A failed upload fails the build. Pass the token as a Docker
build secret, not a build arg:
RUN --mount=type=secret,id=SENTRY_AUTH_TOKEN \
SENTRY_AUTH_TOKEN="$(cat /run/secrets/SENTRY_AUTH_TOKEN 2>/dev/null || true)" \
node node_modules/@cms/engine/bin/cms.js build
Production checklist
NODE_ENV=productionandDATABASE_URLpointed at the production database.CMS_SECRETset to a value of its own (openssl rand -base64 32), never a local or example one.CMS_SEED_ADMIN_EMAILset to a real email (or create accounts later withcms user create <email>).- Migrations generated, committed, and applied as a pre-deploy step.
- Durable asset storage:
s3()from@cms/storage-s3, orlocalDisk()on a mounted volume for a single instance. A container’s own disk is wiped on every deploy;cms startlogs a warning whenever it runslocalDisk()withNODE_ENV=production; on a mounted volume, that warning is expected. - An email provider (
smtp()orses()). Without one, login codes are only printed to the server log, andcms startwarns about it in production. - A reverse proxy or platform TLS in front. The built-in rate limiter is in-memory and per-process; for multi-instance deployments, put rate limiting at the edge.
- For API-only instances, set
ADMIN_UI=false.
Behind a separate frontend
Many projects run two services: the CMS engine and a separate frontend (Astro, TanStack Start, Next.js, …) that reads from the API.
- Deployment order. Deploy the engine first and wait for
GET /healthz/db→200 OKbefore deploying the frontend, so the frontend never boots against an unreachable or unmigrated database. - CORS. Add the frontend’s production origin to your engine’s
cors.originsbefore going live. - Server-side reads on Fly.io. When the frontend’s server calls the engine over Fly’s private network, use
http://<app>.internal:<port>, not<app>.flycast. Flycast goes through Fly’s proxy, so withforce_https = trueits plain-HTTP requests are redirected to HTTPS and the read fails. - Frontend runtime config. The frontend has the same rebuild-free-rotation need as the admin. Have its server read
process.envat request time and hand the values to the browser instead of baking them in — for example, a small route that returns a JS snippet assigningwindow.__ENV, loaded in the document<head>before other scripts.
CDN caching
By default every API read answers without Cache-Control, so a CDN in front of the engine passes every read through. Two config keys change that, both off by default:
export default config({
// …
cacheTags: { prefix: "site:" }, // or `true` for no prefix
apiCache: { sMaxAge: 60, staleWhileRevalidate: 300 },
});
What gets cached
With apiCache, a read a CDN may share answers Cache-Control: public, max-age=0, s-maxage=<sMaxAge>. Browsers keep nothing (max-age=0), so only the CDN holds content. With staleWhileRevalidate, the read also answers CDN-Cache-Control: public, max-age=<sMaxAge>, stale-while-revalidate=<n>: Cloudflare reads it instead of Cache-Control, and browsers never see the stale window, so they can’t serve a read a purge evicted. A read is shared only when all of these hold:
- it is a
GETof an entity document, an entity list orfind, a global, or/api/search; - it succeeded (2xx);
- it carries no credentials: no
Authorizationheader and no session cookie, so it runs under the public role; - it is not a draft read (
?draft=true).
Every other API read answers private, no-store: reads with an API key (whatever its role) or a session, draft reads, errors, /api/health, and the auth, API key, referrer, version, custom and plugin routes. A custom or plugin route’s own Cache-Control is replaced too, so a route can’t make a caller-specific answer shareable, and its CDN-Cache-Control and Cloudflare-CDN-Cache-Control are removed, since Cloudflare would obey them over Cache-Control. A response with no Cache-Control is storable by default, so stating it keeps every cache in the path (a CDN with a default TTL, a reverse proxy, a browser) from storing a caller-specific answer, whatever its rules. Writes are untouched, and asset files keep their own headers (see Assets).
apiCache needs cacheTags.
Cache tags
With cacheTags, every successful published read carries a Cache-Tag header, under any role, API keys and sessions included. Tags say what a response holds; they never make it shareable, and Cache-Control is unchanged without apiCache. Draft reads and errors carry none.
| Tag | Means |
|---|---|
<prefix>e:<entity> |
The response reads this entity or global (a list, a find, a document, or a search that covered it), resolves into it, or filters or sorts through a relation into it (filter[author.name]=Ana, or a role’s permission filter that does), even when the role saw none of its documents: publishing one changes the response. Every document the response holds or references also tags its entity, so a value that drops the d: tags still covers it. An empty list or find (a 200 with no documents) carries only these entity tags. |
<prefix>d:<id> |
This document is in the response: a top-level one, a translation in _translations, a resolved one, or one only referenced as { id, _entity }. |
Purge d:<id> when a document changes, and e:<entity> when a list of it may change: create, publish, unpublish, delete, and every update of an entity without drafts (an update can move a document into a filtered list). A delete also purges e:<entity> for every entity and global with a relation to the deleted one’s entity, nested in objects, arrays, unions or rich text included: the delete nulls or drops their references without an update of their own, and that can change a list that never held the deleted document (filter[author][$exists]=false). The engine keeps the header under 8 KB, about 200 document tags, so a Node client (whose whole header block is capped at 16 KB) can still read it; past that a response carries only its e: tags, which name every entity its documents belong to. The scheme is stable, so a purge for any CDN can be written against it. Use a prefix when two projects share one CDN zone. The CMS refuses to boot with a prefix so long that the e: tags of all entities together pass 8 KB, so the e: tags always fit.
Tags on API-key reads can name documents the public role can’t read. Cloudflare strips Cache-Tag before it answers visitors; on a CDN that doesn’t, those ids reach the page’s visitors. Give the site’s server a key with no more access than the site needs.
Tagging the site’s pages
A site’s server reads with an API key over its own network, so its reads never pass through the CDN. What the CDN caches is the site’s pages. Set the tags of every read a page made on its HTML response, served from the same CDN zone with the same prefix, and the purge that evicts a document’s API reads evicts every page that shows it too. A page can then be cached for hours. Every page reads the globals (navigation, footer, settings), so saving one evicts them all.
@cms/client/server gathers the tags per incoming request. In TanStack Start, a request middleware scopes each request and sets the header:
// src/start.ts
import { createMiddleware, createStart } from "@tanstack/react-start";
import { pageTags } from "./lib/cms"; // createTagCollector(), passed to the client's onRequest
const cacheTags = createMiddleware({ type: "request" }).server(({ next }) =>
pageTags.run(async () => {
const result = await next();
const header = pageTags.header();
// No value fits under 8 KB without losing a dependency: don't let the CDN keep this page.
if (header === undefined) result.response.headers.set("Cache-Control", "private, no-store");
else if (header) result.response.headers.set("Cache-Tag", header);
return result;
}),
);
export const startInstance = createStart(() => ({ requestMiddleware: [cacheTags] }));
header() is undefined when even the entity tags and your own pass 8 KB: no shorter value covers every change that should evict the page, so the page goes uncached instead. Remove any CDN-Cache-Control the page sets there too, since Cloudflare obeys it over Cache-Control.
Only reads finished before the response’s headers go out count: load a page’s content in its route loaders, not in components that stream in later. A cache you keep in front of the client must replay the tags of the reads it answers (see Page cache tags). A 404 from a find that matched nothing still carries the entity’s tag, so publishing a document of that entity evicts it.
Cloudflare setup
Cloudflare doesn’t cache JSON by default. Add a Cache Rule for the CMS hostname:
- When:
http.host eq "cms.example.com" and starts_with(http.request.uri.path, "/api/") and not any(lower(http.request.headers.names[*])[*] == "authorization") and not http.cookie contains "cms_session=" - Then: Eligible for cache; Edge TTL: Use cache-control header if present, bypass cache if not; Browser TTL: Respect origin.
The cache key is the URL. Keep the Authorization and cookie conditions: Cloudflare can answer a request that carries an Authorization header from a copy it cached for an anonymous one, so an API-key caller would get the public role’s content. For the same reason, read published content from the browser without an API key: grant the public role read on what the site needs. Reads with a key answer private, no-store, so they are never stored.
Cloudflare ignores Vary: Origin, so with cors on, a read it may cache answers Access-Control-Allow-Origin: *, with no Access-Control-Allow-Credentials and no Vary: Origin. An echoed origin would otherwise be served to every other origin, and a copy filled by a request without Origin (a bot, the site’s server) would carry none. Browsers refuse * on a credentialed request, so make those reads without credentials: "include". Every other read keeps the per-origin answer.
Choosing the window
Without a purge, a publish can take sMaxAge to show, plus staleWhileRevalidate: during that second window the CDN still answers with the old read while it fetches the new one. With { sMaxAge: 60, staleWhileRevalidate: 300 }, the first visitor after 6 minutes can still see content up to 6 minutes old. Keep both short (60 seconds already takes repeated reads off the CMS); a stale window refreshes in the background instead of making a visitor wait.
With @cms/cloudflare, each publish purges the reads (and tagged pages) that hold what changed, so the window can be hours: freshness comes from the purge, and the window only bounds how long a missed purge (a Cloudflare outage) can last. On a live site, raising sMaxAge from 60 to 3600 once the purge was proven kept a publish showing in about 1.5 seconds.
The window still bounds whatever changes without a write to the CMS, because nothing purges it:
- Content that goes live by date, such as a
publishAtfield the site filters on, shows withinsMaxAgeof that date. - Data the site’s pages read from elsewhere (a commerce platform, another API) shows within the page’s own window. That window is set by the site, not by
apiCache, so it can stay short (5 minutes, say) while the API reads live for an hour.
Example: Fly.io
A fly.toml for the engine. release_command applies migrations in an ephemeral VM before the new version goes live; a failed migration blocks the deploy while the old version keeps serving.
app = 'my-cms-engine'
primary_region = 'cdg'
kill_signal = 'SIGTERM'
kill_timeout = '10s'
[deploy]
strategy = 'canary'
release_command = 'pnpm exec cms migration apply'
[http_service]
internal_port = 4000
force_https = true
[[http_service.checks]]
grace_period = '20s'
interval = '10s'
timeout = '5s'
method = 'GET'
path = '/healthz'
Create the app, set secrets, and deploy:
fly apps create my-cms-engine
fly secrets set \
DATABASE_URL="postgres://…" \
CMS_SECRET="$(openssl rand -base64 32)" \
CMS_SEED_ADMIN_EMAIL="admin@example.com" \
CORS_ORIGINS="https://my-frontend.example.com" \
--app my-cms-engine
fly deploy
Further reference
The examples/ecommerce project carries a complete two-service setup — engine plus frontend — including the full multi-stage Dockerfile that applies everything above.
Previous
Live preview
Next
Overview