async function handler(event) {
  let req = event.request;
  let backendResponse;

  if (req.method === 'GET' || req.method === 'HEAD') {
    // No need to preserve bodies for GET and HEAD
    let url = req.url;
    let method = req.method;
    let headers = req.headers;

    let req1 = new Request(url, { method, headers });
    backendResponse = await fetch(req1, {
      backend: "origin_0"
    });

    // If the response is 403 or 5xx, retry with the secondary backend.
    if (backendResponse.status === 403 || (backendResponse.status >= 500 && backendResponse.status < 600)) {
      // FOR DEMO PURPOSES
      // Change the request to origin to prompt the right kind of response
      // This code should not be used in a production deployment
      let url = new URL(req.url);
      url.pathname = '/status/200';

      console.log("Failing over to the secondary backend...");
      let req2 = new Request(url, { method, headers });
      backendResponse = await fetch(req2, {
        backend: "origin_1"
      });
    }
  } else {
    // Nothing special for other methods.
    backendResponse = await fetch(req, {
      backend: "origin_0"
    });
  }

  return backendResponse;
}

addEventListener("fetch", event => event.respondWith(handler(event)));