CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-msw

Seamless REST/GraphQL API mocking library for browser and Node.js.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

cli.mddocs/

CLI (Command Line Interface)

MSW provides a command-line interface for initializing and managing Service Worker files in browser environments.

Capabilities

Initialize Command

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 operation

Usage 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/project

What the CLI Does

The msw init command performs the following operations:

  1. Copies Service Worker File: Copies the mockServiceWorker.js file from the MSW package to your specified public directory
  2. Creates Directory: Creates the target directory if it doesn't exist
  3. Updates package.json (when --save is used): Adds MSW configuration to your package.json file
  4. Validates Setup: Ensures the Service Worker file is properly placed for browser environments

Service 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.

Integration Examples

React Applications:

# Create React App
msw init public/ --save

# Vite
msw init public/ --save

# Next.js
msw init public/ --save

Vue Applications:

# Vue CLI
msw init public/ --save

# Vite + Vue
msw init public/ --save

# Nuxt.js
msw init static/ --save

Angular Applications:

# Angular CLI
msw init src/assets/ --save

# Or in the public folder if using a custom setup
msw init public/ --save

Static Site Generators:

# Gatsby
msw init static/ --save

# Astro
msw init public/ --save

# 11ty
msw init dist/ --save

Package.json Integration

When 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.

Development Workflow

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 server

Continuous Integration:

# In your CI/CD pipeline
npm ci
npx msw init public/
npm run build
npm run test

Multiple 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/

Troubleshooting

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.json

Advanced Usage

Custom 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/ --save

Docker Integration:

# Dockerfile
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npx msw init public/
RUN npm run build

Build Script Integration:

{
  "scripts": {
    "prebuild": "msw init public/",
    "build": "react-scripts build",
    "pretest": "msw init public/",
    "test": "react-scripts test"
  }
}

Error Handling

The CLI provides clear error messages for common issues:

  • Directory not found: Creates the directory or suggests creating it manually
  • Permission issues: Suggests running with appropriate permissions
  • Invalid paths: Validates that the provided path is accessible
  • Missing package.json: Warns when --save is used without a package.json file

Command Reference

# 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 version

Exit Codes:

  • 0 - Success
  • 1 - General error (file system, permissions, etc.)
  • 2 - Invalid arguments or usage

Integration with Build Tools

Webpack:

// 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"
  }
}

docs

browser-setup.md

cli.md

graphql-handlers.md

http-handlers.md

index.md

nodejs-setup.md

react-native-setup.md

response-creation.md

utilities.md

websocket-handlers.md

tile.json