Mock Service Worker is an API mocking library for browser and Node. It provides seamless mocking by interception of actual requests on the network level using Service Worker API. This makes your application unaware of any mocking being at place.
In this example we integrate Mock Service Worker with Next by following the next steps:
- Define a set of request handlers shared between client and server.
- Setup a Service Worker instance that would intercept all runtime client-side requests via
setupWorker
function. - Setup a "server" instance to intercept any server/build time requests (e.g. the one happening in
getServerSideProps
) viasetupServer
function.
Mocking is enabled using the NEXT_PUBLIC_API_MOCKING
environment variable. By default, mocking is enabled for both development and production. This allows you to have working preview deployments before implementing an actual API. To disable MSW for a specific environment, change the environment variable value in the file corresponding to the environment from enabled
to disabled
.
The service worker file will automatically be generated in public/mockServiceWorker.js
after installing node_modules
. If the file is not generated, you can explicitly generate it with the following command:
npx msw init public/
More information on this setup step can be found in the MSW documentation here.
Deploy the example using Vercel:
Execute create-next-app
with npm, Yarn, or pnpm to bootstrap the example:
npx create-next-app --example with-msw with-msw-app
yarn create next-app --example with-msw with-msw-app
pnpm create next-app --example with-msw with-msw-app
Deploy it to the cloud with Vercel (Documentation).