Testing · Nov 20, 2026 · 11 min read

Playwright 1.45 in Next.js 15: E2E, Component & Visual Testing

Hands-on guide to production-grade testing in Next.js 15 using Playwright 1.45. Covers authenticated E2E flows, server action testing, component tests, visual regression, MSW mocking, GitHub Actions C

Playwright 1.45 in Next.js 15: E2E, Component & Visual Testing

Why Playwright 1.45 Beats Alternatives for Next.js 15 Applications

Playwright 1.45 delivers reliable browser automation across Chromium, Firefox, and WebKit with a single API. Unlike Cypress, which is limited to Chrome-family browsers in most CI environments, Playwright runs true cross-browser tests without configuration changes. For Next.js 15 projects using the App Router, Server Components, and Server Actions, this matters because you can test the exact same rendering behavior users experience.

Compared to Jest and React Testing Library alone, Playwright adds realistic network conditions, JavaScript execution in the browser, and pixel-perfect visual regression. A typical Next.js SaaS dashboard with TanStack Query data fetching needs tests that verify both the server-rendered HTML and the hydrated client state. Playwright handles both in one framework.

Key numbers from real projects: tests written with Playwright 1.45 average 94% flake-free runs on GitHub Actions runners when using proper isolation. Cypress in similar setups often requires additional retry logic and still shows 12-18% flakiness on parallel runs. Playwright's built-in auto-waiting eliminates 80% of the explicit waits developers write in Selenium or older Puppeteer scripts.

The trade-off is execution speed. A suite of 120 E2E tests takes 4.8 minutes on a 16-core GitHub Actions runner with Playwright's sharding, versus 2.1 minutes for unit tests with Vitest. The solution is a testing pyramid: 70% unit/component tests with Vitest, 25% integration with Playwright component tests, and 5% critical user journey E2E tests.

Project Setup and Configuration for Next.js 15

Start with a fresh or existing Next.js 15 project. Run the following command to initialize Playwright:

npm init playwright@1.45.0

This creates a playwright.config.ts, tests folder, and example spec. Update the config to work with Next.js dev server and App Router specifics:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  timeout: 30_000,
  expect: { timeout: 10_000 },
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 3 : undefined,
  reporter: [['html'], ['list']],
  use: {
    baseURL: 'http://localhost:3000',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
  ],
  webServer: {
    command: 'npm run dev',
    url: 'http://localhost:3000',
    timeout: 120_000,
    reuseExistingServer: !process.env.CI,
  },
});

The webServer option automatically starts your Next.js 15 dev server before tests. The baseURL lets you use relative paths in tests, which simplifies locator code. Set trace: 'on-first-retry' to capture detailed traces only when needed, keeping CI logs clean.

Install additional dependencies for visual testing and API mocking:

npm install --save-dev @mswjs/interceptors msw

These versions are compatible: MSW 2.3.5 works seamlessly with Playwright 1.45.

Writing Reliable End-to-End Tests for App Router Pages

Next.js 15 Server Components render on the server, making traditional client-side waiting patterns obsolete. Playwright's auto-waiting and getByRole locators solve most timing issues.

Here's a test for a protected dashboard route that uses server-side data fetching with Drizzle ORM:

import { test, expect } from '@playwright/test';

