Set Up MSW in Node.js

Share this video with your friends

Send Tweet

Let's use the "setupServer" API from Mock Service Worker to enable API mocking on the server-side of our Remix application. This way you can intercept and mock server-side requests, like those happening in the "loader" and "action" functions, as well as reuse the same setup for any other Node.js process, like integration tests with tools like Vitest or Jest in the future.

johnnycook
johnnycook
~ a month ago

I had issues running the remix dev server when I added server.listen()line. I couldn't solve it, so I just reinstalled msw with version 0.0.0-fetch.rc-20 same as in the completed code. This fixed the server.

npm install msw@0.0.0-fetch.rc-20

Artem Zakharchenko
Artem Zakharchenko(instructor)
~ a month ago

Hi! Have you tried msw@latest? You shouldn't be using the fetch RC anymore, it's rather old. The latest MSW should work well with Remix. Let me know if it doesn't.

johnnycook
johnnycook
~ a month ago

I have tried the latest msw, but @remix-run/server-runtime then fails and throws an error. I also tried to update to latest

 "@remix-run/node": "^2.12.1",
 "@remix-run/react": "^2.12.1",
 "@remix-run/serve": "^2.12.1",

but that throws some other errors with Response type.

Artem Zakharchenko
Artem Zakharchenko(instructor)
~ a month ago

Got it! Please, do you have a reproduction repo I can look at? I think I know what's going on.

johnnycook
johnnycook
~ a month ago

Sure.

  1. Clone the original repo
  2. Install latest msw (in my case 2.4.9)
  3. Setup a msw server with setupServer([]); and call server.listen() in entry.server.tsx.

But I don't think it's that critical for the tutorial purposes. It's possible to install latest msw, latest remix deps, replace Response objects with HttpResponse and run it normally.