Responding with binary

Provide the ArrayBuffer as the mocked response body to respond with that binary data.

Browser

import { http, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('/images/:imageId', async ({ params }) => {
    // The easiest way to obtain a buffer in the browser
    // is to fetch the resource you need and read its body
    // as "response.arrayBuffer()".
    const buffer = await fetch(`/static/images/${params.imageId}`).then(
      (response) => response.arrayBuffer()
    )
 
    // Use the "HttpResponse.arrayBuffer()" shorthand method
    // to automatically infer the response body buffer's length.
    return HttpResponse.arrayBuffer(buffer, {
      headers: {
        'Content-Type': 'image/jpeg',
      },
    })
  }),
]

Don’t forget to describe the MIME type of your response body in the Content-Type response header.

Node.js

You can use fetch() to request resources and read them as ArrayBuffer in Node.js as well. However, you can also read any file in your file system and respond with its binary.

import fs from 'node:fs'
import path from 'node:path'
import { http, HttpResponse } from 'msw'
 
export const handlers = [
  http.get('/videos/:videoId', async ({ params }) => {
    // Read a video file from the file system.
    const buffer = fs.readFileSync(
      path.resolve(process.cwd(), 'mock-assets/videos', `${videoId}.mp4`)
    )
 
    return HttpResponse.arrayBuffer(buffer, {
      headers: {
        'Content-Type': 'video/mp4',
      },
    })
  }),
]