Set Up MSW in Node.js

Share this video with your friends

Social Share Links

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.

Instructor: [0:00] There are no service workers in Node.js, but we can use MSW there all the same. Let's create a new node module where we will set up MSW in Node.js. In the node module, import { setupServer } from 'msw/node'. Create a new server variable, and assign it the result of the setupServer function call.

[0:19] The setupServer function will return an object that we can use to start, stop, and control MSW in Node.js. Let's export the server object so we can reuse it in any Node.js process, such as our development server in Remix or integration tests with tools like Vitest or Jest.

[0:36] Similar to the setupWorker function, the setupServer expects request handlers. Let's import them from the same handlers module. By relying on the same list of handlers, we introduce a single source of truth for our network description and then utilize functions like setupServer and setupWorker to let MSW establish API mocking correctly in different environments for us.

[0:57] The Node.js setup is ready. All we'll have to do is start it. To do that, go to the server entry of our application. In Remix, that's an entry.server module. Import the server object from the Node.js integration we've just created. Then, call server.listen() to enable API mocking.

[1:19] Notice that this method is synchronous, and it will affect the current process as soon as it's called. Despite the name, the setupServer API does not create any actual servers, and instead, extends the standard Node.js APIs like HTTP to provision request interception.

[1:36] As the last thing, let's make sure that we enable API mocking only while in development by checking the node environment variable on the process and calling server.listen() conditionally.