Mock Service Worker
  1. Recipes
  2. Custom transformer

Custom transformer

Use case

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.

Defining a transformer

Use the createResponseComposition API to create a custom transformer by defining a transformer. Assign the transformer to the defaultTransformers property, which can take multiple transformers. A transformer receives the response, optionally it modifies the response, and then it must return the (modified) response.

The example below uses the json-bigint package to serialize the response body.

1import { createResponseComposition } from 'msw'
2import * as JSONbig from 'json-bigint'
3
4export const customResponse = createResponseComposition({
5 defaultTransformers: [
6 (res) => {
7 if (res.body && res.headers?.get('content-type')?.endsWith('json')) {
8 res.body = JSONbig.stringify(res.body)
9 }
10 return res
11 },
12 ],
13})

Using a transformer

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

1import { rest } from 'msw'
2import { customResponse } from './custom-response'
3
4export const handlers = [
5 rest.get('http://test.mswjs.io/me', (req, res, ctx) => {
6 const me = {
7 username: 'Sarah',
8 balance: BigInt(1597928668063727616),
9 }
10
11 // use customResponse instead of res
12 return customResponse(ctx.json(me))
13 }),
14]