You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Gatsby.js项目中使用Mock Service Worker(MSW)替代Mirage.js时遇到环境适配及Webpack编译问题

Can I use MSW with Gatsby?

Absolutely, you can use Mock Service Worker (MSW) with Gatsby—you just need to account for Gatsby's hybrid server-side rendering (SSR)/static site generation (SSG) and browser runtime environment, which is the root cause of your errors. Let's break down the solution step by step:

Why You're Seeing Those Errors

  • setupWorker error: setupWorker is designed exclusively for browser environments. Gatsby runs code in Node.js during SSR/SSG builds, so if your MSW initialization runs in that context, it'll throw the non-browser environment error.
  • setupServer Webpack error: setupServer is for Node.js environments (like Jest tests), not browser bundles. When Webpack tries to compile it for the browser, it hits Node-specific APIs that aren't available in the browser, causing the compile failure.

Step-by-Step Implementation

1. Install MSW

First, add MSW to your dev dependencies:

npm install msw --save-dev

2. Define Your API Mocks

Create a handlers file to define your mock endpoints (e.g., src/mocks/handlers.js):

import { rest } from 'msw'

export const handlers = [
  // Example mock: replace with your actual API endpoints
  rest.get('/api/your-data', (req, res, ctx) => {
    return res(
      ctx.status(200),
      ctx.json({
        data: 'This is your mocked API response'
      })
    )
  }),
]

3. Initialize MSW Exclusively in the Browser

Create a browser-specific initialization file (e.g., src/mocks/browser.js) with a guard to ensure it only runs in the browser:

import { setupWorker } from 'msw'
import { handlers } from './handlers'

// Only run this in the browser (skip SSR/SSG Node context)
if (typeof window !== 'undefined') {
  const worker = setupWorker(...handlers)
  worker.start({
    // Bypass requests Gatsby makes internally to avoid interference
    onUnhandledRequest: 'bypass'
  })
}

4. Load MSW via Gatsby's Browser-Only Entry Point

Gatsby provides gatsby-browser.js—a file that only runs in the browser. Import your MSW initialization here:

// gatsby-browser.js
import './src/mocks/browser'

Key Notes

  • Never load MSW in Node-side files: Avoid importing MSW in gatsby-node.js or gatsby-ssr.js—these run in Node.js and will trigger the original errors.
  • Disable in production: If you don't want MSW active in production builds, add an environment check to the initialization:
    if (typeof window !== 'undefined' && process.env.NODE_ENV === 'development') {
      // Initialize worker here
    }
    
  • SSR/SSG mock data: MSW only intercepts browser-side requests. If you need mock data during SSR/SSG (e.g., for getStaticProps), return mock data directly in those functions instead of using MSW.

内容的提问来源于stack exchange,提问作者Johann Kaltner Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:14:04