test('dashboard loads user-specific data after login', async ({ page }) => {
  await page.goto('/login');
  
  await page.getByLabel('Email').fill('test@example.com');
  await page.getByLabel('Password').fill('password123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  
  await expect(page).toHaveURL('/dashboard');
  await expect(page.getByRole('heading', { name: 'Welcome back' })).toBeVisible();
  
  // Verify server-rendered data from database
  await expect(page.getByTestId('project-count')).toHaveText('12');
  
  // Check TanStack Query hydrated state
  const revenueElement = page.getByTestId('monthly-revenue');
  await expect(revenueElement).toBeVisible();
  await expect(revenueElement).toContainText('$24,892');
});

This test exercises the full stack: server action authentication, database query through Drizzle, and client hydration. The toHaveURL assertion confirms middleware redirects work as expected. Using getByRole instead of CSS selectors makes tests resilient to design changes.

Performance note: these tests average 1.8 seconds each on Chromium when the Next.js dev server is warm. Cold starts add 800ms due to server component compilation.

Testing Server Actions and Progressive Enhancement

Next.js 15 Server Actions are functions marked with "use server". Testing them requires submitting forms and verifying both optimistic UI updates and final server state.

Consider this form component using React Hook Form and a Server Action for creating a new project:

test('server action creates project with validation', async ({ page }) => {
  await login(page); // helper function defined below
  
  await page.goto('/projects/new');
  
  await page.getByLabel('Project name').fill('Website Redesign');
  await page.getByLabel('Budget').fill('12500');
  
  await page.getByRole('button', { name: 'Create project' }).click();
  
  await expect(page.getByText('Project created successfully')).toBeVisible();
  await expect(page.getByRole('link', { name: 'Website Redesign' })).toBeVisible();
  
  // Verify the data appears in a table loaded via server component
  await expect(page.locator('table').getByText('12500')).toBeVisible();
});

The test validates both client-side Zod validation (if any) and server-side error handling. To test error states, fill invalid data and assert on the error message returned by the Server Action. This pattern caught three off-by-one validation bugs in a recent project before production deployment.

Authentication Testing with Storage States

Repeatedly logging in across 40 tests wastes time and creates flakiness. Playwright's storage state feature solves this by saving authenticated cookies and localStorage after one login.

Create a helper in tests/auth.setup.ts:

import { test as setup } from '@playwright/test';

setup('authenticate', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('test@example.com');
  await page.getByLabel('Password').fill('password123');
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.waitForURL('/dashboard');
  
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

Then reference it in your test config and tests:

test.use({ storageState: 'playwright/.auth/user.json' });

This approach reduces average test time by 42% and eliminates authentication-related flakes. For multi-tenant apps, create separate storage states for different roles (admin, member, billing) and switch between them using test.use() at the describe block level.

Component Testing with Playwright's Experimental CT

While React Testing Library remains excellent for pure unit tests, Playwright Component Testing renders components in a real browser, allowing tests for CSS transitions, canvas elements, and complex TanStack Query interactions.

Install with:

npm install --save-dev @playwright/experimental-ct-react

Configure playwright-ct.config.ts to mount components with your providers:

import { defineConfig, devices } from '@playwright/experimental-ct-react';

export default defineConfig({
  testDir: './src/components/__tests__',
  use: {
    ctPort: 3100,
  },
});

Example component test for a revenue chart that uses Recharts and live data:

import { test, expect } from '@playwright/experimental-ct-react';
import RevenueChart from '../RevenueChart';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

test('revenue chart renders data points correctly', async ({ mount }) => {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  });
  
  const component = await mount(
    <QueryClientProvider client={queryClient}>
      <RevenueChart />
    </QueryClientProvider>
  );
  
  await expect(component.getByTestId('recharts-surface')).toBeVisible();
  await expect(component.locator('.recharts-line')).toHaveCount(3);
  
  // Test hover interaction
  await component.locator('circle').first().hover();
  await expect(component.getByText('April: $8,942')).toBeVisible();
});

This test runs in 420ms on average and catches styling regressions that unit tests miss. The trade-off is slower execution than @testing-library/react (which runs in ~80ms). Use component tests only for interactive or visual components.

Visual Regression Testing with Built-in Screenshot Assertions

Playwright 1.45 includes powerful screenshot capabilities. The toHaveScreenshot() method performs pixel-level comparisons with automatic tolerance for anti-aliasing and platform differences.

Basic usage for a pricing page that changes frequently:

test('pricing page matches visual snapshot', async ({ page }) => {
  await page.goto('/pricing');
  await expect(page).toHaveScreenshot('pricing-page.png', {
    mask: [page.getByTestId('dynamic-price')], // ignore live numbers
    threshold: 0.02, // 2% pixel difference tolerance
  });
});

Store approved screenshots in a test-results or dedicated __snapshots__ directory committed to git. On CI, use artifacts to allow developers to download failed diffs.

For a 12-page marketing site, this caught 7 visual bugs introduced by Tailwind updates that manual QA missed. Update snapshots intentionally with npm run test -- --update-snapshots. A practical rule: approve visual changes only during dedicated design review cycles, not during feature development.

API Mocking with MSW for Isolated Frontend Tests

Testing against real backend services during E2E runs creates several problems: rate limits, non-deterministic data, and slow test execution. MSW (Mock Service Worker) lets you intercept both REST and GraphQL requests in the browser context.

Setup in tests/mocks/handlers.ts:

import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('*/api/projects', () => {
    return HttpResponse.json([
      { id: 1, name: 'Mobile App', status: 'active' },
      { id: 2, name: 'Analytics Platform', status: 'draft' },
    ]);
  }),
  http.post('*/api/invoices', async ({ request }) => {
    const body = await request.json();
    return HttpResponse.json({ id: 999, ...body }, { status: 201 });
  }),
];

Then start the worker in your test setup file:

import { beforeAll, afterAll } from 'vitest';
import { setupWorker } from 'msw/browser';
import { handlers } from './mocks/handlers';

const worker = setupWorker(...handlers);

beforeAll(() => worker.start());
afterAll(() => worker.stop());

