How to mock APIs in Storybook with MSW (Mock Service Worker)
Install Mock Service Worker (MSW)

We’re going to add Mock Service Worker (MSW) to our project and make it available globally.

Usually, Service Workers offer better cache control on websites and web apps. These Workers stand between your front-end and the network, catching all requests being made.

Instead of managing the cache, MSW allows you to catch calls to the network. You can set up whatever you need in place of the official response: your application will act as usual without noticing it’s a mocked response.

Step 1: install the package as a dev dependency.

npm i -D msw

Step 2: initiate the MSW config and let it creates a file in our Storybook public folder recently created (don’t forget to adapt the path to your folder structure)

npx msw init .storybook/public/

After having run this command, the library creates the file mockServiceWorker.js in your public folder. Don’t delete it as explained inside as it is needed to start the service worker.

If everything went well, you should now be able to access this file when you run Storybook. In my case, the URL is:

http://localhost:6006/mockServiceWorker.js

Step 3: start MSW from your Storybook preview.js file by adding…

This line at the beginning of the file:

import { setupWorker, rest } from ‘msw’;

These lines at the end of the file:

// Storybook executes this module in both bootstrap phase (Node)

// and a story's runtime (browser). However, we cannot call `setupWorker`

// in Node environment, so we need to check if we're in a browser.

if (typeof global.process === 'undefined') {

// Create the mockServiceWorker (msw).

const worker = setupWorker();

// Start the service worker.

worker.start();

// Make the `worker` and `rest` references available globally,

// so they can be accessed in stories.

window.msw = { worker, rest };

}

If everything is well configured, when you run Storybook, you should see a message in your console informing you that Mock Service Worker is started:
['Alexis Oney']
['React', 'Front End Development', 'Storybook', 'Mock Service Worker', 'Design Systems']