
MSW Has a Free API Mocking Library: Mock REST and GraphQL APIs in Browser and Node.js Without Changing App Code
Your frontend depends on 5 APIs. Backend isn't ready. You create mockData.json , wrap fetch calls in if (process.env.NODE_ENV === 'development') , and your production code becomes littered with mock logic. What if you could intercept network requests at the service worker level — without touching your application code? That's MSW (Mock Service Worker). Your app makes real fetch calls. MSW intercepts them and returns mock responses. Your code doesn't know the difference. Quick Start npm install msw --save-dev npx msw init ./public # For browser usage Define Handlers // mocks/handlers.ts import { http , HttpResponse } from " msw " ; export const handlers = [ http . get ( " /api/users " , () => { return HttpResponse . json ([ { id : " 1 " , name : " Aleksej " , email : " dev@example.com " }, { id : " 2 " , name : " Maria " , email : " maria@example.com " }, ]); }), http . post ( " /api/users " , async ({ request }) => { const body = await request . json (); return HttpResponse . json ( {
Continue reading on Dev.to Webdev
Opens in a new tab



