Seamless REST/GraphQL API mocking library for browser and Node.js.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
MSW provides a command-line interface for initializing and managing Service Worker files in browser environments.
Initialize MSW in a project by copying the Service Worker file to the public directory.
# Initialize in current directory's public folder
msw init
# Initialize in specific directory
msw init <publicDir>
# Initialize with options
msw init [publicDir] [--save] [--cwd <directory>]Command Options:
publicDir (optional) - Relative path to the public directory where the Service Worker file should be placed--save - Save the worker directory path in your package.json for future reference--cwd <directory> - Custom current working directory for the operationUsage Examples:
# Basic initialization - copies mockServiceWorker.js to ./public/
msw init
# Initialize in a custom public directory
msw init ./static
msw init ./dist/public
msw init ./build/assets
# Save the configuration in package.json
msw init ./public --save
# Initialize from a different working directory
msw init ./public --cwd /path/to/project
# Combined options
msw init ./static --save --cwd /path/to/projectThe msw init command performs the following operations:
mockServiceWorker.js file from the MSW package to your specified public directory--save is used): Adds MSW configuration to your package.json fileService Worker File:
The copied mockServiceWorker.js file is required for MSW to work in browser environments. It acts as the network interceptor that captures and handles HTTP requests.
React Applications:
# Create React App
msw init public/ --save
# Vite
msw init public/ --save
# Next.js
msw init public/ --saveVue Applications:
# Vue CLI
msw init public/ --save
# Vite + Vue
msw init public/ --save
# Nuxt.js
msw init static/ --saveAngular Applications:
# Angular CLI
msw init src/assets/ --save
# Or in the public folder if using a custom setup
msw init public/ --saveStatic Site Generators:
# Gatsby
msw init static/ --save
# Astro
msw init public/ --save
# 11ty
msw init dist/ --saveWhen using the --save flag, MSW adds configuration to your package.json:
{
"msw": {
"workerDirectory": "public"
}
}This configuration helps MSW and development tools locate the Service Worker file automatically.
Initial Project Setup:
# 1. Install MSW
npm install msw --save-dev
# 2. Initialize MSW
npx msw init public/ --save
# 3. Set up your handlers (in code)
# 4. Start your development serverContinuous Integration:
# In your CI/CD pipeline
npm ci
npx msw init public/
npm run build
npm run testMultiple Environments:
# Development environment
msw init public/ --save
# Test environment (different directory)
msw init test-public/ --cwd ./test
# Production build (ensure Service Worker is included)
msw init dist/public/Common Issues and Solutions:
# Error: Public directory doesn't exist
mkdir public
msw init public/
# Error: Permission denied
sudo msw init public/
# Or change directory permissions
# Error: Service Worker not found by browser
# Check that the file is in the correct public directory
ls public/mockServiceWorker.js
# Verify the path in your setupWorker call matches
# setupWorker().start({ serviceWorker: { url: '/mockServiceWorker.js' } })Directory Structure Validation:
After running msw init public/, your project should look like:
project/
├── public/
│ ├── mockServiceWorker.js ← Added by MSW CLI
│ └── index.html
├── src/
│ ├── mocks/
│ │ ├── handlers.js
│ │ └── browser.js
│ └── index.js
└── package.jsonCustom Service Worker Configuration:
# Initialize with custom path that matches your setupWorker configuration
msw init assets/workers/
# Then in your code:
setupWorker().start({
serviceWorker: {
url: '/assets/workers/mockServiceWorker.js'
}
})Monorepo Setup:
# Initialize for multiple packages
cd packages/frontend
msw init public/ --save
cd ../admin-panel
msw init public/ --save
cd ../mobile-web
msw init static/ --saveDocker Integration:
# Dockerfile
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npx msw init public/
RUN npm run buildBuild Script Integration:
{
"scripts": {
"prebuild": "msw init public/",
"build": "react-scripts build",
"pretest": "msw init public/",
"test": "react-scripts test"
}
}The CLI provides clear error messages for common issues:
--save is used without a package.json file# Full command syntax
msw init [publicDir] [options]
# Available options:
# publicDir Relative path to public directory (default: "public")
# --save Save worker directory in package.json
# --cwd <directory> Custom current working directory
# --help Show help information
# --version Show MSW versionExit Codes:
0 - Success1 - General error (file system, permissions, etc.)2 - Invalid arguments or usageWebpack:
// webpack.config.js
const path = require('path');
module.exports = {
// Ensure Service Worker is copied to output directory
plugins: [
new CopyPlugin({
patterns: [
{ from: 'public/mockServiceWorker.js', to: 'mockServiceWorker.js' }
]
})
]
};Vite:
// vite.config.js
export default {
publicDir: 'public', // Vite automatically serves files from public/
// mockServiceWorker.js will be available at /mockServiceWorker.js
};Parcel:
{
"source": "src/index.html",
"scripts": {
"start": "msw init dist/ && parcel serve",
"build": "msw init dist/ && parcel build"
}
}