Posts

Showing posts with the label mock api

Guide to Mocking API with MSW in NextJS

Image
Introduction MSW (Mock Service Worker) is the most popular library for modern projects, used to simulate APIs by intercepting network requests at the network layer. Instead of mocking at the application layer, MSW operates at the Service Worker layer (browser) and Node.js interception (server-side). Advantages: Simulate everything: Method, URL, Header, Status code, Delay. Help Frontend develop independently when Backend has not finished the API. Runs on both the browser (Browser) and NodeJS environment (SSR). Does not change the API call logic code, only needs request interception configuration. Clean mock code, written like writing a real API. Usage: You define handlers. When the application calls a URL, MSW catches that request and returns the response you defined without ever actually sending the request to the server. Detail Run the following commands to install and create the mockServiceWorker.js file # install yarn add msw # create mockServiceWorker.js npx msw init public/ ...