Loading...
There are a bunch of situations where mocking API requests can really come in handy. Maybe you’re...
msw/browser
)msw/node
) that works well for SSR and API routesmocks
directory at the root of your project. This will hold everything related to MSW, including handlers and setup files for both the browser and Node.js environments.Here’s the structure:app/page.tsx
GithubUserName
) and also displays the user’s GitHub login directly.components/UserName.tsx
useEffect
. Instead of showing the login, it displays the user’s full name.💡 Note:If you start the development server at this point, you'll see something like this:
The client-side fetching here is redundant. Since the same user data is already available on the server, it could be passed as a prop to the client component. We're doing it this way purely to demonstrate both client-side and server-side mocking with MSW.
mocks/data/github-user.json
mocks/handlers.js
https://api.github.com/users/*
. If you want to target a specific user or URL, you can provide the exact match instead.*mocks/node.js
mocks/browser.js
🛠️ From the Next.js documentation:We’re going to use this hook to spin up our mock server.
"Instrumentation is the process of using code to integrate monitoring and logging tools into your application. This allows you to track the performance and behavior of your application, and to debug issues in production."
instrumentation.ts
instrumentation.ts
and add the following:NEXT_RUNTIME === 'nodejs'
ensures we only run this in the Node.js runtime (not in the Edge runtime).NEXT_PUBLIC_MSW_ENV === 'test'
lets us control when to enable MSW. This way, mocks are only active in testing or development environments.⚠️ Note:
This example uses Next.js version 15.3.5.
Depending on your version, you might need to enable the instrumentation hook explicitly in your config:
mockServiceWorker.js
file that gets served from the public/
folder.public/mockServiceWorker.js
file that MSW uses under the hood.components/MswWorker.tsx
layout.tsx
instrumentation-client.ts
instrumentation.ts
for server-side setup, there's also an instrumentation-client.ts
file in Next.js that runs on the client before hydration starts.In theory, we could load the MSW worker from there. Which sounds ideal, but after testing it out, I ran into some race conditions. Some API calls were firing before the worker was fully initialized, which kinda defeats the whole purpose of mocking.At the time of writing this, clientInstrumentationHook
is still an experimental feature. So until it's more stable (or there's a solid workaround), it’s safer to stick with loading the worker manually in a client-side component like MswWorker.tsx
.⚠️ Important:
This file (instrumentation-client.ts
) is executed before hydration, so avoid doing anything here that may block rendering or impact performance in production environments.
⚙️ Config Note:
Depending on your next js version, you might need to add the following tonext.config.ts
to enable this: