okayus/okayus-skills/cloudflare-workers-e2e-playwright

Claude Code and agent skill by okayus/okayus-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Wire Playwright e2e tests against a Cloudflare Workers app (Hono + Vite + @cloudflare/vite-plugin) by running the built Worker with `wrangler dev`. Use when React never mounts under a strict CSP (the Vite HMR inline preamble), when the Worker under test reads an empty D1 (the `wrangler dev --config` state path), when e2e vars are silently overridden by the `.dev.vars` copy the vite plugin writes into dist, when `wrangler dev` answers with `500 Network connection lost` and exits, or when testing passkey login with a WebAuthn virtual authenticator or third-party OAuth with a seeded session instead of a dev-bypass route. Keeps the suite to three specs. For running it inside a Docker sandbox see playwright-e2e-in-docker-sandbox.

Install

npx vskill@latest install okayus/okayus-skills/cloudflare-workers-e2e-playwright

SKILL.md

The same SKILL.md was published earlier as okayus/okayus-skills/cloudflare-workers-e2e-playwright.

Cloudflare Workers + Playwright e2e (without the two silent traps)

The two traps in one sentence: pointing Playwright at pnpm dev (Vite) makes Vite's HMR inline preamble collide with your strict CSP and prevents React from mounting on any non-/ path; switching to wrangler dev --config dist/.../wrangler.json then makes the Worker query a different empty D1 sqlite (silently, no migrations) unless you pass --persist-to .wrangler/state.

This skill exists because the author burned several hours debugging both traps in sequence on a single Phase 9 PR. Each trap looks like a different bug — CSP says "inline script blocked", D1 says "no such table: users" — but the root cause for both is the same: the dev-mode plumbing that's convenient for interactive iteration silently diverges from production semantics, and e2e is exactly where that divergence shows up.

When to use this skill

  • You're adding Playwright e2e to a Cloudflare Workers + Vite + React project
  • Your app has a strict script-src 'self' CSP applied via Hono middleware (secureHeaders)
  • You're seeing one or more of:
  • Executing inline script violates Content Security Policy in the browser console after page.reload()
  • D1_ERROR: no such table: users when register / login hits the DB during e2e
  • Tests that pass against vite dev but fail in CI / production-like environments
  • WebAuthn / passkey flows that you want to automate without bypassing them
  • Your auth is third-party OAuth (Google / GitHub) and you can't see how to e2e it without shipping a login bypass — there's no virtual authenticator for OAuth (see the seeded-session seam below)
  • You develop in a network-isolated Docker sandbox (egress firewall, no host browser, no Cloudflare login) and want the suite to run fully in-container
  • You want to scope e2e narrowly per the "configuration not exhaustive" testing philosophy

Do not use for:

  • Pure SPA projects without a Worker (no D1, no Hono middleware) — Vite dev server e2e works fine
  • Projects without a strict CSP — the HMR preamble conflict doesn't trigger
  • Apps where you've already accepted 'unsafe-inline' in production CSP — different threat model

