End-to-end testing with Playwright
Drive a real browser against a production build with Playwright, reuse a logged-in state, and test the flows unit tests cannot reach.
End-to-end testing with Playwright
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- End-to-end tests run a real browser against a running app and are the way to test async Server Components, Server Actions and caching together.
- Test a production build (`next build` then `next start`), not the dev server, and let Playwright's `webServer` option start it in CI.
- Log in once in a setup step, save the browser state, and let tests start already authenticated instead of typing credentials every time.
- Prefer `getByRole` locators and Playwright's retrying `expect` over CSS selectors and fixed sleeps.
What unit tests cannot see
Your unit tests pass. The login form’s component test passes, the session helper’s test passes. And production login is broken, because the proxy redirects to a page that does not exist, or a Server Action throws on a missing environment variable. No unit test could notice, because none of them ran the whole system.
An end-to-end (E2E) test drives a real browser against a running copy of your app, the way a user would: open a page, click, type, and check what appears. It is slow compared with a unit test and it breaks for more reasons, so you write fewer of them and aim them at the flows that matter: sign up, log in, check out. It is also the only way to test async Server Components, Server Actions and caching behavior together, which unit tests cannot reach.
Playwright
Playwright is the tool the Next.js docs lead with. It runs your tests in Chromium, Firefox and WebKit, so one test file covers three engines. The fastest start is the official with-playwright example, or you add it to an existing project and write a test:
// tests/example.spec.ts
import { test, expect } from "@playwright/test";
test("navigates to the about page", async ({ page }) => {
await page.goto("/");
await page.getByRole("link", { name: "About" }).click();
await expect(page).toHaveURL("/about");
await expect(page.getByRole("heading", { level: 1 })).toContainText("About");
});
Using page.goto("/") works once baseURL is set in playwright.config.ts. getByRole finds elements the way a screen reader would, which makes tests resilient to markup changes. Prefer it over CSS selectors.
Run it against a production build
The docs recommend testing production code, not the dev server. A dev server compiles on demand, has different caching, and shows overlays and warnings that real users never see. The sequence is npm run build, npm run start, and then npx playwright test in another terminal. To avoid doing that by hand, Playwright’s webServer option can start the server for you and wait until it responds; point its command at npm run build && npm run start in CI.
This is also where Next.js 16 details bite. If you enable Cache Components, tests of what appears immediately after a navigation, before dynamic content streams in, use the instant() helper from @next/playwright, as described in the instant navigation guide. If you use it on a production build, the docs say to set EXPOSE_TESTING_API=1 when you build and start the test server.
Logging in without logging in every test
Most interesting pages are behind auth. Typing credentials into the form before every test is slow and makes every test depend on the login page. The standard pattern is a setup step that logs in once, saves the browser’s cookies to a file (Playwright calls this storageState), and lets each test start already authenticated. Tests for protected routes then begin on the page they care about. You still write one test that exercises the login form itself, and a test that an unauthenticated visitor is redirected.
In Playwright the setup step is a project that other projects depend on:
// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
use: { baseURL: "http://localhost:3000" },
projects: [
{ name: "setup", testMatch: /auth\.setup\.ts/ },
{
name: "chromium",
use: { ...devices["Desktop Chrome"], storageState: ".auth/user.json" },
dependencies: ["setup"],
},
],
webServer: {
command: "npm run build && npm run start",
url: "http://localhost:3000",
reuseExistingServer: !process.env.CI,
},
});
// tests/auth.setup.ts
import { test as setup, expect } from "@playwright/test";
setup("sign in", async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Password").fill("hunter2");
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page).toHaveURL("/dashboard");
await page.context().storageState({ path: ".auth/user.json" });
});
To test the signed-out case, wrap a test in test.describe with test.use({ storageState: { cookies: [], origins: [] } }). I ran this against a small Next.js 16.4.6 app with a Server Action login and a cookie-guarded /dashboard, on Playwright 1.65.1: the setup, the signed-in test and the signed-out redirect test all passed. Add .auth/ to .gitignore, since that file holds a live session cookie.
That setup mirrors what the authentication lessons taught: the proxy is an optimistic redirect, and the data layer is the real check. An E2E test is the one place where you can prove both work together, and a good suite includes a “user A cannot open user B’s record” case.
Keep the suite honest
A few habits keep E2E suites from becoming flaky. Use Playwright’s built-in waiting, expect(...).toBeVisible() retries until the condition is true, instead of fixed sleeps. Keep tests independent so they can run in any order and in parallel. Seed the data a test needs rather than depending on whatever the last test left behind. And run them in CI on every pull request, or they quietly rot.
What the video covers
Aditya Singh’s “End-to-End Testing in Next.js 15 with Playwright: Authentication, Routes & Role-Based Access” is a 38-minute chaptered video from November 2024. It covers setup and configuration, tests for public routes, tests for protected routes, global authentication setup, a hybrid strategy, and role-based features, which is the combination this lesson needs. It is on Next.js 15, and the app under test uses middleware-based auth, which is proxy.ts in Next.js 16, so the test code carries over but the app code needs the rename. Its linked repository is named playwright-nextauth, so the login it tests is Auth.js, which the previous lessons discussed. It is a small channel. Cosden Solutions’ 33-minute Playwright tutorial on a plain React app is listed under “deeper” for fundamentals.
Where this fits
Tests, like the rest of the app, are better when the code is typed. Next: TypeScript in Next.js.
Check yourself
Why should E2E tests run against a production build?
A dev server compiles on demand, caches differently and shows overlays real users never see, so a production build is closer to what ships.
What problem does saving the browser state after login solve?
It avoids logging in through the form before every test, which is slow and makes every test depend on the login page.
What should an auth-focused E2E suite prove that a unit test cannot?
That the proxy redirect and the data-layer checks work together, for example that an unauthenticated visitor is redirected and that one user cannot open another user's record.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.