mswjs / msw

Seamless REST/GraphQL API mocking library for browser and Node.js.
https://mswjs.io
MIT License
15.73k stars 506 forks source link

How do I implement MSW in a NextJS backend? #2136

Closed moonman239 closed 5 months ago

moonman239 commented 5 months ago

I'm new to MSW and have been trying to get MSW to intercept "fetch" requests that my NextJS app backend makes to a third-party API. I have my handlers & server set up already, and I have imported my server code into an API endpoint (so according to my logs, MSW must be listening whenever I trigger the endpoint after running "npm run dev") According to instructions, this is probably where said code should be imported.

However, it appears that my requests are all being "bypassed" without warning, despite me configuring MSW to emit a warning if it receives a request that it cannot handle, so debugging is pretty hard.

The server is initialized like so:

\\ listen.ts
import { server } from './msw_server';

server.listen({
    onUnhandledRequest:'warn'
});

and set up like so:

\\msw_server.ts
import { setupServer } from 'msw/node'
import { handlers } from './msw_handlers';

export const server = setupServer(...handlers)

and imported like so in the API endpoint:

import "../mockServiceWorker/listen.ts"