mock api with MSW in Nuxt, both in the browser and on the server
npm install nuxt-msw[//]: # ([![npm version][npm-version-src]][npm-version-href])
[//]: # ([![npm downloads][npm-downloads-src]][npm-downloads-href])
[//]: # ([![License][license-src]][license-href])
[//]: # ([![Nuxt][nuxt-src]][nuxt-href])
Mock api with MSW in your Nuxt app
- ⛰ Zero config integration with MSW
- 🚠 Works both in the browser and on the server during SSR
1. Add nuxt-msw and msw dependencies to your project
``bashUsing pnpm
pnpm add -D nuxt-msw msw
2. Add
nuxt-msw to the modules section of nuxt.config.ts and enable it in options:`js
export default defineNuxtConfig({
modules: [
'nuxt-msw'
],
msw: {
enabled: true
}
})
`3. Write some request handlers in
msw/handlers.ts.`ts
import { http, HttpResponse } from 'msw'export default [
http.get('https://example.com/api/user/1', () => HttpResponse.json({
id: 12,
name: 'Albert Einstein'
})),
http.post('https://example.com/api/user', () => HttpResponse.text('OK')),
]
`That's it! Now the specified requests are intercepted by MSW both in the browser and on the server during SSR ✨
`ts
const { data } = useFetch('https://example.com/api/user/1')
watch(data, (value) => {
console.log(value) // { id: 12, name: 'Albert Einstein' }
})
`Development
`bash
Install dependencies
yarn installGenerate type stubs
yarn run dev:prepareDevelop with the playground
yarn run devBuild the playground
yarn run dev:buildRun ESLint
yarn run lintRun Vitest
yarn run test
yarn run test:watchRelease new version
yarn run release
``
[npm-version-src]: https://img.shields.io/npm/v/nuxt-msw/latest.svg?style=flat&colorA=18181B&colorB=28CF8D
[npm-version-href]: https://npmjs.com/package/nuxt-msw
[npm-downloads-src]: https://img.shields.io/npm/dm/nuxt-msw.svg?style=flat&colorA=18181B&colorB=28CF8D
[npm-downloads-href]: https://npmjs.com/package/nuxt-msw
[license-src]: https://img.shields.io/npm/l/nuxt-msw.svg?style=flat&colorA=18181B&colorB=28CF8D
[license-href]: https://npmjs.com/package/nuxt-msw
[nuxt-src]: https://img.shields.io/badge/Nuxt-18181B?logo=nuxt.js
[nuxt-href]: https://nuxt.com