Tested with next 16.4.6 (Turbopack), react 19.3.1, msw 3.0.8, @playwright/test 1.65.1 (Chromium), TypeScript 6.0.3 on Node 22.23.5; 24/24 Playwright tests passing, 2026-11-29 Repro: sgedda/devxtools-tutorials (nextjs-msw-checkout)
In the Next.js App Router, most of your fetch calls run on the server, where MSW’s browser service worker can’t see them. This tutorial mocks them anyway: one set of MSW handlers answers Server Components, a Server Action and a Route Handler in Node, plus a Client Component in the browser. A Playwright suite then tests a real checkout against a production build. Each of the five steps names a bug that usually only shows up in production, shows how to reproduce it, and pins the fix with a spec. Every snippet is copied from the sample app, and every claim below was run on the pinned versions. devxtools.dev is independent and has no relationship with Next.js, MSW or Playwright.
What you’ll build, and why server-side fetch needs a different MSW setup
The sample is a Northwind Supply checkout in the nextjs-msw-checkout/ folder of sgedda/devxtools-tutorials. The catalog page, the checkout Server Action and a receipt Route Handler call an upstream commerce API (http://127.0.0.1:4010) on the server. One Client Component, a shipping estimate, calls it from the browser. Nothing listens on that port: either MSW answers, or the request fails.
If your app only fetches from the browser (a Vite SPA, say), you don’t need any of this. Start with MSW in React with Playwright, which covers the service worker in depth. If you only want to stub requests inside one test, mocking APIs directly with Playwright page.route is simpler, but it only sees browser traffic too.
| Step | What it shows | Spec |
|---|---|---|
| 1 | A Server Component fetch answered by MSW in Node | e2e/nextjs-step-1-server-component-fetch.spec.ts |
| 2 | A client-side fetch answered by the service worker, same handler | e2e/nextjs-step-2-client-side-fetch.spec.ts |
| 3 | The Server Action charges the card and creates the order; a Route Handler reads it | e2e/nextjs-step-3-payment-call.spec.ts |
| 4 | Per-test overrides: declined card, slow provider, 500, outage, sold-out item | e2e/nextjs-step-4-per-test-overrides.spec.ts |
| 5 | The confirmation, then the catalog shows the reduced stock | e2e/nextjs-step-5-confirmation-and-caching.spec.ts |
Prerequisites and project setup
You need Node.js 22 or later. The sample pins next 16.4.6, react and react-dom 19.3.1, msw 3.0.8, @playwright/test 1.65.1 and typescript 6.0.3. TypeScript 7.0.2 didn’t work with this stack: tsc couldn’t see Next’s generated PageProps types, and typescript-eslint rejected it.
git clone -b nextjs-msw-checkout https://github.com/sgedda/devxtools-tutorials.git
cd devxtools-tutorials/nextjs-msw-checkout
npm install
npx playwright install chromium
npm run dev # http://localhost:3000, API mocked by MSW (Node + browser)
npm run test:e2e # builds and starts three servers, then runs every spec
npm run typecheck # next typegen && tsc --noEmit
Run next typegen (or a build) before tsc: route types are generated.
Start MSW in Node from instrumentation.ts
Next.js calls register() in src/instrumentation.ts once per server instance, before it handles requests. That’s where MSW’s Node server starts:
export async function register() {
// Only the Node.js runtime: msw/node can't run in the Edge runtime (and doesn't need to:
// this app has no Edge routes). The dynamic import keeps msw out of the Edge bundle.
if (process.env.NEXT_RUNTIME === 'nodejs' && process.env.MSW_ENABLED === 'true') {
const { startMockServer } = await import('./mocks/node')
startMockServer()
}
}
startMockServer() in src/mocks/node.ts calls setupServer(health, ...handlers) and server.listen() with a strict onUnhandledFrame: any request to the upstream API that no handler matches is an error. So a test that passes with no upstream running proves MSW answered every server-side call.
onUnhandledFrame({ frame, defaults }) {
if (frame.protocol !== 'http') return
const { request } = frame.data as { request: Request }
if (request.url.startsWith(API_URL)) defaults.error()
},
Two bundler traps, one config line each
Both bundlers work with MSW once next.config.ts has these lines:
// Load MSW from node_modules at runtime instead of bundling it into server chunks.
serverExternalPackages: ['msw'],
// ...
turbopack: {},
webpack(config, { isServer }) {
if (isServer) config.resolve.alias = { ...config.resolve.alias, 'msw/browser': false }
return config
},
- Turbopack dev crashes evaluating a bundled
msw/nodein a page’s server chunk (The "path" argument must be of type string … Received an instance of URL).serverExternalPackages: ['msw']makes Node load MSW fromnode_modulesinstead. next build --webpackfails withPackage path ./browser is not exported from package …/msw, because webpack resolves the browser-onlyimport('./browser')for the server bundle too. Aliasingmsw/browsertofalseon the server fixes it. Thewebpackhook then makes Next 16’s default Turbopack build refuse to run, so the config also needsturbopack: {}.
Playwright runs against next build && next start
The Playwright setup works like tutorial #1’s (Playwright webServer, traces on retry, video on failure), with one difference: the mocked server is a production build, npm run build:mocked && npm run start:mocked on :3000. Tests then see the caching you ship, and nothing compiles mid-test. On a cold next dev --webpack, the first Server Action compiled mid-test and assertions timed out (9, 8 and 11 of 12 passed on three cold starts). The full config, with an unmocked server on :3001 and a test-proxy server on :3003, is in the sample’s playwright.config.ts.
Run everything with npx playwright test. It should end with 24 passed. Each step below has a checkpoint that runs only its spec in the mocked project (Playwright still starts all three servers first, so expect it to take up to a minute).
Step 1: Mock a Server Component fetch
The prod bug: the catalog renders on the server, so the browser service worker never sees its request, and your “mocked” page quietly calls the real API or fails.
The catalog page is an async Server Component:
export default async function CatalogPage() {
const { products } = await apiFetch<{ products: Product[] }>('/catalog/products', catalogFetchInit())
// ...
}
The handler for GET /catalog/products waits 700 ms, so loading.tsx streams a skeleton first. The spec proves the data came from the server render: the browser makes zero requests to the upstream API.
const browserApiCalls: string[] = []
page.on('request', (request) => {
if (request.url().startsWith('http://127.0.0.1:4010')) browserApiCalls.push(request.url())
})
// Don't wait for `load`: by then the streamed catalog has replaced the skeleton.
await page.goto('/', { waitUntil: 'commit' })
// loading.tsx streams first while the mocked upstream takes ~700 ms.
await expect(page.getByTestId('product-skeleton').first()).toBeVisible()
const products = page.getByRole('list', { name: 'Products' }).getByRole('listitem')
await expect(products).toHaveCount(6)
// ...
// The data came from the server render: the browser made no request to the upstream API.
expect(browserApiCalls).toEqual([])
Gotcha: page.goto() waits for load, which fires only after the Suspense content has streamed in, so the skeleton is already gone. Use waitUntil: 'commit' to assert a loading.tsx state.
Checkpoint: npx playwright test nextjs-step-1 --project=mocked should report 1 passed.
Step 2: Mock a client-side fetch with the same handlers
The prod bug: you mock the server and the browser with two different fake APIs, they drift apart, and the shipping price in the form stops matching the price you charge.
ShippingEstimate is a Client Component that calls GET /shipping/quote from the browser. The same handler in src/mocks/handlers.ts answers it, this time through MSW’s service worker. src/mocks/browser.ts is the familiar setupWorker(...handlers), and mswReady() starts it once, before the first client fetch:
export function mswReady(): Promise<void> {
if (!browserMswEnabled || typeof window === 'undefined') return Promise.resolve()
ready ??= import('./browser').then(async ({ worker }) => {
await worker.start({ quiet: true, onUnhandledFrame: 'bypass' })
})
return ready
}
The browser learns whether mocking is on from NEXT_PUBLIC_MSW_ENABLED, which next.config.ts inlines at build time from MSW_ENABLED. Playwright can prove which side answered:
const quote = page.waitForResponse((r) => r.url().startsWith('http://127.0.0.1:4010/shipping/quote'))
await page.getByLabel('Postal code').pressSequentially('111 34', { delay: 60 })
await expect(page.getByTestId('shipping-loading')).toBeVisible()
// This request was made by the browser and answered by the service worker, not a server.
const response = await quote
expect(response.fromServiceWorker()).toBe(true)
Later, the checkout Server Action requests the same quote on the server, and the Node server answers it with the same handler.
Checkpoint: npx playwright test nextjs-step-2 --project=mocked should report 1 passed.
Step 3: Mock the payment call in a Server Action
The prod bug: the payment runs in a Server Action, which no browser-side mock can reach, so the most important call in your checkout is the one that’s never tested.
placeOrder() in src/app/checkout/actions.ts runs on the server. It re-reads the cart and the shipping quote (never trust prices from the browser), charges the card, creates the order and redirects:
const charge = await apiFetch<Charge>('/payments/charges', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount, last4: digits.slice(-4), idempotencyKey: values.idempotencyKey }),
})
order = await apiFetch<Order>('/orders', { method: 'POST', /* ... */ })
// ...
redirect(`/orders/${order.id}`)
All four upstream calls go through the MSW server started in instrumentation.ts. That works in next start and next dev, with Turbopack and webpack. The payment handler waits 1.1 s, so the pending state is visible:
await page.getByRole('button', { name: 'Pay $556.00' }).click()
// The mocked payment provider takes ~1.1 s, so the pending state is visible.
await expect(page.getByRole('button', { name: 'Processing payment…' })).toBeDisabled()
await expect(page).toHaveURL(/\/orders\/NW-10424$/)
const confirmation = page.getByTestId('order-confirmation')
await expect(confirmation.getByRole('heading')).toHaveText('Order NW-10424 confirmed')
await expect(page.getByTestId('confirmation-total')).toHaveText('$556.00')
A second test fetches the receipt Route Handler with page.request.get('/orders/NW-10424/receipt') and checks it reads the same mocked order (Total charged $556.00).
One React 19 gotcha: a <form action> is reset after the action runs, even when it fails, so a declined card would wipe what the customer typed. The checkout form submits manually inside startTransition(() => formAction(formData)) and uses controlled inputs instead.
Checkpoint: npx playwright test nextjs-step-3 --project=mocked should report 2 passed.
Step 4: Per-test overrides without leaking between workers
The prod bug: your declined-card test passes alone and fails in CI, because four workers share one Next.js server and one test’s override answers another test’s payment.
MSW runs inside the Next.js process, so a Playwright test can’t call server.use() on it, and every worker shares that one server. We measured the naive approach (a global server.use() and one shared mock database): 7 of 12 tests failed at 4 workers, with errors like another test’s order number and stock count, or an override wiped by another test’s resetHandlers().
The fix gives each test its own scope:
- The
mockApifixture sets a uniquemsw-test-idcookie per test (it includes a per-run id, so ids never repeat across runs). apiFetch()forwards it upstream asx-msw-test-id, only when MSW is on.- The handlers keep a separate seeded database and override list per id (
src/mocks/scope.ts). mockApi.use()registers a named scenario for that id through a test-only route,POST /api/test/msw, which returns 404 unlessMSW_ENABLED=true.
test('a declined card shows inline recovery and the retry succeeds', { tag: '@clip' }, async ({ page, mockApi, pace }) => {
await mockApi.use({ name: 'payment-declined', times: 1 })
await page.goto('/checkout')
await fillCheckout(page)
await page.getByRole('button', { name: 'Pay $556.00' }).click()
const banner = page.getByTestId('checkout-error')
await expect(banner).toContainText('Your card was declined')
await expect(banner).toContainText('HTTP 402 · card_declined')
// The failed Server Action didn't wipe the form.
await expect(page.getByLabel('Street address')).toHaveValue('Sveavägen 44')
// ...
// The scenario was registered with times: 1, so the retry reaches the default handler.
await banner.getByRole('button', { name: 'Try again' }).click()
await expect(page).toHaveURL(/\/orders\/NW-10424$/)
})
The same spec covers a slow payment provider (payment-slow, which the sample delays by 3.5 s unless a test sets delayMs), a retryable 500, a catalog outage that renders error.tsx and recovers on retry, and a 409 out_of_stock. In Next 16, error.tsx receives retry, not reset. Also filter getByRole('alert'): Next renders an empty role="alert" route announcer.
The trade-off: overrides are named scenarios defined in the app’s mock code (src/mocks/scenarios.ts), not handlers written inline in a test, because a test can’t ship a function into the server. In return, tests run fully parallel against one server. With per-test scopes, --workers=4 --repeat-each=3 passed 36/36.
Checkpoint: npx playwright test nextjs-step-4 --project=mocked should report 5 passed.
Try breaking it: run MSW_ISOLATION=global npx playwright test --project=mocked --workers=4 --retries=0. That switches the fixture to the shared, naive pattern, and several tests fail at once.
Step 5: Verify the confirmation and make sure caching doesn’t hide the mock
The prod bug: an order really reduced stock in the mock, but the catalog still shows the old number, because Next served a cached fetch, and the cache even survives a restart.
The /orders handler is stateful: placing an order reduces stock in that test’s copy of the mock backend. The spec checks the confirmation, goes back to the catalog with a client-side <Link>, and expects the new stock:
await confirmation.getByRole('link', { name: 'Back to catalog' }).click()
await expect(stockOf('Noise-cancelling headphones')).toHaveText('4 in stock')
await expect(stockOf('USB-C dock, 11-in-1')).toHaveText('28 in stock')
await expect(stockOf('Mechanical keyboard')).toHaveText('11 in stock')
That only passes because apiFetch() defaults to cache: 'no-store' for anything a test (or a user) can change:
// Fresh data by default: a cached response would hide what the mock returns now.
response = await fetch(`${API_URL}${path}`, {
...(init.next || init.cache ? {} : { cache: 'no-store' as const }),
...init,
headers,
})
With next: { revalidate: 60 } on the catalog fetch, the test gets “5 in stock” instead of “4”: the confirmation is right, but the Server Component read the data cache. The entries live in .next/cache/fetch-cache/ and were still served after a next start restart. The cache key includes request headers, so the x-msw-test-id header also gives each test its own entries.
Tag-based revalidation after the mutation (revalidateTag or updateTag) is the usual production alternative to no-store. We did not test it in this sample, so treat it as untested here. Prerendered shells and the client router cache didn’t hide any mock data in our runs.
Checkpoint: npx playwright test nextjs-step-5 --project=mocked should report 3 passed.
Try breaking it: build once, start the mocked server with the catalog on revalidate: 60, then run the test against it (Playwright reuses your server on :3000 locally):
npm run build:mocked && CATALOG_REVALIDATE=60 npm run start:mocked
# in a second terminal:
npx playwright test nextjs-step-5 --project=mocked -g "catalog reflects" --retries=0
It fails with Expected: "4 in stock", Received: "5 in stock": the order went through, but the catalog came from the data cache. Restart without the variable, and the default cache: 'no-store' makes the test pass again.
Running it in CI and debugging with recordings and traces
With CI set, the config retries failed tests twice, records a trace on the first retry, keeps video only for failures and switches to GitHub annotations plus an HTML report. It also starts fresh servers instead of reusing anything on the ports. Only :3000 is ever reused locally, after another app on a shared port was once silently tested instead of ours. The job needs:
npm ci
npx playwright install --with-deps chromium
CI=true npx playwright test
Upload playwright-report/ and test-results/ as artifacts, and open a trace with npx playwright show-trace.
HMR trap in next dev. After any server-file edit, Next puts back the fetch it captured before instrumentation.ts ran. MSW’s patch disappears silently, and edits to the handlers never apply because instrumentation.ts doesn’t re-run. Requests then fail with “Could not reach the commerce API” until you restart. The sample fixes it with a dev-only ensureMockServer(), which apiFetch() calls only when NODE_ENV=development. It requests a health URL only MSW answers, re-applies the patch if it’s gone, and swaps in freshly compiled handlers. CI runs a production build, so it never hits this.
The clips on this page come from the same specs: npm run record:clips runs the @clip tests on one worker with video on, then encodes MP4, WebM and a WebP poster.
The alternative: Next’s experimental test proxy
Next.js has its own route: experimental.testProxy, with fixtures from next/experimental/testmode/playwright. On 16.4.6 it’s still experimental: next build lists it under “Experiments (use with caution)”, and the docs bundled with the package don’t mention it. The app runs without MSW, and Next forwards each server-side fetch to the Playwright test, which can answer with handlers written inline. It isolates tests automatically.
What we found in e2e/extras/testmode.spec.ts (6/6 passed):
- Next’s built-in MSW wrapper,
next/experimental/testmode/playwright/msw, doesn’t load with MSW 3. It requiresstrict-event-emitterand callsmsw.handleRequest(), and MSW 3 has neither. - A small adapter works:
next.onFetch()passes each request to MSW’s publicgetResponse(handlers, request), so the same handlers answer Server Components, client fetches, the Server Action and the Route Handler. page.requestbypasses the proxy. It skipscontext.route(), carries no test headers, and Next makes the real fetch, which gave a502in our run.
It needs a separate build with the flag (npm run build:testmode, served on :3003). For now, the instrumentation.ts route is the one this sample relies on.
FAQ
Why doesn’t MSW’s service worker mock fetches made in Next.js Server Components?
Server Components, Server Actions and Route Handlers run in Node, not in the browser, so their requests never pass through the service worker. Start MSW’s setupServer in instrumentation.ts, gated by NEXT_RUNTIME === 'nodejs', and use the same handlers in the browser with setupWorker for Client Component fetches.
How do I mock fetch in Next.js Server Actions and Route Handlers?
The same way as Server Components: the MSW server started in instrumentation.ts intercepts them. In our sample it answered all four upstream calls of the checkout Server Action and the receipt Route Handler, in next start and next dev, with Turbopack and webpack.
Should I use instrumentation.ts or Next’s experimental Playwright test mode?
Use instrumentation.ts if you want something stable that works in next dev and in production builds, and you’re fine with named scenarios for overrides. The experimental test proxy lets tests write handlers inline and isolates them automatically, but on Next 16.4.6 it’s experimental, needs a separate build, and its built-in MSW wrapper doesn’t load with MSW 3.
How do I avoid mock state leaking between parallel Playwright tests?
Give each test an id, send it as a cookie, forward it to the mocked API as a header, and keep mock data and overrides per id. A global server.use() and one shared mock database made 7 of 12 tests fail at 4 workers in our run. Per-test scopes passed 36/36 at 4 workers with 3 repeats.
Does Next.js fetch caching hide my mocked responses?
It can. A fetch with revalidate kept serving old stock after a mocked order, and the cache survived a restart. Use cache: 'no-store' for data your tests change, and make test ids unique per run. We didn’t test revalidateTag or updateTag as an alternative.
Can I reuse the same handlers in Vitest/Jest and Playwright?
Yes. This sample already runs one handlers array in Node and in the browser. Unit tests can pass it to setupServer from msw/node too. See how to mock API calls in Jest for that setup, and MSW vs Nock if you’re choosing a Node mocking library.
Related
MSW in React with Playwright · MSW · Playwright · How to mock API calls in Playwright · Mock API calls in Jest · MSW vs Nock · Mocking & test data tools
Sources (checked 2026-11-29)
- Sample app and verified findings:
nextjs-msw-checkout/on thenextjs-msw-checkoutbranch of sgedda/devxtools-tutorials (commit2ead89e), including FINDINGS.md. Re-run on Node 22.23.5: 24/24 Playwright tests passing. - Next.js
instrumentation.ts: https://nextjs.org/docs/app/guides/instrumentation - MSW
setupServerand the 2.x → 3.x migration guide: https://mswjs.io/docs/api/setup-server · https://mswjs.io/docs/migrations/2.x-to-3.x