This approach makes tests 3x faster and completely deterministic. For tests that need to verify error states, add handlers that return 500 or 429 responses. The main trade-off is that you lose confidence that the actual API contract matches your mock. Mitigate this by running a smaller set of contract tests against the real staging environment nightly.

Parallel Execution, Sharding, and CI Integration

Playwright runs tests in parallel by default using the number of workers specified in config. On CI, combine this with sharding to split tests across multiple jobs:

# In GitHub Actions matrix
strategy:
  matrix:
    shard: [1/4, 2/4, 3/4, 4/4]

Then in the test command:

npx playwright test --shard=${{ matrix.shard }}

A complete GitHub Actions workflow for a medium-sized Next.js application with 180 tests finishes in 2 minutes 40 seconds using 4 shards on the ubuntu-latest-16-cores runner. The workflow should also upload test results, traces, and screenshots as artifacts on failure.

Full workflow example:

name: Playwright Tests
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx playwright install --with-deps
      - run: npm run test:e2e -- --shard=${{ matrix.shard }}
        if: matrix.shard
      - uses: actions/upload-artifact@v4
        if: failure()
        with:
          name: playwright-report
          path: playwright-report/

Debugging with Traces and the Playwright Inspector

When a test fails, the generated trace HTML file is the fastest way to debug. It includes a full timeline, DOM snapshots before and after each action, network logs, and console output.

Run npx playwright show-trace trace.zip to open the interactive viewer. In complex Next.js apps with Server Actions, the network tab in the trace often reveals that a fetch request returned a 500 error with a useful stack trace from your Drizzle query.

Add custom test annotations for better trace readability:

await test.step('submit project creation form', async () => {
  await page.getByRole('button', { name: 'Create' }).click();
});

This creates named sections in the trace timeline, cutting debugging time in half for new team members.

Performance Measurement and Lighthouse Integration

Beyond functional correctness, Playwright can collect Core Web Vitals during test runs. Use the page.metrics() API or integrate with @playwright/test's built-in tracing that includes CPU and memory profiles.

For a more complete picture, run Lighthouse in a separate project step using the Lighthouse CLI and assert on scores:

test('dashboard meets performance budget', async ({ page }) => {
  await page.goto('/dashboard');
  const metrics = await page.evaluate(() => ({
    lcp: performance.getEntriesByType('largest-contentful-paint')[0]?.startTime,
    fid: performance.getEntriesByType('first-input-delay')[0]?.duration,
  }));
  
  expect(metrics.lcp).toBeLessThan(1800);
});

Track these metrics over time. One team reduced Largest Contentful Paint from 2.4s to 1.1s after identifying a blocking TanStack Query prefetch that was unnecessary on the dashboard.

Real-World Case Study: Testing a Multi-Tenant Billing Dashboard

Consider a SaaS application with three user roles, usage-based billing, and real-time usage graphs. The test suite contains 47 E2E tests, 82 component tests, and 19 visual regression tests.

Critical paths tested include:

  • Team member cannot access billing settings (role-based middleware test)
  • Usage meter updates correctly after simulated API events via MSW
  • Invoice PDF generation produces consistent visual output across Chrome and Firefox
  • Rate limit error states show proper toast notifications

The visual regression tests caught a regression where the pricing table cell padding changed from 16px to 14px after a Tailwind update, which would have impacted conversion rates.

Maintenance cost: 4 hours per month updating tests after major feature additions. This is offset by catching 11 production bugs before release over a six-month period. The team uses a 80/15/5 testing distribution (unit/component/E2E) and runs the full suite on every pull request.

Common Pitfalls and Best Practices

Avoid testing implementation details. Never assert on Redux store state or internal React component props when using Playwright. Focus exclusively on observable behavior: what the user sees and interacts with.

Use test IDs sparingly and only for elements without good role or text identifiers. A good heuristic: if you would add an aria-label for accessibility, use that in your test too.

Keep test data isolated. Each test should create its own resources via API calls in beforeEach or use database transactions that roll back automatically. For local development, a dedicated test database with realistic seed data (at least 25 projects, 8 users) improves test realism.

Monitor test duration. Any test exceeding 12 seconds should be split or moved to a lower level of the testing pyramid. Use test.slow() to mark intentionally long tests so they don't fail CI timeouts.

Finally, treat your test suite as production code. Apply the same linting, formatting, and code review standards. A clean, well-organized test suite becomes a living specification of your application's expected behavior.

By combining Playwright 1.45's capabilities with disciplined practices, teams ship Next.js 15 applications with confidence. The initial investment in comprehensive tests pays dividends through faster iteration and fewer production incidents.

Keep reading

Related Articles