Injecting CORS headers in response, larger requests fail

So looking further I came across the following topic:

This sounded exactly like my case. So I’ve implemented the following:

addEventListener('fetch', event => {
  // console.log(event.request);
  event.respondWith(handle(event.request))
})

async function handle(request) {
  if (request.method === "OPTIONS") {
    return handleOptions(request)
  } else if (request.method === "GET") {
    
    let response = await fetch(request)

    // Handle status 304
    if (response.status !== 200) {
      return response
    }
    
    let { readable, writable } = new TransformStream()
    response.body.pipeTo(writable)
        
    let newResponse = new Response(readable, response);
    newResponse.headers.append("Access-Control-Allow-Origin", "*");
    return newResponse
    
  } else if (request.method === "HEAD" ||
             request.method === "POST"){
    fetch(request)
  } else {
    return new Response(null, {
      status: 405,
      statusText: "Method Not Allowed",
    })
  }
}

// We support the GET, POST, HEAD, and OPTIONS methods from any origin,
// and accept the Content-Type header on requests. These headers must be
// present on all responses to all CORS requests. In practice, this means
// all responses to OPTIONS requests.
const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type",
}

function handleOptions(request) {
  if (request.headers.get("Origin") !== null &&
      request.headers.get("Access-Control-Request-Method") !== null &&
      request.headers.get("Access-Control-Request-Headers") !== null) {
    // Handle CORS pre-flight request.
    return new Response(null, {
      headers: corsHeaders
    })
  } else {
    // Handle standard OPTIONS request.
    return new Response(null, {
      headers: {
        "Allow": "GET, HEAD, POST, OPTIONS",
      }
    })
  }
}

So basically I check if there’s a status 200 or not. If it isn’t, than it was probably a 304 from the origin and it should just be passed on. This seems to solve the flip flopping (we’ll monitor over the next few hours). Though curl still gives a status 500.