Creating Custom Responses
You'll learn how to manually construct Response objects for testing and service worker scenarios.
Why Create Custom Responses?
Sometimes you need to create a Response object from scratch rather than getting one from fetch(). This is especially useful in service workers when you want to serve cached content, synthetic responses, or handle offline scenarios. It's also valuable for testing code that expects Response objects without making real network requests.
Think of it like a restaurant creating a "sample plate" for display—it looks exactly like the real dish but doesn't come from the actual kitchen.
The Response Constructor
The Response constructor lets you build Response objects manually:
// Create a simple text response
const response = new Response('Hello, world!', {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': 'text/plain'
}
});
// Read the response
response.text().then(text => {
console.log(text); // "Hello, world!"
});
Creating JSON Responses
A common pattern is creating JSON responses:
const data = { message: 'Custom response', timestamp: Date.now() };
const jsonResponse = new Response(JSON.stringify(data), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
jsonResponse.json().then(obj => {
console.log(obj.message); // "Custom response"
});
Practical Use: Offline Fallback
In service workers, you might return a custom response when offline:
const offlineResponse = new Response('You are offline', {
status: 503,
statusText: 'Service Unavailable'
});
Key Takeaway: The Response constructor lets you create synthetic Response objects with custom body content, status codes, and headers—essential for service workers and testing scenarios where you need Response objects without making actual network requests.