LOGOMock Service Worker
  1. Api
  2. setupServer()


A function that sets up a request interception layer in NodeJS environment.

This function is designed for NodeJS environment. If looking for a way to apply API mocking in a browser environment, consider using setupWorker instead.


Since Service Worker API cannot run in a non-browser environment, the NodeJS support of request interception is done via a designated node-request-interceptor library.

Although there is "server" in setupServer, the library does not establish any actual servers, but operates by augmenting native request issuing modules (such as https or XMLHttpRequest). The namespace is chosen for what the logic represents, not how it works internally.


There may be certain limitations when reusing request handlers between client and server. For example, if your request handler operates with localStorage, it wouldn't do so in NodeJS environment, because that API is specific to a browser.

Here are some pieces of advice on how to handle such limitations:

  • Introduce any necessary polyfills for browser-specific APIs.
  • Break down a response resolver into set of independent functions. That way you can omit the functions that are meant for a browser, and optionally substitute them with compatible NodeJS replacements.


Typically, setupServer is used for unit and integration tests, however, it will run in any NodeJS process.

Here's an example of the integration test using Jest and Mock Service Worker to provide a seamless API mocking:

1import { rest } from 'msw'
2import { setupServer } from 'msw/node'
4const server = setupServer(
5 // Describe the requests to mock.
6 rest.get('/book/:bookId', (req, res, ctx) => {
7 return res(
8 ctx.json({
9 title: 'Lord of the Rings',
10 author: 'J. R. R. Tolkien',
11 }),
12 )
13 }),
16beforeAll(() => {
17 // Establish requests interception layer before all tests.
18 server.listen()
21afterAll(() => {
22 // Clean up after all tests are done, preventing this
23 // interception layer from affecting irrelevant tests.
24 server.close()
27test('renders a book data', () => {
28 // Render components, perform requests, API communication is covered.