Playwright E2E testing in a Next.js app rests on five decisions: scaffold with npm init playwright@latest, test a production build rather than the dev server, log in once in a setup project and reuse the saved state, reset your data before the run, and keep CI headless. Playwright covers Chromium, WebKit and Firefox on Windows, Linux and macOS, so one config can cover the browsers your users actually have (Playwright docs). The setup below follows that order, with a Supabase-flavoured data reset, a CI workflow outline, and rules for letting a coding agent write specs without wrecking them.
What to cover end to end, and what to leave alone
E2E tests cost more time and money than the other checks you own. Spend them where a failure costs real money or trust. Next.js itself describes Playwright as the tool for End-to-End and Integration testing (Next.js testing guides), and that frame is the right size: journeys, not units.
What earns a spec:
- Sign-up, log-in and log-out, including the redirect when you hit a protected page logged out
- The one flow that makes the business money (checkout, booking, the first paid action)
- The main create, edit and delete loop for your core data
- Anything that crosses a boundary your unit tests cannot see: middleware, server actions, a third-party redirect
What does not:
- Validation permutations. Test those against the function or the form component.
- Pure helpers and formatting. A unit runner is faster.
- Every visual state of every component.
Playwright's maintainers have said in a GitHub issue that Playwright Test is a generic runner and they use it for targets that are not end-to-end (issue 14268). True, and useful. I'd still keep your fast unit tests in a unit runner and keep the browser suite small enough that people run it. A suite that takes too long gets skipped, and a skipped suite is worth nothing.
If you want the argument for why any of this matters when an AI tool is editing your code, read tests and AI coding tools. This post covers the Playwright setup itself.
Install and config
Two routes. The quickest for a fresh project is pnpm create next-app --example with-playwright with-playwright-app , which gives you a Next.js project with Playwright already configured (Next.js docs). For an existing app, run npm init playwright@latest (or the yarn and pnpm equivalents). It initialises a new project or adds Playwright to an existing one, and re-running it later does not overwrite your tests (Playwright install docs).
You get playwright.config.ts , a lockfile and tests/example.spec.ts. The config holds target browsers, timeouts, retries, projects and reporters. By default, tests run headless and in parallel across Chromium, Firefox and WebKit.
This is the starter config I'd begin from. It's an illustrative outline, not a paste-and-pray file, so adjust names to your repo:
testDir: './tests'anduse: { baseURL: 'http://localhost:3000' }, so specs can callpage.goto('/settings')instead of spelling out the origin (use options).- A
webServerblock whose command builds and starts the production server, with the URL set to the same origin. Next.js recommends running tests against production code because it behaves more like what users get; thewebServerfeature exists so Playwright starts the server and waits for it. retriesset higher on CI than locally, using an environment check. Retries hide flakiness, so keep the count low and read the flaky list in the report.- A
setupproject matching/.*\.setup\.ts/, then browser projects that depend on it (next section). - Chromium as the everyday project, with Firefox and WebKit marked
default: false.
That last point comes from the Playwright 1.64 release notes: testProject.default keeps a project in the config without running it by default, so a plain npx playwright test runs Chromium only, while --project=\"*\" runs all three (release notes). Check your own version with npx playwright --version before relying on it.
The same release added --shuffle, which schedules tests in a random order and prints a seed so you can reproduce it. Use it. Order-dependent tests are quiet liars.
For newer Next.js apps, if you use Cache Components, the instant() helper from @next/playwright lets you assert what is visible straight after a navigation, before dynamic content streams in. If you are mid-upgrade, keep the Next.js 16 upgrade guide open while you rerun the suite.
Logging in once with storage state
Playwright runs each test in an isolated browser context, and a test can load previously saved authenticated state instead of logging in every time (auth docs). Logging in through the UI before every spec is the most common way to make a suite slow. Don't.

