Skip to content

Add end-to-end tests to a Next.js app

This guide adds Playwright end-to-end tests to an existing Next.js app, runs them against a production build locally and in CI, and then reuses the same tests against a preview deployment.

From the project root:

Terminal window
npm init playwright@latest

Choose TypeScript and a tests folder. Add the generated test-results/, playwright-report/, and playwright/.auth/ folders to .gitignore.

Test the production build, not the development server. Development mode compiles routes on first request and shows overlays that a production build never renders, which makes tests slower and less representative.

playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
const port = 3000;
export default defineConfig({
testDir: './tests',
retries: process.env.CI ? 2 : 0,
use: {
baseURL: process.env.BASE_URL ?? `http://localhost:${port}`,
trace: 'on-first-retry',
},
// Skip the local server when BASE_URL points at a deployed preview.
webServer: process.env.BASE_URL
? undefined
: {
command: `npm run build && npm run start -- --port ${port}`,
url: `http://localhost:${port}`,
reuseExistingServer: !process.env.CI,
timeout: 180_000,
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});

Locate elements the way a user finds them: by role, label, and visible name. These survive markup and styling changes that break CSS selectors.

tests/home.spec.ts
import { test, expect } from '@playwright/test';
test('visitor can reach pricing from the home page', async ({ page }) => {
await page.goto('/');
await page.getByRole('navigation').getByRole('link', { name: 'Pricing' }).click();
await expect(page).toHaveURL(/\/pricing$/);
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
});

Run it with npx playwright test, or npx playwright test --ui to watch it step by step.

page.route() intercepts requests made by the browser: client components, fetch in event handlers, and client-side data libraries. It cannot see requests made on the server by Server Components, Route Handlers, or Server Actions. For those, point the app at a test backend through its environment configuration rather than trying to intercept from the browser.

test('shows an empty state when search has no results', async ({ page }) => {
await page.route('**/api/search?**', (route) => route.fulfill({ json: { results: [] } }));
await page.goto('/search');
await page.getByRole('searchbox').fill('nothing matches this');
await expect(page.getByText('No results')).toBeVisible();
});

Log in through the real UI in a setup project, save the browser state, and let other tests start signed in. Keep test credentials in CI secrets and use a dedicated test account.

tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
const authFile = 'playwright/.auth/user.json';
setup('sign in', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill(process.env.E2E_USER_EMAIL!);
await page.getByLabel('Password').fill(process.env.E2E_USER_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL(/\/dashboard/);
await page.context().storageState({ path: authFile });
});
// playwright.config.ts, replacing the projects entry
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
],

Use the workflow in Run Playwright tests on every pull request with GitHub Actions as written: the webServer block builds and starts the app inside the job. Pass any environment variables your build needs as repository secrets, not values in the workflow file.

If the app deploys to Vercel, also run the suite against each preview deployment, where the real environment variables, middleware, and edge configuration apply. Because the config above reads BASE_URL, the same tests, including the signed-in setup project, run unchanged from a workflow in this repository; give that workflow the same test-account secrets. See Run Playwright tests against a Vercel preview deployment. QualityMax-managed suites are separate: they run scripts stored in QualityMax, not this repository’s Playwright config.

Hand-written tests cover the journeys you already know about. QualityMax can crawl the running app, propose test cases for the journeys it finds, and generate Playwright scripts for the ones you approve. Review each generated test and its first execution before counting it as coverage.

Coming from Cypress? See Cypress to Playwright.