Next.jsMedium

How do you write end-to-end tests with Playwright or Cypress for Next.js?

Build and start the app (next build && next start), point Playwright or Cypress at it, and script real user flows: visit pages, click links, fill forms, and assert on visible, accessible content and URLs. Playwright's webServer option can start the server automatically, which is the setup the Next.js docs show.

Playwright setup

  1. npm init playwright@latest.
  2. In playwright.config.ts, set webServer: { command: "npm run build && npm run start", url: "http://localhost:3000", reuseExistingServer: !process.env.CI } and use.baseURL.
  3. Write tests with locators such as page.getByRole("link", { name: "Pricing" }).
  4. Run npx playwright test; use --ui and traces to debug.

What to test end to end

  • Critical journeys: sign-up, login, checkout, search.
  • Async Server Components, Server Functions, redirects and auth guards, which unit tests cannot cover well.
  • Streaming and loading states: Playwright auto-waits for elements.
  • Instant navigations: instant() from @next/playwright (Next.js 16.3) holds back dynamic content so you can assert that the prefetched UI shows immediately after a click.

Cypress

npx cypress open, set baseUrl, use cy.visit, cy.findByRole (Testing Library plugin), cy.intercept for network stubs. Cypress also supports component testing for Client Components.

Good practices

  • Test against a production build; dev mode has no prefetching and different caching.
  • Seed a test database or mock external APIs at the network level (MSW, page.route).
  • Use storageState to reuse an authenticated session across tests.
  • Run in CI with sharding and keep traces and videos for failures.

Code example

tsx
1// playwright.config.ts
2import { defineConfig, devices } from "@playwright/test";
3
4export default defineConfig({
5 testDir: "./e2e",
6 use: { baseURL: "http://localhost:3000", trace: "on-first-retry" },
7 webServer: {
8 command: "npm run build && npm run start",
9 url: "http://localhost:3000",
10 reuseExistingServer: !process.env.CI,
11 timeout: 180_000,
12 },
13 projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
14});
15
16// e2e/auth.spec.ts
17// import { test, expect } from "@playwright/test";
18// test("redirects anonymous users to login", async ({ page }) => {
19// await page.goto("/dashboard");
20// await expect(page).toHaveURL(/\/login\?next=%2Fdashboard/);
21// await page.getByLabel("Email").fill("ada@example.com");
22// await page.getByLabel("Password").fill("correct horse battery");
23// await page.getByRole("button", { name: "Sign in" }).click();
24// await expect(page.getByRole("heading", { name: /welcome back/i })).toBeVisible();
25// });

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app