Worker throwing exception when trying to modify header response

I’m using the code found in the Cloudflare docs to try and return a 410 for certain pages

 * @param {string} headerNameSrc Header to get the new value from
 * @param {string} headerNameDst Header to set based off of value in src
const headerNameSrc = 'foo'; //"Orig-Header"
const headerNameDst = 'Last-Modified';

async function handleRequest(request) {
   * Response properties are immutable. To change them, construct a new
   * Response and pass modified status or statusText in the ResponseInit
   * object. Response headers can be modified through the headers `set` method.
  const originalResponse = await fetch(request);

  // Change status and statusText, but preserve body and headers
  let response = new Response(originalResponse.body, {
    status: 500,
    statusText: 'some message',
    headers: originalResponse.headers,

  // Change response body by adding the foo prop
  const originalBody = await originalResponse.json();
  const body = JSON.stringify({ foo: 'bar', ...originalBody });
  response = new Response(body, response);

  // Add a header using set method
  response.headers.set('foo', 'bar');

  // Set destination header to the value of the source header
  const src = response.headers.get(headerNameSrc);

  if (src != null) {
    response.headers.set(headerNameDst, src);
      `Response header "${headerNameDst}" was set to "${response.headers.get(headerNameDst)}"`
  return response;

addEventListener('fetch', event => {

I changed the Status to 410 and that didn’t work - I get an Error 1101 - Worker threw exception

I simply want to return a 410 for Google (and other crawlers to see)

You are using the body of originalResponse twice.

let response = new Response(originalResponse.body - consumed.
const originalBody = await originalResponse.json(); - reused.

The body of a response is a ReadableStream and can only be used once. You should be either using tee() to create two ReadableStreams or modifying the new response that you made in the first instance of reading it.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.