msw-nextjs
v1.1.1
Published
Toolkit to seamlessly extend a nextJS application so it can mock dependency calls in borwser and node environment. This solution supports local development alongside cloud environments.
Downloads
28
Readme
Mock Service Worker for NextJS v14^
Lightweight module to expose methods to easily integrate your nextJS app with MSW.
The msw-nextjs/node
and msw-nextjs/browser
is intened to be used instead of msw/node
and msw/browser
respectively.
Initialise mocks on the server
Run serverInitialise
from msw-nextjs/node
on the server as early possible during initialisation.
Instrumentation hook dependency
It is suggested that you run serverInitialise
inside the instrumentation hook from NextJS.
Initialise mocks on the client
Create a React high-order component using createBrowserHOC
from msw-nextjs/browser
passing in browser msw resolvers.
To activate browser mocks in that component and it's sub components, wrap you component with the return of createBrowserHOC
.
A component wrapped in your HOC will be suspended with React Suspense until client mocks have been initialised. For this reason you can pass an optional fallback node to the HOC to override the default.
Example
msw-nextjs-helpers.ts
export const withMSW = createBrowserHOC[<< msw-handlers >>];
ClientComponent.tsx
import { withMSW } from './msw-nextjs-helpers.ts';
...
export default withMSW(ClientComponent);