Skip to content

Instantly share code, notes, and snippets.

@declaresub
Created December 3, 2022 16:26
Show Gist options
  • Save declaresub/9a7b8b4f5f57e21bf05003fdf64788aa to your computer and use it in GitHub Desktop.
Save declaresub/9a7b8b4f5f57e21bf05003fdf64788aa to your computer and use it in GitHub Desktop.
Configure nuxt to use Mock Service Worker
import { setupWorker } from 'msw'
import { handlers } from './api/index'
// This configures a Service Worker with the given request handlers.
export const worker = setupWorker(...handlers)
import { rest, RestRequest, RestContext, ResponseFunction } from 'msw'
import { logMockRequest, MSWRequestHandler } from '~/api/msw/decorators'
function makeURL(path: string, base = 'http://127.0.0.1:3000') {
// base is hard-coded here. It should be read from runtimeConfig.public.nuxtServerOrigin,
// but useRuntimeConfig isn't easily avaiable until the project moves all the way to nuxt 3.
// This really matters should we want to use API mocking in a release stage other than development.
return `${base}${path}`
}
async function getApi200(
req: RestRequest,
res: ResponseFunction,
ctx: RestContext
) {
const responseBody = {
self: { path: '/api', method: 'GET' },
version_id: '4c75ce4392947de85974976c75ab47a188dede4a',
}
return res(ctx.status(200), ctx.json(responseBody))
}
export const handlers = [rest.get("/api", logMockRequest(getApi200))]
async function start_msw_worker() {
if (process.env.NODE_ENV === 'development') {
console.log('Importing mock service worker.')
const { worker } = await import('../api/msw/browser')
console.log('Starting mock service browser.')
worker.start({
onUnhandledRequest: 'bypass', // disable logging of requests not handled by MSW.
})
}
else{`NODE_ENV = ${process.env.NODE_ENV}, so no mock service worker.`}
}
start_msw_worker()
async function start_msw_server() {
if (process.env.NODE_ENV === 'development') {
console.log('Importing mock service server.')
const { server } = await import('../api/msw/server')
console.log('Starting mock service server.')
server.listen()
}
else{`NODE_ENV = ${process.env.NODE_ENV}, so no server-side mock service worker.`}
}
start_msw_server()

Install

npm install msw --save-dev npm install encoding --save-dev

Run from command line

npx msw init static --save

The files msw.client.js, msw-server.js go in ~/plugins.

My directory layout:

~/api/ ~/api/msw/ ~api/msw/browser.js ~api/msw/server.js ~/api/msw/api/ ~/api/msw/api/index.ts

MSW does not appear to play well with the use of nuxt server and whatever helpful things it does for you under the hood. I don't really understand nuxt, so it is possible that someone more knowledgeable about nuxt might be able to get the two to cooperate.

I use fetch, not $fetch = ohmyfetch; ohmyfetch tries to be more helpful than I prefer.

// Add this to your nuxt configuration,
plugins: [
'~/plugins/msw.client.js',
'~/plugins/msw.server.js',
import { setupServer } from 'msw/node'
import { handlers } from './api/index'
// This configures a request mocking server with the given request handlers.
export const server = setupServer(...handlers)
@maxarias-io
Copy link

MSW does not appear to play well with the use of nuxt server and whatever helpful things it does for you under the hood. I don't really understand nuxt, so it is possible that someone more knowledgeable about nuxt might be able to get the two to cooperate.

I use fetch, not $fetch = ohmyfetch; ohmyfetch tries to be more helpful than I prefer.

I'm running exactly into this. I'm using $fetch because I can intercept requests easily to refresh the JWT... but it brings other issues. Ugh. Maybe I should just stick to fetch.

Thanks for putting this out here btw. I landed on a similar solution, but using if (typeof window === 'undefined') { instead of naming the files .client./.server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment