Lesson 23 of 27Production Next.js
Testing Next.js Apps
Decide what to test where in a Next.js app: Vitest for logic and Client Components, direct calls for actions and handlers, Playwright for the rest.
A team ships a refactor of the checkout page. Every unit test is green, because every test mocks the database, the session and the payment client. In production, the Server Action reads cookies() before the user is signed in, throws, and nobody can buy anything for forty minutes. Next.js apps are hard to test in a naive way because so much of the work happens across a boundary: server and client, render and request, your code and the framework. This lesson gives you a map of which tool tests which layer, how to test Server Actions and Route Handlers as plain functions, and how to run Playwright against a real production build in CI.
What to test where
You already know the testing trophy from Testing React and the Design & Architecture course's Testing Strategy. The Next.js twist is that some of your code cannot be rendered in a unit test at all, and some of it can only be trusted when the real framework runs it. Sort every file in app/ and lib/ into one of five buckets:
| Code | Tool | Why |
|---|---|---|
| Pure logic: pricing, Zod schemas, formatters, DTO mappers | Vitest, node environment | Fast, deterministic, no framework involved |
| Client Components and hooks | Vitest + React Testing Library, jsdom | Interaction and state, rendered in isolation |
| Server Actions and the data access layer | Vitest, node environment, real test database | They are async functions; call them directly |
| Route Handlers | Vitest, call the exported GET or POST | They take a Request and return a Response |
| Async Server Components, layouts, streaming, caching, proxy | Playwright against next build && next start | Only the real framework renders them correctly |
The row people get wrong is the last one. The official Next.js testing guide says it plainly: async Server Components are new to the React ecosystem and Vitest does not support rendering them. You can unit-render a synchronous Server Component, but the moment it awaits data, test it end to end. That is not a loss. An async Server Component is mostly "fetch, then render", so test the fetch (your data access function) in Vitest and the render in Playwright. Keep the component itself thin.
Match each piece of code to the cheapest test that gives real confidence.
Setting up Vitest for a Next.js project
The setup from the Next.js docs is short: vitest, @vitejs/plugin-react, jsdom, @testing-library/react, @testing-library/dom, and vite-tsconfig-paths so your @/ imports resolve.
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({
plugins: [tsconfigPaths(), react()],
test: {
environment: "node", // default for logic, actions and handlers
setupFiles: ["./test/setup.ts"],
alias: {
// "server-only" throws outside the react-server build; make it a no-op in tests
"server-only": new URL("./test/empty.ts", import.meta.url).pathname,
},
},
});test/setup.ts is the same file as in Testing React: the jest-dom matchers import plus afterEach(() => cleanup()), so each component test starts with an empty page.
Two details in that file save hours.
Pick the environment per file. Most of your tests should run in plain Node, which is faster and has a real fetch, Request and Response. Component tests opt into the DOM with a comment at the top of the file: // @vitest-environment jsdom. Running everything in jsdom hides bugs, because jsdom's globals are not the ones your server code sees in production.
Neutralise server-only. Your data access layer starts with import "server-only", which is exactly right in the app: it turns an accidental client import into a build error. But the package works by throwing when it is loaded outside the React Server build condition, and Vitest is not that build. Alias it to an empty file (as above) or mock it with vi.mock("server-only", () => ({})). If you see "This module cannot be imported from a Client Component module" in a test run, this is why.
Client Components that call useRouter, usePathname or useSearchParams from next/navigation need those hooks mocked, because there is no App Router mounted in a unit test. Mock the module and return what the test needs:
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { vi, test, expect } from "vitest";
import { FilterPanel } from "./filter-panel";
const replace = vi.fn();
vi.mock("next/navigation", () => ({
useRouter: () => ({ replace }),
usePathname: () => "/shop",
useSearchParams: () => new URLSearchParams("color=red"),
}));
test("ticking a size updates the URL without adding history", async () => {
render(<FilterPanel sizes={["S", "M"]} />);
await userEvent.click(screen.getByRole("checkbox", { name: "M" }));
expect(replace).toHaveBeenCalledWith("/shop?color=red&size=M", { scroll: false });
});The assertion is on the URL the component asked for, not on internal state. That is the behaviour a user and a teammate care about.
render(await ProductPage({ params: Promise.resolve({ id: '1' }) })) in Vitest to test an async Server Component. It sometimes passes and sometimes breaks after upgrades. What is the better approach?Testing Server Actions as functions
A Server Action is an exported async function with a "use server" directive. In a test it is just a function, so call it. What makes it awkward is that it usually touches three framework services: the session (via cookies()), the cache (revalidatePath, updateTag) and navigation (redirect). The trick is to design the action so those are easy to replace.
"use server";
import { z } from "zod";
import { updateTag } from "next/cache";
import { getSession } from "@/lib/auth";
import { db } from "@/lib/db";
const DeleteInput = z.object({ postId: z.string().uuid() });
export async function deletePost(_prev: unknown, formData: FormData) {
const session = await getSession();
if (!session) return { ok: false, error: "Sign in first" };
const parsed = DeleteInput.safeParse({ postId: formData.get("postId") });
if (!parsed.success) return { ok: false, error: "Invalid post" };
const deleted = await db.post.deleteMany({
where: { id: parsed.data.postId, authorId: session.userId },
});
if (deleted.count === 0) return { ok: false, error: "Not found" };
updateTag(`posts:${session.userId}`);
return { ok: true };
}In the test, mock your own auth module and next/cache, but keep the database real:
import { vi, test, expect, beforeEach } from "vitest";
import { deletePost } from "./actions";
import { db } from "@/lib/db";
import { getSession } from "@/lib/auth";
vi.mock("@/lib/auth", () => ({ getSession: vi.fn() }));
vi.mock("next/cache", () => ({ updateTag: vi.fn() }));
beforeEach(async () => {
await db.post.deleteMany();
await db.post.create({ data: { id: "6f1c...", authorId: "alice", title: "Hi" } });
});
test("a user cannot delete someone else's post", async () => {
vi.mocked(getSession).mockResolvedValue({ userId: "bob" });
const form = new FormData();
form.set("postId", "6f1c...");
expect(await deletePost(null, form)).toEqual({ ok: false, error: "Not found" });
expect(await db.post.count()).toBe(1);
});Why a real database? The bug that matters in this action is the authorId in the where clause. If you mock db.post.deleteMany to return { count: 1 }, the test passes whether or not the query is scoped to the author, and it would pass on the day someone deletes that line. Run Postgres in Docker in CI (or a Testcontainers instance per test run), apply migrations once, and reset tables between tests. A transaction rolled back after each test is faster still if your ORM supports it.
Remember from Securing a Next.js App that every action is a public POST endpoint. The most valuable action tests are therefore the hostile ones: signed out, wrong user, malformed input, an ID that does not exist. The happy path is often already covered by your E2E test.
Here is the same idea without any framework, so you can see the shape of an authorization test. The fake database honours the where clause, which is the whole point.
Press Run (⌘ Enter) to see what happens.redirect and notFound in tests
redirect() and notFound() work by throwing a special error that the framework catches. In a direct call there is no framework to catch it, so the promise rejects. That is useful: assert on it. The thrown error carries a digest string that starts with NEXT_REDIRECT (and includes the target URL) or NEXT_HTTP_ERROR_FALLBACK;404. Treat those strings as framework internals that can change, so wrap the check in one test helper rather than repeating it in every file. Better still, mock next/navigation and assert that redirect was called with the expected path.
Testing Route Handlers
A Route Handler is the easiest thing in Next.js to test, because it speaks web standards. Import the exported function, build a Request, await the Response. Dynamic segments arrive as the second argument, and params is a Promise in Next.js 16.
import { test, expect } from "vitest";
import { GET } from "./route";
test("returns 404 for an unknown order", async () => {
const req = new Request("http://localhost/api/orders/999", {
headers: { authorization: "Bearer test-token" },
});
const res = await GET(req, { params: Promise.resolve({ id: "999" }) });
expect(res.status).toBe(404);
expect(await res.json()).toEqual({ error: "Order not found" });
});If the handler is typed to take a NextRequest (because it reads request.nextUrl or request.cookies), construct one with new NextRequest(url, init) from next/server. For webhooks, write one test that signs the body with your test secret and one that sends a bad signature, and check the bad one returns 400 before touching the database.
proxy.ts is harder to unit test because what matters is mostly which requests it runs on. Next.js ships helpers under next/experimental/testing/server (such as unstable_doesMiddlewareMatch to check a matcher against a URL). They are marked unstable, so check the current docs before relying on them, and prefer covering real proxy behaviour, like a signed-out redirect, in an E2E test.
End-to-end with Playwright against a production build
Run E2E tests against next build && next start, not next dev. The dev server compiles routes on first request (so the first test to hit a page is slow and flaky), shows the error overlay instead of your error.tsx, logs extra warnings, and does not prerender, so caching and static shells behave differently. The bug you are hunting is the one that only appears in production; test production.
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./e2e",
retries: process.env.CI ? 2 : 0,
use: { baseURL: "http://localhost:3000", trace: "on-first-retry" },
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
webServer: {
command: "npm run build && npm run start",
url: "http://localhost:3000",
reuseExistingServer: !process.env.CI,
timeout: 180_000,
},
});Seed data deliberately. A globalSetup file migrates and seeds the test database once. Tests that create data use unique values (an email with a random suffix) so they can run in parallel without colliding. Sign in once in a setup project and save storageState to a file, so each test starts already authenticated instead of clicking through the login form forty times.
Mocking third-party APIs is the classic trap. Playwright's page.route() intercepts requests made by the browser. In a Next.js app, the call to Stripe or your CMS usually happens on the server, inside a Server Component or action, so page.route() never sees it.
Playwright drives a real browser.
You have three workable options for server-side calls. Point the server at a stub service through an environment variable (STRIPE_API_BASE=http://localhost:4010 in the test build), which is simple and honest. Start MSW's Node server from instrumentation.ts only when a test flag is set. Or use Next.js's experimental test mode (next/experimental/testmode/playwright), which gives each test a next.onFetch hook to answer server-side fetch calls. The last one is experimental, so weigh it like any experimental API.
page.route('**/api.cms.com/**', ...) to return fake articles, but the page still shows real CMS content. Why?Testing instant navigations (16.3 and later)
If the app uses Cache Components, you can lock in "this page shows its shell instantly" as a test. The instant() helper from @next/playwright holds back dynamic content for the duration of a callback, so your assertions only see what was prerendered or prefetched:
import { test, expect } from "@playwright/test";
import { instant } from "@next/playwright";
test("product page has an instant shell on client navigation", async ({ page }) => {
await page.goto("/store/shoes");
await instant(page, async () => {
await page.click('a[href="/store/hats"]');
await page.waitForURL((url) => url.pathname === "/store/hats");
await expect(page.locator("h1")).toContainText("Baseball Cap");
await expect(page.getByText("In stock")).toHaveCount(0); // dynamic, not yet streamed
});
await expect(page.getByText("In stock")).toBeVisible();
});The testing API is on automatically in next dev; for a production build, Next.js has a config flag to expose it for the test build only (check the current Instant Navigation guide for its name and caveats). The Streaming, Loading UI and Instant Navigations lesson covers how to design the boundaries these tests protect.
Tests in CI
A Next.js pipeline that catches real problems runs cheap checks first and expensive ones last, so a typo fails in thirty seconds rather than eight minutes.
jobs:
check:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env: { POSTGRES_PASSWORD: test }
ports: ["5432:5432"]
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with: { node-version: 24, cache: npm }
- run: npm ci
- run: npx next typegen && npx tsc --noEmit
- run: npx eslint .
- run: npx vitest run
- run: npx playwright install --with-deps chromium
- run: npx playwright testA few Next.js specifics:
- Lint with the ESLint CLI.
next lintwas removed in Next.js 16. Useeslint .witheslint-config-nextin a flat config. - Generate route types before type checking.
next typegenwrites thePageProps,LayoutPropsand route types thattscneeds, without running a full build.next buildalso type checks, but failing fast is cheaper. - Cache the build.
next buildkeeps a cache in.next/cache; restoring it between CI runs makes rebuilds much faster. - E2E on previews. On Vercel or any platform with preview deployments, a second job can run the Playwright suite against the preview URL. That tests the real hosting (CDN, functions, environment variables) and catches "works in CI, broken on the platform" bugs.
- Quarantine flakes. Retries hide flakiness; they do not fix it. Track tests that pass only on retry and fix the cause, which in Next.js is usually waiting on a fixed timeout instead of a URL or a visible element.
Order the CI steps so the cheapest failures are caught first.
- Tap the steps below in the right order.
What does this print?
const results = [
{ name: "checkout", attempts: ["fail", "pass"] },
{ name: "search", attempts: ["pass"] },
{ name: "login", attempts: ["fail", "fail", "pass"] },
{ name: "profile", attempts: ["pass"] },
];
const flaky = results.filter((r) => r.attempts.length > 1 && r.attempts.at(-1) === "pass");
console.log(flaky.map((r) => r.name).join(","));- test environment
- The globals a test runs with in Vitest:
nodefor server code,jsdomfor components that need a DOM. Set per file with a@vitest-environmentcomment. - server-only
- A package imported at the top of server modules that makes a client import fail the build. It throws in plain test runners, so alias or mock it in tests.
- webServer
- Playwright config that starts the app (for example
next build && next start) and waits for its URL before running tests. - storageState
- A saved file of cookies and storage that lets Playwright tests start already signed in.
- instant()
- A helper from
@next/playwright(Next.js 16.3+) that holds back dynamic content so a test can assert on the shell a navigation shows immediately. - flaky test
- A test that passes and fails on the same code. Retries hide it; the cause is usually a timing assumption.