MSW vs Nock
Choosing between the two most popular HTTP mocking libraries
When you need to mock HTTP requests in JavaScript or TypeScript tests, two tools dominate:MSW (Mock Service Worker) and Nock. Both are mature, well-maintained, and widely adopted, but they take fundamentally different approaches to interception.
At a Glance
MSW
- ✅ Works in browser and Node.js
- ✅ Network-level interception (Service Worker)
- ✅ Same API everywhere
- ✅ Great for full-stack apps
- ❌ Slightly more setup
- ❌ No built-in recording
Nock
- ✅ Dead simple API
- ✅ Built-in record/replay
- ✅ Powerful request matching
- ✅ Battle-tested since 2011
- ❌ Node.js only
- ❌ Patches HTTP module
Which Should You Choose?
Choose MSW if...
- You're building a React, Vue, or Angular app with browser tests
- You want the same mocking code in both browser and Node.js
- You prefer network-level interception over module patching
- You want to use mocks in development, not just tests
Best for: Modern web applications with component + integration tests
Choose Nock if...
- You're only testing Node.js code (backend services, APIs)
- You want the absolute simplest API possible
- You need to record real API calls and replay them
- You don't need browser support
Best for: Backend Node.js services and APIs
Side-by-Side Code Example
MSW
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
const server = setupServer(
http.get('/api/user', () => {
return HttpResponse.json({
id: 1,
name: 'John Doe'
})
})
)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())Nock
import nock from 'nock'
nock('https://api.example.com')
.get('/api/user')
.reply(200, {
id: 1,
name: 'John Doe'
})
// That's it! Nock intercepts
// matching requests automaticallyDetailed Comparison
| Feature | MSW | Nock |
|---|---|---|
| Browser Support | ✅ Yes | ❌ No |
| Node.js Support | ✅ Yes | ✅ Yes |
| Interception Method | Service Worker / Native modules | Patches Node.js HTTP module |
| Record/Replay | ❌ No | ✅ Yes |
| TypeScript Support | ✅ Native | ✅ Yes (types included) |
| Learning Curve | Medium | Low |
| GitHub Stars | 16k+ | 12k+ |
| First Released | 2018 | 2011 |
Also Consider: Polly.js
If you need record/replay functionality with browser support, check out Polly.js. Built by Netflix, it works in both environments and specializes in recording real API traffic. It's more complex to set up than MSW or Nock, but fills a unique niche.