Hello.

article

One Astro build can run as a public and a gated preview Worker

2026-11-06 · Storyblok, Astro and Cloudflare Workers

TL;DR One Astro build can serve published pages and drafts from two Cloudflare Workers, given a different name and variable per deploy. Gate the drafts with Storyblok's signed token, not Cloudflare Access: the editor loads the preview in an iframe, and Access answers with a blank page. Check the gate with curl before sharing the URL.

Cloudflare Access in front of the draft preview looked like the obvious fix. Instead the Storyblok Visual Editor showed a blank "refused to connect" page. The editor loads the preview in an iframe, and the Access login page refuses to be framed.

One build serves two hostnames

Astro renders every page on demand inside a Cloudflare Worker (output: 'server', with @astrojs/cloudflare) and fetches content from the Storyblok Content Delivery API. blog-mikepenz-dev serves published content on blog.mikepenz.dev. blog-mikepenz-dev-preview serves drafts on preview.blog.mikepenz.dev.

Request path, production and preview

Requests the page. In the Visual Editor it is an iframe inside Storyblok.

1 / 5

The same code answers on both hosts. Only the variable, the hostname and the secrets differ.

Two config choices came from failures

@storyblok/astro v11 has no Astro integration to register. Components are registered with defineStoryblokBlocks in src/storyblok.ts, and the API client is @storyblok/api-client.

With trailingSlash: 'always', Astro answered the slashless form of a URL with a 404 before any middleware could redirect it. The old site's /a/<slug> redirected to /a/<slug>/, so the config uses 'ignore' and a middleware sends the 301.

import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
  output: 'server',
  adapter: cloudflare({ imageService: 'passthrough' }),
  build: { inlineStylesheets: 'never' }, // CSP: no inline <style>/<script>
  session: false, // no KV session binding
  trailingSlash: 'ignore',
  vite: { build: { assetsInlineLimit: 0 }, define: { __BUILD_ID__: JSON.stringify(Date.now().toString(36) + Math.random().toString(36).slice(2, 8)) } },
  site: 'https://blog.mikepenz.dev',
});

__BUILD_ID__ gives every build its own id, which the cache key in part 4 uses. Invocation logs are off because a fetch invocation log message is <Method> <URL>, and some URLs here carry secrets in the query string: the webhook ?key= and the preview token.

Each Worker holds only the secrets it needs

The site needs eight values. Six end up as Worker secrets, two only exist in the shell that deploys. Names only, never values:

Name

What it is

Where you create it

Lives on

STORYBLOK_TOKEN

Public access token, published content only

Storyblok: Space > Settings > Access Tokens, type Public

production Worker

STORYBLOK_PREVIEW_TOKEN

Preview access token, reads drafts

Same page, type Preview. Use a different token than the public one

preview Worker, local dev

STORYBLOK_REGION

eu, us and so on; the region of your space

Space settings

both Workers

WEBHOOK_SECRET

Authorizes the purge webhook (part 4)

openssl rand -hex 32

production Worker

CLOUDFLARE_ZONE_ID

The zone whose cache gets purged

Dashboard > your zone > Overview, right column

production Worker

CLOUDFLARE_PURGE_TOKEN

API token that can only purge cache

Dashboard > My Profile > API Tokens > Create, permission Zone > Cache Purge > Purge, resources: your one zone

production Worker

CLOUDFLARE_API_TOKEN

Deploy token for wrangler

Dashboard > API Tokens (below)

deploy shell only

CLOUDFLARE_ACCOUNT_ID

Account wrangler deploys to

Dashboard > Workers & Pages > Overview

deploy shell only

The production Worker holds no preview token, so it cannot read drafts, and the preview Worker holds no Cloudflare API token. The deploy token is the most valuable value in the table, because whoever holds it can overwrite the live Worker. It never becomes a Worker secret, and the purge token is a separate token.

I do not keep these in a .env or .dev.vars file. They live in a 1Password Environment named blog.mikepenz.dev, mounted as a local .env file that is a named pipe: 1Password serves the values to whoever reads it, and nothing sits on disk. The mount must stay outside the project, because with the pipe inside the bind-mounted folder my container build hung until I killed it. It is hygiene, not isolation: while 1Password is unlocked, any process of yours can read the pipe. I have not tried Windows, and the docs describe local .env files for Mac and Linux.

None of this needs 1Password. The code reads plain environment variables and Worker secrets, so a shell profile, direnv or your CI's secret store works.

wrangler's browser login cannot call back into a container, so deploys use an API token. The one I use is owned by the account and carries Workers Scripts edit, Zone read, Zone Settings edit and Cache Purge edit, and it does not touch DNS. Workers Scripts edit plus Zone read is probably the minimum, so start there and add permissions only when a deploy fails. To check a token without printing it, ask Cloudflare and print only the status:

bash
./c node -e 'fetch(`https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/tokens/verify`,{headers:{authorization:`Bearer ${process.env.CLOUDFLARE_API_TOKEN}`}}).then(r=>r.json()).then(j=>console.log(j.success,j.result?.status))'

That endpoint is for account-owned tokens. A token owned by your user verifies at /client/v4/user/tokens/verify, and mine returned 401 on that one.

The deploy script sets a secret with one helper. It reads the variable inside the container and pipes it straight into wrangler secret put, so the value never reaches the terminal or the shell history:

bash
put() { ./c sh -c "printf %s \"\$$1\" | npx wrangler secret put $1 --name $2"; }
put STORYBLOK_PREVIEW_TOKEN blog-mikepenz-dev-preview

One deploy script ships both Workers

