How do I implement MSW in a NextJS backend? #2137
-
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:
and set up like so:
and imported like so in the API endpoint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi, @moonman239! MSW on the server will follow the Node.js integration instructions. You have to call Now, Next.js doesn't really expose you one. The next best place I found is the instrumentation hook. It will indeed instantiate MSW server-side and allow it to intercept the requests you make on the server. Take a look at the in-progress Next.js + MSW example that features both client-side and server-side integrations using the instrumentation hooks I've mentioned. It's incomplete but it can serve you as a reference to get started. Note that when you initiate MSW server-side, you will be intercepting requests your server makes. For example, if your |
Beta Was this translation helpful? Give feedback.
Hi, @moonman239!
MSW on the server will follow the Node.js integration instructions. You have to call
server.listen()
preferably in your server entrpoint.Now, Next.js doesn't really expose you one. The next best place I found is the instrumentation hook. It will indeed instantiate MSW server-side and allow it to intercept the requests you make on the server.
Take a look at the in-progress Next.js + MSW example that features both client-side and server-side integrations using the instrumentation hooks I've mentioned. It's incomplete but it can serve you as a reference to get started.
Note that when you initiate MSW server-side, you will be intercepting requests your server makes. For exam…