API mocking example (Mock Service Worker) with Next.js
- Published on
- Authors
- Name
- Binh Bui
- @bvbinh
Photo by Matthew Henry
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 I integrate Mock Service Worker with Next by following the next steps:
- Define a set of request handlers shared between client and server.
import { rest } from 'msw'
export const handlers = [
rest.get('https://my.backend/book', (req, res, ctx) => {
return res(
ctx.json({
title: 'Lord of the Rings',
imageUrl: '/book-cover.jpg',
description:
'The Lord of the Rings is an epic high-fantasy novel written by English author and scholar J. R. R. Tolkien.',
})
)
}),
rest.get('/reviews', (req, res, ctx) => {
return res(
ctx.json([
{
id: '60333292-7ca1-4361-bf38-b6b43b90cb16',
author: 'John Maverick',
text: 'Lord of The Rings, is with no absolute hesitation, my most favored and adored book by‑far. The triology is wonderful‑ and I really consider this a legendary fantasy series. It will always keep you at the edge of your seat‑ and the characters you will grow and fall in love with!',
},
])
)
}),
]
- Setup a Service Worker instance that would intercept all runtime client-side requests via
setupWorker
function.
import { setupWorker } from 'msw'
import { handlers } from './handlers'
export const worker = setupWorker(...handlers)
- Setup a "server" instance to intercept any server/build time requests (e.g. the one happening in
getServerSideProps
) viasetupServer
function.
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)
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 code for this article is available on GitHub
Thanks for your reading!