Course contentsShow
← JavaScript
Lesson 2277 of 2,72347. Networking PrimitivesFree lesson

Creating Custom Response Objects

Build Response objects manually with new Response() for testing, mocking, or Service Worker scenarios.

Creating Custom Response Objects

You'll learn how to build Response objects from scratch for testing, mocking, or Service Worker scenarios.

What Are Custom Response Objects?

So far you've worked with Response objects returned by fetch(). But JavaScript also lets you create Response objects manually using the new Response() constructor. This is invaluable when you need to simulate server responses in tests, build custom Service Worker logic, or mock API calls without hitting a real network.

Think of it like being a stage director: instead of waiting for actors (servers) to show up, you create stand-ins (custom responses) that behave exactly how you need them to.

Creating a Response Manually

The simplest custom response:

const response = new Response('Hello, world!');
console.log(response.ok); // true
console.log(response.status); // 200 (default)

You can specify status codes, headers, and any body type:

const jsonResponse = new Response(
  JSON.stringify({ user: 'Alice', id: 42 }),
  {
    status: 200,
    statusText: 'OK',
    headers: {
      'Content-Type': 'application/json',
      'X-Custom-Header': 'test-value'
    }
  }
);

const data = await jsonResponse.json();
console.log(data.user); // 'Alice'

Why This Matters

Custom Response objects let you control every detail—body, status, headers—without any network activity. Perfect for Service Workers that intercept requests and return cached or synthetic responses, or for unit tests that verify how your code handles specific server responses.

Key Takeaway: Use new Response(body, options) to create synthetic Response objects with full control over status, headers, and body content—essential for testing, mocking, and Service Workers.