mswMock Service Worker
  1. Recipes
  2. Custom response composition

Custom response composition

Sometimes the default response serializer (application/json), provided by the default response transformer, isn't what you need and you're looking for a way to overwrite the default serialization for a response.

In this recipe we are going to write a custom response transformer that serializes BigInt values that cannot be otherwise transformed using JSON.stringify.

Creating a composition

Use the createResponseComposition API to create a custom response composition.

1// src/mocks/res/delayed-response.js
2import { createResponseComposition, context } from 'msw'
4export const delayedResponse = createResponseComposition(null, [
5 context.delay('real'),

The createResponseComposition accepts two arguments:

In the example above we've created a custom delayedResponse composition that attaches a realistic delay time to every mocked response. We're using an existing context.delay function as opposed to createResponseComposition({ delay: 123 }) because it comes with the behavior with need out of the box.

Using a composition

Once the custom response transformer is defined, use it to return the response instead of using the default response method.

1// src/mocks/handlers.js
2import { rest } from 'msw'
3import { delayedResponse } from './res/delayed-response'
5export const handlers = [
6 rest.get('/user', (req, res, ctx) => {
7 // This mocked response has realistic
8 // response time automatically.
9 return delayedResponse(
10 ctx.json({
11 firstName: 'John',
12 lastName: 'Maverick',
13 }),
14 )
15 }),