Skip to content

[email protected] config needed for the Next.js (Pages router) #2532

@mataspetrikas

Description

@mataspetrikas

hey hey,

we have noticed that the msw stops working for us when we update it to v2.8+ with [email protected] (page router).

Does anyone have a working [email protected] setup in typescript?

Our current config that works for [email protected] (node v22.13.0, cypress v13):

import type { SetupWorker } from 'msw/browser';
import type { SetupServer } from 'msw/node';

export async function initServerMocks(): Promise<SetupServer | undefined> {
  if (typeof window === 'undefined') {
    const { server }: { server: SetupServer } = await import('./server');
    server?.listen({
      onUnhandledRequest: (request) => {
        // Disable the `console.warn` logging of un-captured requests
        // as the warning will be issued even for the requests that are intentionally not captured.
        // e.g. assets and pages
        console.warn(`No request handler found for ${request.url}`);
      },
    });
    return server;
  }
}

export async function initBrowserMocks() {
  if (typeof window !== 'undefined') {
    // use require on the client instead of import
    // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment, unicorn/prefer-module
    const { worker }: { worker: SetupWorker } = await require('./browser');
    await worker.start({
      // Disable the `console.warn` logging of uncaptured requests
      onUnhandledRequest: 'bypass',
      quiet: false,
    });
  }
}

export {};

server.ts

// eslint-disable-next-line import-x/no-unresolved
import { setupServer } from 'msw/node';
import { handlers } from 'src/mocks/handlers';

export const server = setupServer(...handlers);

browser.ts

import * as msw from 'msw';
import { setupWorker } from 'msw/browser';
import { handlers, browserOnlyHandlers } from 'src/mocks/handlers';

export const worker = setupWorker(...handlers, ...browserOnlyHandlers);

// Expose methods globally to make them tweakable in integration tests
window.msw = { ...msw, worker };

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions