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

async function handleRequest(event) {
  const req = event.request;

  // Headers are available immediately and are generally safe to log
  // at scale without impacting the performance of your application
  console.log('Request headers', Object.fromEntries(req.headers));
  
  // Consuming the request body uses memory and means you must
  // create a fresh Request to send the same body in a backend
  const reqBody = ["GET", "HEAD"].includes(req.method) ? undefined : await req.text();
  console.log('Request body', reqBody)
  
  const beReq = new Request(req.url, {
    method: req.method,
    headers: req.headers,
    body: reqBody,
  })

  const beResp = await fetch(beReq, { backend: "origin_0" });
  console.log('Response headers:', Object.fromEntries(beResp.headers));

  // Consuming the response body uses memory and means you must
  // create a fresh Response to send the same body to the client
  const beRespBody = await beResp.text();
  console.log('Response body:', beRespBody);

  return new Response(beRespBody, {
    status: beResp.status,
    headers: beResp.headers
  });
}