Deliverables (completion criteria)

  • [ ] playwright.config.ts with webServer.command: "pnpm run e2e:server" (NOT pnpm dev)
  • [ ] package.json script: "e2e:server": "pnpm build && pnpm exec wrangler dev --config dist/<bundle>/wrangler.json --persist-to .wrangler/state --port <port>"
  • [ ] All console.error() calls in security-relevant middleware (auth / authorization 404) verified to NOT leak in production but show correctly during e2e
  • [ ] WebAuthn-using golden-path test uses CDP virtual authenticator, NOT DEV_BYPASS_USER_ID
  • [ ] OAuth-using golden-path test uses the seeded-session seam (seed a real session row keyed exactly as production keys it, inject the cookie), NOT a DEV_BYPASS / test-login route — no Worker code added or modified for e2e
  • [ ] e2e test count stays narrow: golden path 1 + auth boundary 1 + security headers 1-3 (≤ 6 specs total)
  • [ ] .dev.vars (or e2e-specific vars) documented in e2e/README.md with the required values (SESSION_SECRET, any auth bootstrap tokens, RP_ID=localhost if WebAuthn; ORIGIN = baseURL if OAuth — note the seam needs no OAuth client secrets)
  • [ ] e2e/helpers/dev-reset.ts / seed.ts (or equivalent) hardcodes --local in every wrangler invocation to prevent accidental prod D1 wipe
  • [ ] The .dev.vars copy in dist/<bundle>/ is neutralised (deleted by a prepare step, or every key passed with --var) — Trap 2b
  • [ ] No spec sends a request body to a route that rejects before reading it (session 401 / CSRF 403) — Trap 3
  • [ ] tsconfig.e2e.json (types: ["node"]) is part of pnpm check, so CI type-checks e2e/** and playwright.config.ts even though e2e does not run there
  • [ ] One paragraph in playwright.config.ts explaining why we don't target `vite dev` so the next person doesn't "simplify" it back
  • [ ] If running in a Docker sandbox: follow the companion skill `playwright-e2e-in-docker-sandbox` (baked browser, stripped rate-limit binding, --ip 127.0.0.1, gated --no-sandbox)

Trap 1: Strict CSP vs Vite HMR inline preamble

@vitejs/plugin-react injects an inline <script> into every HTML response in dev mode to bootstrap React Fast Refresh:

html
<script type="module">
import RefreshRuntime from "/@react-refresh";
RefreshRuntime.injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
</script>

Your production CSP (script-src 'self') blocks this inline script. React then fails to bootstrap and the page never mounts. Symptoms: page.reload() in Playwright completes, the URL changes, but no /api/* calls are made and assertions for any UI text time out.

Why `/` works in initial load but reloads break: with @cloudflare/vite-plugin@0.1.x, / is served by Vite directly (the Worker is bypassed), so no Hono middleware → no CSP header → preamble runs. Any non-/ path (including SPA fallback after page.reload()) goes through the Worker → middleware applies CSP → preamble blocked. (On @cloudflare/vite-plugin@1.x the Worker serves / too, so the preamble can be blocked from the initial load — same diagnosis, same fix.)

Why "relax CSP in dev" is the wrong fix: it makes your dev CSP differ from prod CSP, so the e2e isn't actually testing the prod configuration. The whole point of e2e is to verify wiring as it ships.

The correct fix: target the build artifact, not the dev server. The built index.html doesn't have the HMR preamble (it's only injected by Vite dev) so strict CSP is fine. See references/csp-vs-vite-hmr-preamble.md for the full diagnosis trace.

Trap 2: wrangler dev --config state path divergence

Once you switch e2e to wrangler dev --config dist/<bundle>/wrangler.json, you might see:

D1_ERROR: no such table: users: SQLITE_ERROR

This is because wrangler dev resolves .wrangler/state/v3/d1/*.sqlite (the local D1 file) relative to the config file's directory when --config is passed, not relative to the cwd. Since the build emits a fresh wrangler.json into dist/, wrangler creates a brand-new empty sqlite at dist/<bundle>/.wrangler/state/v3/d1/*.sqlite. Your migrations were applied to packages/<pkg>/.wrangler/state/... (cwd-relative, where pnpm db:migrate ran) — completely different file.

Symptom progression to recognize the trap: tests that don't touch the DB (security headers, /health) pass; tests that do touch the DB (register, login, any authenticated route) fail with sqlite "no such table" errors.

The fix: pass --persist-to .wrangler/state to pin the state directory to the cwd-relative path, matching where migrations were applied.

bash
pnpm exec wrangler dev \
--config dist/<bundle>/wrangler.json \
--persist-to .wrangler/state \
--port 5173

See references/wrangler-state-path-quirk.md for the physical evidence (du -sh dist/<bundle>/.wrangler/) and how to detect the trap.

Variant — a dedicated e2e state dir. The requirement is "server and helper commands look at the same sqlite", not the literal .wrangler/state. kokemusu (2026-09-02) points both at --persist-to .wrangler/e2e: globalSetup runs wrangler d1 migrations apply <db> --local --persist-to .wrangler/e2e (idempotent, creates the file on first run) and then empties every table, so a run starts from "no user, no rows" and never touches the `pnpm dev` database (its registered passkeys and posts survive). One constant (E2E_PERSIST_DIR in e2e/env.ts) feeds the db helper; the e2e:server script repeats it on the command line.

Trap 2b — the `.dev.vars` copy. @cloudflare/vite-plugin 1.x copies .dev.vars into dist/<bundle>/.dev.vars at build time, and wrangler reads .dev.vars from the directory of the config it was given — the same config-relative rule as the state path. So the e2e server silently runs with the developer's DEV_CSP=1 (relaxed CSP → the security spec fails) and dev ORIGIN (→ 403 on every POST, challenge_mismatch on verify). Fix in the prepare step: delete dist/<bundle>/.dev.vars and write the e2e values into the derived config's vars, or pass every key with --var (CLI --var outranks the copy; measured precedence --var > .dev.vars > vars). Verified 2026-09-02 in kokemusu (vite-plugin 1.53, wrangler 4.125).

Trap 3: a request body the Worker never reads kills wrangler dev

Symptom: one spec passes, the next one's first request (or the next request from curl) is a 500 `Network connection lost`, and wrangler dev prints ✘ [ERROR] and exits — every later spec fails with ECONNREFUSED.

Cause: the previous request carried a body (a JSON POST) and the Worker answered before reading it — exactly what a session gate (401) or a CSRF check (403) does. wrangler dev's ProxyWorker → user-worker hop keeps that connection pooled, the runtime closes it because of the unread body, and the next request through the proxy dies on the stale connection (entry.worker.js fetch → Network connection lost); wrangler treats the ProxyWorker error as fatal. Reproduced deterministically with curl on wrangler 4.125.0 and 4.128.0 (2026-09-02, kokemusu):

bash
curl -X POST -H 'Origin: http://localhost:5183' -H 'Content-Type: application/json' \
--data '{"body":"x"}' http://127.0.0.1:5183/api/posts # 401, body unread
curl -X POST -H 'Origin: http://localhost:5183' http://127.0.0.1:5183/api/auth/logout
# → 500 Network connection lost, then wrangler dev exits

Production workerd does not care — returning early without draining the body is normal and correct there — so do not change the Worker for this (no defensive await c.req.text() in the session middleware). The rule lives in the specs: never send a body to a route that rejects before reading it. An auth-boundary spec asserts POST /api/posts → 401 without data:; the outcome is identical because the gate answers first. Requests whose body is read before the reply (register/begin parsing JSON before a 403 on a wrong token, a validation 400 after c.req.json()) are fine. Upgrading wrangler does not help (4.128.0 behaves the same); write the rule into e2e/README.md.

WebAuthn (passkey) automation

If your app uses WebAuthn, do not add a DEV_BYPASS_USER_ID shortcut just to make e2e easier. That bypasses sessionMiddleware / register / login entirely, so the e2e provides zero regression coverage for the wiring you most want to protect.

Use Playwright's CDP WebAuthn.addVirtualAuthenticator instead. It works headlessly, lives in the browser context, and exercises the real @simplewebauthn/browser → @simplewebauthn/server round-trip:

typescript
const cdp = await page.context().newCDPSession(page);
await cdp.send("WebAuthn.enable");
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
options: {
protocol: "ctap2",
transport: "internal",
hasResidentKey: true,
hasUserVerification: true,
isUserVerified: true,
},
});

The virtual authenticator must be enabled before page.goto() of any auth-relevant page. RP_ID must match the page origin's hostname (localhost for local dev, your prod domain in prod). In the Docker sandbox bind the server to 127.0.0.1 but keep baseURL / ORIGIN / RP_ID on localhost (verified 2026-08-30 in matatabetai — see the reference). See references/webauthn-virtual-authenticator.md for the full helper module + .dev.vars requirements.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/okayus/okayus-skills/cloudflare-workers-e2e-playwright/badge)](https://verified-skill.com/skills/okayus/okayus-skills/cloudflare-workers-e2e-playwright)

Something wrong with this skill or its page? Tell us.