For tests without server-side state, Playwright recommends one shared account: authenticate once in a setup project, save the state, reuse it. The steps are:
- Create a
playwright/.authdirectory and add it to.gitignore. - Write
tests/auth.setup.tsthat performs the real login through the UI (fill the form, click the button, then wait for the final URL or a logged-in element so the cookies are actually set). - End that setup test with
await page.context().storageState({ path: authFile }). - Declare a setup project with
testMatch: /.*\.setup\.ts/. - Give each browser project
dependencies: ['setup']andstorageState: 'playwright/.auth/user.json'.
On step 1, the docs are direct: the state file may contain cookies and headers that could impersonate you or your test account, and they strongly discourage committing it, public or private repo. If the state need not persist between runs, write it under the project's outputDir, which is cleaned before every run.
Gotchas worth knowing
- IndexedDB is not in the snapshot by default. If your auth library keeps tokens there (the docs name Firebase Authentication), pass
indexedDB: truealongside the path. Cookie-based and localStorage-based sessions are covered as they are. - Stored state expires. You delete it when it does. UI mode will not run the setup project by default, so run
auth.setup.tsby hand now and then. - A logged-out project is just another project without
storageState. The projects docs describe running the same tests logged in and logged out as an intended use (projects docs). - Two roles in one test (an admin sends something, a user receives it)? The docs' multi-role pattern extends the base test with
adminPageanduserPagefixtures, each creating abrowser.newContextwith its own state file such asplaywright/.auth/admin.json(issue 29411 quotes it).
A shared account stops being fine the moment tests change that account's data and affect each other. That brings us to the part nobody documents well.
Resetting test data
Playwright's docs don't prescribe how to reset a database, and they shouldn't. This is my pattern for Supabase-backed apps. Treat it as a starting point rather than a rule.
- Never point tests at production. Use a separate Supabase project for testing, or a local stack. Put its URL and keys in environment variables for the test run only.
- Reset from Node, not from the browser. A small script using the service-role key truncates the tables your tests touch and reinserts known rows. That key bypasses row-level security, so it belongs in CI secrets and your local
.env, never in anything shipped to a browser. - Run the reset before the setup project. Make it a dependency of the auth setup, or a global setup step, so every run begins from the same rows. Create the test user as part of the seed so the saved login always has something to log into.
- Let tests that write data use unique values. A timestamp or random suffix in a title means two parallel workers don't fight over the same row.
- Test policies from the user's side. Because the reset bypasses security rules, add a spec that logs in as the ordinary user and confirms they cannot see someone else's rows.
Shuffle earns its keep here. Run npx playwright test --shuffle when you add a spec; if it only passes after another spec has created a row, you have found a dependency before it found you.
One caveat, since I can't verify your schema. Truncating in the wrong order trips foreign keys. Write the seed so it deletes children before parents, or use cascade, and keep the script boring.
Page objects without overdoing it
Page objects are good until they become a second codebase. My rule: don't write one until two specs share the same flow. Before that, inline locators are easier to read and easier to delete.
When you do write one, keep it thin:
- Locators as properties, built from role, text or test id. Playwright's code generator prioritises exactly those when it picks a locator (codegen docs), and they survive markup changes better than CSS chains.
- A handful of verbs for multi-step actions (
login,addToBasket,openSettings). - No assertions hidden inside helper methods. The spec should show what is being proved.
locator.within(), new in 1.64, if you need to combine two locators and scope a search to a card or table row.
Resist inheritance trees. Fixtures are the better composition tool: the multi-role example above wraps each page object in a fixture and closes its context afterwards. That is enough structure for most Next.js apps.
Running in CI
On CI, Playwright runs headless by default, and npx playwright install-deps installs the system dependencies (Next.js docs). To update the package and browsers, the install docs give npm install -D @playwright/test@latest followed by npx playwright install --with-deps.
A workflow outline, in the order the steps should run:
- Check out the repo and set up Node (Next.js's own adapter-testing example pins
node-version: '20'; use whichever your app targets). - Install dependencies from the lockfile.
- Restore a cache of
~/.cache/ms-playwright, the browser download folder that example also caches. - Install browsers with
npx playwright install --with-deps(orchromiumonly, the way that example does withpnpm playwright install --with-deps chromium, if you only run one browser). - Build the app, then run
npx playwright test --project=\"*\"so the full browser set runs here while your laptop runs only Chromium. - Upload the HTML report as an artefact when the run fails. The report opens by itself only on failures locally; in CI you grab it as a file.
Put the Supabase test URL and keys in your CI provider's secrets. Pull-request runs from forks usually don't get them, so decide up front whether those PRs run the E2E job at all.
I haven't put a run-time table in here. A figure from someone else's suite tells you nothing about yours, and the useful number is your own trend: read the duration line at the end of each run and watch it move as specs are added. If it creeps, shard it or trim the suite per the section above.
If you'd rather have the test setup, the data reset and the pipeline wired in from the first commit of a build, that's a normal part of our bespoke web development work.
Letting coding agents write tests safely
Agents are decent at writing Playwright specs and bad at knowing whether the spec proves anything. A test that clicks around and asserts that a heading exists will pass on a broken page. The setup has to constrain them.
Playwright ships tooling that fits this. The test generator records your actions and writes locators for you. The Playwright CLI is a command-line interface for browser automation designed for coding agents, with token-efficient commands and installable skills (npm install -g @playwright/cli ). Its docs compare it with MCP: the CLI defaults to headless with a lower token cost, while MCP defaults to headed and carries tool schemas and snapshots in context (CLI docs). Playwright MCP also supports WebMCP by default as of 1.64, and --no-webmcp opts out.
My rules for an agent working in the repo:
- It reads the existing page objects and fixtures first, and reuses them.
- It may add specs and page objects. It may not edit
playwright.config.ts, the auth setup or the reset script without a human reviewing that diff. - Every new spec asserts an outcome (a URL, a saved row, a visible confirmation), not just that something rendered.
- It runs the new spec with
--shuffleand on the logged-out project too, if the page is meant to be protected. - It never commits state files. The CLI's
state-savewrites cookies plus localStorage of every origin visited, and the docs say never to commit those files because they carry live authentication tokens (storage docs). Your.gitignoreentry forplaywright/.authshould cover wherever the agent writes them too.
For the wider case on tests as a guardrail around AI edits, see tests and AI coding tools. The Playwright part is above: small suite, fixed data, locked config.
FAQ
Do I need to run all three browsers on every pull request?
No. The default is all three, but you can mark Firefox and WebKit default: false and run Chromium on pull requests, saving the full --project=\"*\" run for merges to main or a nightly job. That's a judgement about risk and speed, not a Playwright rule.
Why did the HTML report not open after my run?
It only opens automatically when there are failures. After a clean run, open it yourself with npx playwright show-report.
My login only works the first time. What now?
The stored state has probably expired, or the setup project did not run (UI mode skips it by default). Delete the saved file and run auth.setup.ts again.
Do I need the `instant()` helper?
Only if you use Cache Components and care about what appears immediately after navigation, before dynamic content streams in. Otherwise ordinary assertions with web-first waiting are enough.
Start with a small suite on a production build, one login saved by a setup project, and a data reset you trust. The sharpest caveat: the saved auth file is a live credential, so keep playwright/.auth out of git and out of any agent's commits.