The adapter writes dist/server/wrangler.json without env blocks, so one config cannot describe production and preview. scripts/deploy.sh deploys the same build twice instead, with a different --name and --var STORYBLOK_PREVIEW. Step through it in order:

Step 1 of 4

Build once

./c npx astro build produces one dist/. ./c is the container wrapper from the next section.

A dry run shows what the preview Worker uploads (module table cut at ...):

wrangler deploy --dry-run, preview Worker (trimmed)
$ ./c npx wrangler deploy --dry-run --name blog-mikepenz-dev-preview --var STORYBLOK_PREVIEW:1
⛅️ wrangler 4.158.0
Using redirected Wrangler configuration.
 - Configuration being used: "dist/server/wrangler.json"
 - Original user's configuration: "wrangler.jsonc"
 - Deploy configuration file: ".wrangler/deploy/config.json"
Attaching additional modules:
...
│ Total (23 modules)                                        │      │ 2933.89 KiB │
✨ Read 22 files from the assets directory /app/dist/client
Total Upload: 2970.20 KiB / gzip: 499.34 KiB
env.ASSETS                              Assets                    
env.STORYBLOK_PREVIEW ("(hidden)")      Environment Variable      
--dry-run: exiting now.

I attached both custom domains once in the Cloudflare dashboard, and I run every deploy myself. The domains survive redeploys because the script passes no --domain.

Every JavaScript command runs in a container

There is no Node on my host. Every JavaScript command goes through ./c, a short wrapper around Apple's container CLI:

bash
exec container run --rm $T -v "$PWD":/app -w /app -m 4G -p 4321:4321 -p 8787:8787 -v /etc/ssl/cert.pem:/etc/ssl/cert.pem:ro -e SSL_CERT_FILE=/etc/ssl/cert.pem $E blog-node "$@"

$T is -it only when stdin is a terminal, so scripts work too. $E passes the secrets from the 1Password Environment, so the container only sees environment variables. blog-node is built from node:26-slim.

Cloudflare Access cannot front the Visual Editor

The preview host serves drafts, and it was public. Nothing linked to it, but noindex is not access control.

The first fix was a Worker-level Cloudflare Access policy, which covers routes, Custom Domains and workers.dev. After a few minutes every path returned a 302 to the Access login, and the Visual Editor broke: Chrome showed a blank "refused to connect" page. The login page sends x-frame-options: DENY and frame-ancestors 'none', so it cannot render in the editor's iframe. The Worker never runs for that request, so it cannot change the headers.

No Access variant helps. Policy selectors cannot match a query parameter, so a bypass would expose whole paths. Service tokens need request headers, which an iframe cannot add. Logging in first in a normal tab leaves the Access cookie third-party inside the iframe, which Safari blocks and Firefox partitions in its strict and private modes (CHIPS).

Storyblok's signed token is the gate

Storyblok already answers "did this request come from my editor?". The Visual Editor appends _storyblok_tk[space_id], [timestamp] and [token] to the preview URL. Per the Visual Editor docs, the token is the SHA-1 of space_id:preview_token:timestamp, valid when it matches and the timestamp is less than an hour old, checked on the server. I removed Access from the preview Worker, and the gate runs in its middleware, right after the security headers:

typescript
export async function tkValid(url: URL, o: GateConfig): Promise<boolean> {
  const p = url.searchParams;
  const sid = p.get('_storyblok_tk[space_id]'), ts = p.get('_storyblok_tk[timestamp]'), tok = p.get('_storyblok_tk[token]');
  if (!o.spaceId || !o.tokens.length || !sid || !ts || !tok || sid !== o.spaceId || !/^\d{1,12}$/.test(ts)) return false;
  const t = Number(ts);
  if (t <= o.now - TK_MAX_AGE || t > o.now + TK_FUTURE_SKEW) return false;
  let ok = false;
  for (const pt of o.tokens) ok = same(await sha1(`${sid}:${pt}:${ts}`), tok.toLowerCase()) || ok; // no early exit
  return ok;
}

A unit test (56 cases) and an integration test against the built Worker (46 cases, scripts/test-preview-gate-live.mjs) run in the container with a fake token. The integration script asserts that denied requests make no Storyblok connection. A request without credentials, headers trimmed:

unauthenticated request to the preview host (trimmed)
$ curl -sI https://preview.blog.mikepenz.dev/
HTTP/2 403
content-type: text/plain; charset=utf-8
cache-control: no-store
vary: Cookie
x-robots-tag: noindex, nofollow
content-security-policy: default-src 'self'; ...; frame-ancestors https://app.storyblok.com
server: cloudflare

There is no redirect, and frame-ancestors allows only Storyblok's editor. With the gate in place, the Visual Editor loads the preview with live updates.

On the first try the editor showed "preview requires the Storyblok editor". The space had two preview tokens and the wrong one was configured. The hash did not match, so the gate refused instead of showing a draft.

A git add also once picked up a file named .dev.vars. (trailing dot) that held all the secrets. It was never committed, but the old .gitignore did not cover it, so it ignores .dev.vars* except the example file.

Try it yourself

Create the values from the secrets table, store them in your secret manager, and deploy the same build twice. Set each secret on its Worker with wrangler secret put as shown above:

bash
./c npx astro build
./c npx wrangler deploy --name <project>-preview --var STORYBLOK_PREVIEW:1
./c npx wrangler deploy --name <project> --var STORYBLOK_PREVIEW:0
curl -sI https://<preview-host>/

The last command should return HTTP/2 403. Requirements: Astro with @astrojs/cloudflare, a Storyblok space with a public and a preview token, a Cloudflare account, and a container runtime if you want no Node on the host (replace ./c with npx otherwise).

Good to know

Run curl -sI against your preview host from a clean shell before you share its URL with anyone.