●SONNET 4.5 — Sonnet 4.5 was retired from the Claude API on 11/30. Calls now return an error. Move to Sonnet 5.5●PROJECTS — The Enterprise Analytics API now reports daily usage for the new projects experience (beta)●OPUS 4.5 — claude-opus-4-5 retires on 2027/1/22, 52 days from now. The replacement is claude-opus-5-5●LANGUAGE — Some users say Claude switches to another language mid-session while they write in English●NEW — New: Weekly usage looks like it jumped right after a plan upgrade? Check this first●COWORK — Handing Cowork a folder for the first time? Start with a task that only reads files●SONNET 4.5 — Sonnet 4.5 was retired from the Claude API on 11/30. Calls now return an error. Move to Sonnet 5.5●PROJECTS — The Enterprise Analytics API now reports daily usage for the new projects experience (beta)●OPUS 4.5 — claude-opus-4-5 retires on 2027/1/22, 52 days from now. The replacement is claude-opus-5-5●LANGUAGE — Some users say Claude switches to another language mid-session while they write in English●NEW — New: Weekly usage looks like it jumped right after a plan upgrade? Check this first●COWORK — Handing Cowork a folder for the first time? Start with a task that only reads files
Running Claude Code × Playwright E2E Tests in Production — Pitfalls and Decision Criteria
Implementation patterns for running E2E tests with Claude Code and Playwright in production, plus how to measure whether the investment pays back. Includes the Cloudflare Workers and Pages preview deployment pitfalls, and a decision framework that indie developers can use to judge whether E2E tests are worth the investment.
Across years of building and running apps on my own, the same regret has repeated itself: "if I had written the E2E test before this release, that production incident would have been prevented." Writing and maintaining test code is heavy work, and as an indie developer it has never been realistic to put the same effort into tests as into production code.
That changed when I started combining Claude Code with Playwright. E2E testing finally turned from a sunk cost into an investment. This article gathers what I measured and what I tripped over while rolling this stack out gradually across my own sites.
If I had to name the one thing that changed, it was not the number of tests. It was being able to trust that a red run meant a real bug. Getting there took a detour: for a while I accepted whatever Claude Code wrote, and the suite became flakier, not steadier.
What follows covers what to record from day one so you can tell whether the investment is paying back, the mistakes that slip into generated test code, and the framework I use as an indie developer to decide whether E2E testing is worth it. The code was checked against the Playwright 1.65 line and the GitHub Actions docs as of November 2026.
The First 30 Minutes — Installing Playwright and Wiring It to Claude Code
I picked Playwright for one reason: it drives Chrome, Firefox, and Safari engines from a single config file. Having shipped two Safari-only layout bugs to production, being able to reproduce WebKit locally settled the decision for me. Start with the minimum setup that Claude Code needs to work against.
Installing and Configuring Playwright
npm install --save-dev @playwright/testnpx playwright install# Generate and configure playwright.config.ts
After installing Playwright, create your playwright.config.ts configuration file—this becomes the nerve center for all test execution.
This foundational configuration enables Claude Code to reference your test environment and generate appropriately-scoped test suites on subsequent requests.
Creating Reusable Claude Code Prompt Templates
To maximize efficiency with Claude Code, prepare standardized prompt templates that you'll refine over time.
# Playwright Test Code Generation PromptYou are a Playwright testing expert. Generate test code based on the following requirements.## Requirements- Component/Page to test: [COMPONENT_NAME]- Test scenarios: 1. [Scenario 1] 2. [Scenario 2]## Standards- Adopt Page Object pattern- Use data-testid attributes for element selection- Explicitly define wait strategies (no hardcoded sleeps)- Include localization support if multi-language needed- Include accessibility (a11y) checks## Output Format- Test file path: tests/e2e/[name].spec.ts- Page Object file: tests/pages/[Name]Page.ts
Providing this template to Claude Code ensures consistent, high-quality test generation every time.
How to Measure Cost and Payback
The setup above is well documented in the Playwright and Claude Code references. What is not documented is whether the setup actually pays back once it meets production. I started without recording anything, and three months later I could not answer the simple question "is this working?" These are the metrics I now record from the first day, and how I collect them.
Four metrics worth recording
Metric
How to collect it
How to read it
Flaky rate
Tests whose JSON reporter status is flaky (passed on retry) ÷ all tests, appended after each nightly run
Watch the trend. Don't aim for zero
Time per Page Object
From asking Claude Code to merging after review
Include review time; generation time alone is misleading
Bugs stopped before deploy
For each red run that was a real bug, one line written by hand
One a month is enough to justify the upkeep
CI time per run
The job duration in GitHub Actions
If waiting on PRs feels slow, parallelize or narrow the scope
The flaky rate was the inflection point. It moved E2E tests from "noisy, no one looks" to "if it's red, it's a real bug." Chasing zero by piling on waits makes the suite slow and dull, and a dull suite hides production regressions instead of catching them.
The three Claude Code prompts I keep returning to
I store reusable prompts under .claude/commands/ in each repo so changes are tracked in Git. The three I rely on most are:
Page Object autogeneration prompt — Given a Figma frame link and the data-testid naming convention, Claude Code produces a full Page Object class. Even with review included, it now takes me less time than writing one by hand.
Flaky diagnosis prompt — Given the JSON results of the last 10 CI runs, Claude Code classifies the root cause (network / animation / timing / state leak) and returns a patch. I hit the same kind of flake twice far less often than before.
Visual diff triage prompt — Given a list of *-diff.png filenames and pixel deltas, Claude Code returns a classification (allowable vs. real bug) plus a diff for the mask: config.
Of those, the flaky diagnosis prompt is the highest leverage one for indie developers. The full template lives in the "Automatic Flaky Test Diagnosis and Repair" section below.
The kinds of bugs it stopped before deploy
Looking back, the bugs the suite stopped before a production deploy clustered into four kinds. If you are deciding where to start, this may help:
Payment flow regressions (failing to reach Stripe Checkout)
The previous language lingering after a locale switch (next-intl)
Membership eligibility edge cases
Missing translation keys breaking the layout
In my AdMob app business, I have seen many times what happens when the payment flow breaks for even an hour. Revenue stops the moment Stripe Checkout cannot load. If you run a paid membership on a personal project, prioritize the payment flow in your E2E suite above everything else.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Mistakes that slip into generated tests (networkidle, toHaveCount with a regex, looping reruns) and how to fix them
✦A triage table for tests that fail only on CI, plus a GitHub Actions workflow aligned with Playwright 1.65 and the v6 actions
✦Why E2E breaks around Cloudflare Pages preview URLs, Stripe Checkout and locale switches, with fix code
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Writing test code from a blank file was the biggest psychological barrier for me. Handing over a screenshot of a screen that already works and asking for the test to be derived from it changed the job entirely. Instead of inventing something from nothing, you are describing what is in front of you.
Automatic Test Case Generation from Screenshots
// Prompt to provide Claude Code"Based on the screenshot of an e-commerce product detail page, generate comprehensivePlaywright test code for the critical user interactions.Page elements visible:- Product image carousel (left side with slider controls)- Product info panel (right side): - Product name (H1) - Price display - Star rating (5-star system) - 'Add to Cart' button - Quantity selector dropdown- Customer reviews section belowRequired test scenarios:1. Product info displays on page load2. Image carousel navigation works correctly3. Users can modify quantity and add to cart4. Price calculations are accurate5. Reviews section is accessible via scroll"
Claude Code analyzes the screenshot visually and generates comprehensive test code like this:
// Auto-generated test code exampleimport { test, expect } from '@playwright/test';import { ProductDetailPage } from '../pages/ProductDetailPage';test.describe('Product Detail Page', () => { let page: ProductDetailPage; test.beforeEach(async ({ page: playwrightPage }) => { page = new ProductDetailPage(playwrightPage); await page.goto('/products/123'); }); test('displays product information on page load', async () => { await expect(page.productName).toBeVisible(); await expect(page.productPrice).toBeVisible(); await expect(page.ratingStars).toBeVisible(); }); test('image carousel navigates between product images', async () => { const initialImage = await page.currentProductImage.getAttribute('src'); await page.nextImageButton.click(); // Wait for the src to actually change instead of sleeping a fixed 300 ms await expect(page.currentProductImage).not.toHaveAttribute('src', initialImage ?? ''); }); test('allows users to change quantity and add to cart', async () => { await page.quantityDropdown.selectOption('3'); await page.addToCartButton.click(); await expect(page.cartNotification).toContainText('Added to cart'); // Verify price calculation const expectedPrice = 100 * 3; // unit_price × quantity await expect(page.totalPrice).toContainText(String(expectedPrice)); }); test('reviews section is scrollable into view', async () => { await page.reviewsSection.scrollIntoViewIfNeeded(); await expect(page.reviewsSection).toBeInViewport(); await expect(page.reviewsList.first()).toBeVisible(); // toHaveCount only accepts a number; check 'at least one' via first() });});
Automatic Detection of Interactive Elements
Claude Code automatically detects not just visual elements, but clickable buttons, input fields, dropdowns, and modal windows from your screenshots.
// Interactive element detection"This navigation bar contains these interactive elements:- Logo (clickable, navigates home)- Search input field- Category dropdown menu- User account menuGenerate tests that verify the behavior of each interactive element."
Claude Code's response includes detailed test logic:
The Page Object pattern is the gold standard for maintainable, scalable test suites. Claude Code can auto-generate these patterns perfectly.
Page Object Design Principles and Auto-Generation
The Page Object pattern encapsulates UI elements and their operations. When Claude Code generates Page Objects from your design, test maintainability skyrockets.
Progressive Page Object Construction for Complex Components
For complex UIs, giving Claude Code step-by-step instructions produces more sophisticated Page Objects.
// Complex data table Page Object example// tests/pages/DataTablePage.tsimport { Page, Locator, expect } from '@playwright/test';export class DataTablePage { readonly page: Page; readonly table: Locator; readonly rows: Locator; readonly sortButtons: Locator; readonly paginationButtons: Locator; readonly filterInput: Locator; readonly selectAllCheckbox: Locator; constructor(page: Page) { this.page = page; this.table = page.locator('[data-testid="data-table"]'); this.rows = this.table.locator('[data-testid="table-row"]'); this.sortButtons = this.table.locator('[data-testid="sort-button"]'); this.paginationButtons = page.locator('[data-testid="pagination-button"]'); this.filterInput = page.locator('[data-testid="filter-input"]'); this.selectAllCheckbox = page.locator('[data-testid="select-all"]'); } async goto() { await this.page.goto('/data-table'); await this.table.waitFor({ state: 'visible' }); } // Sorting async sortByColumn(columnName: string) { const button = this.sortButtons.locator(`text=${columnName}`).first(); await button.click(); // Wait for table re-render await expect(this.table).not.toHaveAttribute('aria-busy', 'true'); // wait on the table's own busy state, not networkidle (assumes the table sets aria-busy="true" while loading) } // Filtering async filterByText(text: string) { await this.filterInput.fill(text); await expect(this.table).not.toHaveAttribute('aria-busy', 'true'); // wait on the table's own busy state, not networkidle (assumes the table sets aria-busy="true" while loading) } // Pagination async goToPage(pageNumber: number) { const button = this.paginationButtons .locator(`text="${pageNumber}"`) .first(); await button.click(); await expect(this.table).not.toHaveAttribute('aria-busy', 'true'); // wait on the table's own busy state, not networkidle (assumes the table sets aria-busy="true" while loading) } // Extract row data async getRowData(rowIndex: number): Promise<string[]> { const row = this.rows.nth(rowIndex); const cells = row.locator('[data-testid="table-cell"]'); const count = await cells.count(); const data: string[] = []; for (let i = 0; i < count; i++) { const text = await cells.nth(i).textContent(); data.push(text || ''); } return data; } // Multi-select rows async selectRows(indices: number[]) { for (const index of indices) { const checkbox = this.rows .nth(index) .locator('[data-testid="row-checkbox"]'); await checkbox.check(); } } // Get row count async getRowCount(): Promise<number> { return this.rows.count(); }}
Visual Regression Testing Implementation
UI changes can introduce unintended visual breaks. By combining Claude Code with visual regression testing, you can detect pixel-level UI changes automatically.
Claude Code helps manage visual regression testing comprehensively, immediately identifying the scope of visual changes.
Automatic Flaky Test Diagnosis and Repair
Flaky tests—those that sometimes pass and sometimes fail—undermine test suite reliability. Claude Code can auto-diagnose these issues and propose repairs.
Automatic Flaky Test Detection Patterns
// Prompt to diagnose and fix flaky tests"This test intermittently fails (~15% failure rate):\`\`\`typescripttest('search results display', async ({ page }) => { await page.goto('/search'); await page.fill('[data-testid="search-input"]', 'keyword'); await page.press('[data-testid="search-input"]', 'Enter'); const results = page.locator('[data-testid="search-result"]'); await expect(results.first()).toBeVisible();});\`\`\`Identify the root cause and provide a repaired version."
Claude Code identifies the issues and suggests repairs:
// Repaired test codetest('search results display', async ({ page }) => { await page.goto('/search'); const searchInput = page.locator('[data-testid="search-input"]'); await searchInput.waitFor({ state: 'visible' }); // Ensure field is interactive await searchInput.fill('keyword'); await page.press('[data-testid="search-input"]', 'Enter'); // Wait for navigation await page.waitForURL(/\/search\?q=/); // Explicitly wait for results const results = page.locator('[data-testid="search-result"]'); // Wait for at least one result (toHaveCount does not accept a regex) await expect(results.first()).toBeVisible({ timeout: 5000 }); // Check the result is actionable (toBeFocused does not apply to a result row) await expect(results.first()).toBeEnabled();});
Flaky Test Classification and Repair Strategies
// Flaky test classifications and repair patterns// 1. Network wait insufficiency// Fix: networkidle is officially DISCOURAGED. Listen for the exact response before the actionconst searchDone = page.waitForResponse(r => r.url().includes('/api/search') && r.ok());await page.getByTestId('search-input').press('Enter');await searchDone;// 2. Animation completion not waited// Fix: Replace hardcoded timeouts with condition-based waitsawait page.locator('[data-testid="modal"]').waitFor({ state: 'visible'});await page.waitForLoadState('domcontentloaded');// 3. Async data load not confirmed// Fix: Wait for skeleton loaders to disappearawait page.waitForSelector( '[data-testid="skeleton-loader"]', { state: 'hidden' });// 4. Random selection from multiple elements// Fix: Conditionally select first valid elementconst firstEnabledButton = page .locator('[data-testid="action-button"]:not([disabled])') .first(); // .first().locator() searches descendants, so put the condition in the selectorawait firstEnabledButton.click();// 5. External API response delay// Fix: Set appropriate timeout and add retry logicawait expect(page.locator('[data-testid="data"]')) .toContainText('expected value', { timeout: 10000 });
Teaching Claude Code these patterns improves its auto-repair accuracy significantly.
Catching the Flakiness a Single Report Cannot Show You
Everything above deals with tests that Playwright itself labelled as flaky. But the longer I ran this suite, the more I noticed a nastier category of instability.
Playwright marks a test flaky only when it failed and then passed on a retry within the same run. A test that fails on Monday's run and passes on Tuesday's shows up as a plain red in one report and a plain green in the other. As long as you look at one report at a time, that cross-run flip is invisible to you forever.
So I put a small script between the nightly job and my own attention. It aggregates the reports the job has collected.
#!/usr/bin/env python3"""Aggregate multiple Playwright JSON reports and find tests that flip between runs."""import json, sys, globfrom collections import defaultdictdef walk(node, out): for spec in node.get("specs", []): key = f'{spec.get("file","?")}::{spec.get("title","?")}' for t in spec.get("tests", []): out[key].append(t.get("status", "unknown")) for child in node.get("suites", []): walk(child, out)def load(path): with open(path, encoding="utf-8") as fh: data = json.load(fh) out = defaultdict(list) for suite in data.get("suites", []): walk(suite, out) return {k: v[0] for k, v in out.items() if v}def main(pattern, threshold): paths = sorted(glob.glob(pattern)) if not paths: print(f"No reports matched: {pattern}") return 2 history = defaultdict(list) for p in paths: for key, status in load(p).items(): history[key].append(status) within, across, stable = [], [], 0 for key, statuses in history.items(): seen = set(statuses) if "flaky" in seen: within.append((key, statuses)) elif {"expected", "unexpected"} <= seen: across.append((key, statuses)) else: stable += 1 total = len(history) unstable = len(within) + len(across) rate = unstable / total * 100 if total else 0.0 print(f"{len(paths)} report(s) / {total} test(s)") print(f" Within-run flaky (labelled by Playwright): {len(within)}") print(f" Cross-run flaky (always green in isolation): {len(across)}") print(f" Stable: {stable}") print(f" Instability: {rate:.2f}% (threshold {threshold:.2f}%)") if across: print("\n-- Not detectable from any single report --") for key, statuses in across: print(f" {key}\n {' '.join(statuses)}") return 1 if rate > threshold else 0if __name__ == "__main__": pattern = sys.argv[1] if len(sys.argv) > 1 else "reports/*.json" threshold = float(sys.argv[2]) if len(sys.argv) > 2 else 5.0 sys.exit(main(pattern, threshold))
walk() is recursive because Playwright returns suites nested inside one another. Reading only the top level silently drops tests in any project that organises specs into directories.
To confirm the behaviour I built five sample reports over twelve tests, with three of them deliberately made unstable. This is the actual output.
$ python3 flaky_rate.py "reports/run-1.json" 5.01 report(s) / 12 test(s) Within-run flaky (labelled by Playwright): 1 Cross-run flaky (always green in isolation): 0 Stable: 11 Instability: 8.33% (threshold 5.00%)$ python3 flaky_rate.py "reports/*.json" 5.05 report(s) / 12 test(s) Within-run flaky (labelled by Playwright): 1 Cross-run flaky (always green in isolation): 2 Stable: 9 Instability: 25.00% (threshold 5.00%)-- Not detectable from any single report -- tests/e2e/locale.spec.ts::locale switch preserves the path expected unexpected expected unexpected expected tests/e2e/article.spec.ts::tag page returns 200 expected expected expected expected unexpected
Same suite, same tests: 8.33% from one report, 25.00% once five are compared. Neither of the two extra offenders is labelled flaky anywhere. The locale test fails two runs out of five, which in production terms should be the first thing you fix — and yet I spent a stretch of time reassured by whichever green report I happened to open.
I keep the raw sequence (expected unexpected expected unexpected expected) in the output on purpose, because the shape of the flip carries information. Alternating results point at execution order or state leaking between tests. A single failure at the end points at a recent change or at the deploy environment.
The exit code is deliberately three-valued: 1 when the threshold is exceeded, 0 when it is not, and 2 when no report was found at all. Without that third value, a night where report collection itself broke reports a comfortable 0% and stays green. That is exactly how I once let roughly two weeks pass without noticing that nothing was being measured.
In GitHub Actions I hang it off the end of the nightly job.
The 5% flaky-rate ceiling described later under "Set an upper bound on the investment" is enforced by this exit code rather than by discipline. Discipline was not something I could rely on here.
CI/CD Pipeline Integration (GitHub Actions)
A test suite that is green on your laptop insures you against nothing. Only once it runs on every pull request and blocks the merge when it is red does E2E testing actually stand between you and a production incident. In my experience this is the step that gets postponed the longest.
Auto-Generated GitHub Actions Workflow
# .github/workflows/e2e-tests.ymlname: E2E Testson: push: branches: [ main, develop ] pull_request: branches: [ main, develop ] schedule: - cron: '0 2 * * *' # Daily at 2:00 AM UTCjobs: test: timeout-minutes: 60 runs-on: ubuntu-latest permissions: contents: read pull-requests: write # needed to comment on the PR strategy: fail-fast: false matrix: # No Node version axis: Playwright 1.65 needs Node 20+, and a node x browser # matrix makes artifact names collide browser: [chromium, firefox, webkit] steps: - uses: actions/checkout@v6 - name: Setup Node.js uses: actions/setup-node@v6 with: node-version: lts/* cache: 'npm' - name: Install dependencies run: npm ci - name: Install Playwright browsers run: npx playwright install --with-deps ${{ matrix.browser }} # Let webServer in playwright.config.ts start the app. Starting npm run dev & here # makes Playwright throw on CI, because reuseExistingServer is false there # and the port is already taken - name: Run E2E tests (${{ matrix.browser }}) run: npx playwright test --project=${{ matrix.browser }} - name: Upload test results if: ${{ !cancelled() }} uses: actions/upload-artifact@v5 with: name: playwright-report-${{ matrix.browser }} path: | playwright-report/ test-results/ retention-days: 30 - name: Comment on the PR when tests fail if: failure() && github.event_name == 'pull_request' uses: actions/github-script@v9 with: script: | await github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `❌ E2E tests (${{ matrix.browser }}) failed. The trace is in the Actions artifacts.` }) flaky-detection: name: Flaky test detection runs-on: ubuntu-latest if: github.event_name == 'schedule' steps: - uses: actions/checkout@v6 - name: Setup Node.js uses: actions/setup-node@v6 with: node-version: lts/* cache: 'npm' - name: Install dependencies run: npm ci - name: Install Playwright browsers run: npx playwright install --with-deps # A for-loop of 10 runs wipes test-results/ each time, leaving only the last run. # --repeat-each puts all 10 repetitions into a single results.json - name: Run each test 10 times (flaky detection) run: npx playwright test --repeat-each=10 --retries=0 || true - name: Generate flaky test report if: always() run: node scripts/analyze-flaky-tests.js - name: Upload flaky test report if: always() uses: actions/upload-artifact@v5 with: name: flaky-test-report path: flaky-report.json
Everything above can be reconstructed from the Playwright and Claude Code official documentation. The four pitfalls below could not. I ran into all of them while running my sites on Cloudflare Workers and Pages, and the first two cost me weeks before I worked out the fix.
Pitfall 1: Cloudflare Pages preview URLs change on every commit
Cloudflare Pages issues preview URLs in the format https://<random>.<project>.pages.dev, where the <random> prefix changes per commit. If you hardcode baseURL in playwright.config.ts, you end up editing the config file on every PR.
The fix is to fetch the preview URL inside GitHub Actions after deploy and inject it as an environment variable.
# .github/workflows/e2e-tests.yml- name: Fetch Pages preview URL id: pages run: | DEPLOYMENT_URL=$(curl -s \ -H "Authorization: Bearer ${{ secrets.CF_API_TOKEN }}" \ "https://api.cloudflare.com/client/v4/accounts/${{ secrets.CF_ACCOUNT_ID }}/pages/projects/${{ env.PROJECT }}/deployments?env=preview" \ | jq -r --arg sha "${{ github.event.pull_request.head.sha }}" \ 'first(.result[] | select(.deployment_trigger.metadata.commit_hash == $sha and .latest_stage.status == "success") | .url) // empty') # Pick only this PR's commit, and only once its deploy has finished; fail if empty [ -n "$DEPLOYMENT_URL" ] || { echo "preview not ready"; exit 1; } echo "url=$DEPLOYMENT_URL" >> $GITHUB_OUTPUT- name: Run E2E tests env: PLAYWRIGHT_BASE_URL: ${{ steps.pages.outputs.url }} run: npx playwright test
Taking .result[0] can pick up a deployment from a different branch, so filter by the commit hash and a finished deploy as above. If you want something lighter, Pages also gives every branch an alias, https://<branch>.<project>.pages.dev, which points at the branch's latest commit (non-alphanumeric characters become hyphens). Pass that to PLAYWRIGHT_BASE_URL instead — but while a deploy is still running, the alias points at the previous commit, so wait for it to finish.
Pitfall 2: Right after a Workers deploy, networkidle waits become unpredictable
Right after a deploy, the first few requests to a Worker sometimes came back late for me (how late depends on the environment, and I have not measured it carefully enough to publish numbers). Stack waitForLoadState('networkidle') — wait until there has been no traffic for 500 ms — on top of that, and the wait becomes unpredictable; my CI jobs occasionally timed out. Playwright's own API reference marks networkidle as DISCOURAGED: don't use it for testing, rely on web assertions instead.
There are two fixes. I apply both together.
// tests/global-setup.ts — warm up before the suite runsimport { request } from '@playwright/test';async function globalSetup() { const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? 'http://localhost:3000'; const req = await request.newContext(); // Warm-up: fetch the four primary pages so Workers is hot const warmupPaths = ['/', '/articles', '/membership', '/blog']; await Promise.all( warmupPaths.map(p => req.get(`${baseURL}${p}`, { timeout: 30000 }).catch(() => null) ) ); await req.dispose();}export default globalSetup;
In addition, remove every waitForLoadState('networkidle') from the tests and wait with web assertions such as await expect(locator).toBeVisible(). With both in place, the first-run stalls stopped appearing in my setup.
Pitfall 3: The previous language lingers after a locale switch
On a bilingual site built with next-intl, expect(page.locator('h1')).toContainText('Membership') failed now and then. I was sure cookies were leaking between tests, so I added a beforeEach that wiped cookies and localStorage. Nothing changed.
Looking back, that was never going to help. Playwright Test creates a fresh browser context for every test, so cookies and localStorage do not carry over from one test to the next — the Isolation page of the official docs says so plainly. What was actually carrying state was the inside of a single test, and the storageState file I reused for login. When I saved the logged-in state, the locale cookie (NEXT_LOCALE by default in next-intl) was saved with it and quietly travelled into tests for the other language.
// Split tests by language and start each one in that languagetest.describe('English pages', () => { test.use({ locale: 'en-US' }); test('membership heading renders in English', async ({ page, context }) => { // If you reuse storageState, drop only the locale cookie await context.clearCookies({ name: 'NEXT_LOCALE' }); await page.goto('/en/membership'); await expect(page.getByRole('heading', { level: 1 })).toContainText('Membership'); });});// When a test switches language itself, confirm the switch finished (URL and lang) before checking the headingtest('switch from Japanese to English', async ({ page }) => { await page.goto('/ja/membership'); await page.getByRole('link', { name: 'English' }).click(); await expect(page).toHaveURL(/\/en\/membership/); await expect(page.locator('html')).toHaveAttribute('lang', 'en'); await expect(page.getByRole('heading', { level: 1 })).toContainText('Membership');});
An earlier version of this article used addInitScript to clear localStorage. That runs on every page load, so it also breaks any test that checks whether a language choice is remembered. Deciding which state each test starts from turned out to be far steadier than wiping things.
Pitfall 4: Don't drive the Stripe Checkout page in tests
I used to believe Playwright could not touch the Stripe Checkout form because of CORS. That was wrong. Stripe's own Automated testing guide says frontend interfaces such as Checkout and the Payment Element have security measures that prevent automated testing, and the API is rate-limited, and it recommends simulating those outputs with mock data instead. It is not a place you can't reach — it is a place you shouldn't.
The policy I have settled on has three parts:
In E2E, click the purchase button and assert the redirect to https://checkout.stripe.com/ — nothing more. The Checkout Session is created server-side with a test-mode secret key.
Test the thank-you page on its own, with the payment-verification API mocked.
Keep webhook handling out of E2E and exercise it with the Stripe CLI: stripe listen --forward-to plus stripe trigger checkout.session.completed.
test('purchase button redirects to Stripe Checkout', async ({ page }) => { await page.goto('/membership'); await page.getByTestId('membership-checkout').click(); await expect(page).toHaveURL(/^https:\/\/checkout\.stripe\.com\//); // Stop here; do not fill the Checkout form});test('thank-you page renders after payment', async ({ page }) => { // Mock the verification call made from the browser (this won't help if you verify server-side) await page.route('**/api/checkout/verify?session_id=*', route => route.fulfill({ json: { status: 'complete', plan: 'premium' } }) ); await page.goto('/membership/thanks?session_id=cs_test_dummy'); await expect(page.getByTestId('thanks-heading')).toBeVisible();});
If you run a paid membership, covering just two checkpoints — "reaches Checkout" and "thank-you page renders" — catches most payment-flow accidents before they ship.
A Triage Table for "Green Locally, Red on CI"
Nothing ate more of my time than tests that passed on my iMac and failed in GitHub Actions. Here are the cases I actually hit, indexed by what shows up in the log (the messages are their typical form).
Symptom (what the log says)
Likely cause
How to confirm
Fix
localhost:3000 is already used
The workflow starts npm run dev & while webServer tries to start the same port
Is reuseExistingServer false on CI?
Remove the manual start; let webServer own it
Executable doesn't exist at ...
Browsers not installed, or installed for a different Playwright version
npx playwright --version vs. the lockfile
Run npx playwright install --with-deps after npm ci
uses a deprecated version of actions/upload-artifact: v3
v3 stopped working on GitHub.com on January 30, 2025
The uses: lines
Move to v4 or later (Playwright's own example uses v5)
an artifact with this name already exists
From v4 on, an artifact name cannot be reused within a run; a multiplied matrix produced duplicate names
Matrix axes vs. name:
Put every matrix value in the name, or drop an axis
Test timeout of 30000ms exceeded (CI only)
Waiting on networkidle while analytics or a live connection never goes quiet
The Network tab of the trace
Drop networkidle; wait with web assertions
Only screenshot comparisons fail on CI
OS and font differences; baselines are stored per platform
The suffix of the baseline file name (-linux etc.)
Generate baselines in the same environment as CI (the official Docker image)
The nightly job runs at the wrong hour
schedule cron is in UTC
The run timestamps in Actions
For 2:00 AM in Japan, use 0 17 * * *
Three Misunderstandings Worth Correcting
When Claude Code writes tests, plausible-looking "stabilizers" creep in. I accepted them as proposed at first, and my flaky rate went up, not down.
"Waiting for networkidle makes tests stable." The official API reference marks networkidle as DISCOURAGED and says to rely on web assertions to assess readiness. Pages with ads, analytics or a live connection may never go idle at all.
"Cookies leak between tests, so clear them every time." Playwright Test gives each test a new context. If something looks leaked, suspect a reused storageState or state inside the same test.
"Passing a regex to toHaveCount expresses 'at least one'."toHaveCount takes a number only. Write "at least one" as expect(list.first()).toBeVisible() or expect(list).not.toHaveCount(0).
After fixing those three, I started questioning every wait I add. A wait should wait for proof the screen kept its promise, not for time to pass. I keep that sentence in the standing rules of the prompt I give Claude Code.
The Next Thing You Will Probably Hit
Once CI is green, the next mismatch tends to be "Claude Code reported every test passing, yet CI failed on the exit code." The cause is usually not the tests but how commands and pipes are chained. I wrote that up in Claude Code Says 'All Tests Pass' but CI Goes Red.
The other one is whether to have Claude Code write a test before it fixes a bug that E2E found. Turning a red E2E run into a reproduction test first works well with the flow in Test-Driven Development with Claude Code.
When E2E Tests Are Worth the Investment for an Indie Developer
If you got this far and want to adopt this stack, here is the decision framework I use before writing a single line of test code. As an indie developer, the rule of thumb that has held up across many projects is this.
Preconditions for payback
Adopt the stack if at least three of the following four conditions are true.
Release frequency is weekly or higher (lower than that, manual testing is cheaper)
The product has 10-20 or more primary screens (5 or fewer, a manual checklist is faster)
There is at least one revenue-impacting flow that breaks visibly (payment, signup, etc.)
One person owns CI execution (an indie developer alone is fine)
In my case, the app business plus several sites running in parallel met all four. By contrast, if you operate a single site with monthly releases, manual testing plus Lighthouse CI is usually enough. As an investment decision, ask whether you can spend a week on initial setup and 2-4 hours per month on maintenance.
A recommended adoption order
This is the order I actually used. I do not know of a faster one.
Record one critical flow with npx playwright codegen (within the day)
Pick one naming convention for data-testid (the <screen>-<role> form is the most maintainable I have found)
Have Claude Code generate Page Objects for your three most critical flows (within three days)
Wire it into GitHub Actions to run on every PR (within a week)
Improve waits until the flaky rate stays under 5% (within a month)
Limit visual regression to the payment-flow screens only (permanently)
The key is to avoid going for 100% coverage from day one. A simple monthly KPI works: "did E2E catch at least one production incident this month?" The more metrics you track, the fewer of them anyone actually looks at. Picking a single number to watch is what made this sustainable for me.
Set an upper bound on the investment
Equally important is to cap the investment. Mine are:
Number of E2E test files: at most 1.5x the count of primary screens (around 30 per site in my case)
Monthly maintenance time per site: if it exceeds 4 hours, the suite is breaking down
Flaky rate: if it stays above 5% for 3 weeks straight, freeze new test additions until the root cause is fixed
As long as I stay within those bounds, E2E testing keeps paying back. The moment I exceed them, the suite itself becomes the next outage source.
Pre-Push Checklist
To close out the implementation discussion, here is the 12-item checklist I run through before pushing E2E changes to any of my sites. Every item on it represents a past production incident I personally caused or barely caught.
baseURL in playwright.config.ts is read from an env var, not hardcoded
retries: process.env.CI ? 2 : 0 enables retries only on CI
workers: process.env.CI ? 1 : undefined caps CI parallelism appropriately
screenshot: 'only-on-failure' and trace: 'on-first-retry' are enabled
The data-testid naming convention is written down (<screen>-<role> recommended)
Tests that reuse storageState do not carry the locale cookie along
globalSetup issues warm-up requests to primary pages
waitForLoadState('networkidle') is gone; waits use web assertions
Visual tests mask: dynamic elements explicitly
GitHub Actions uses actions/upload-artifact@v5 to capture the trace on failure (v3 stopped working in January 2025)
A nightly schedule: job runs the suite once to flag new flakes
Test names are written so the failure message is actionable in Slack alerts
We have walked through the implementation, the production pitfalls, and the decision framework for adopting this stack as an indie developer. If you want a concrete first step today, record one critical flow with npx playwright codegen, then rewrite the selectors to follow the <screen>-<role> data-testid convention I shared. That single move sets up everything downstream.
Thanks for reading. I hope your project stays stable in production.
Share
Thank You for Reading
Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.