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

const handler = async (event) => {
  // Avoid making changes to the original Request object.
  // It's always better to clone and create a new object.
  const originalReq = event.request;

  // Browsers identify the intended purpose of a request via the
  // Sec-Fetch-Dest header (https://w3c.github.io/webappsec-fetch-metadata/)
  let contentType = originalReq.headers.get("Sec-Fetch-Dest");

  // The above header is usually a good indicator but you should also strip querystrings
  // from any other URLs that you know are not affected by querystring.
  let url = new URL(originalReq.url);

  let stripQuery = (contentType && contentType.match(/^(audio|audioworklet|embed|font|image|manifest|object|paintworklet|script|sharedworker|style|track|video|worker|xslt)$/))
    || url.pathname.match(/\.(jpe?g|gif|png|webp|css|)$/);

  if (stripQuery) {
    console.log('Removing query string from URL ' + url);
    // Remove all query string
    url.search = new URLSearchParams();
    console.log('URL forwarded to origin is ' + url);
  }

  // Create a new Request object with an updated url
  const newReq = new Request(
    url.toString(),
    originalReq
  );

  // Forward the modified request to the origin.
  const backendResponse = await fetch(newReq, {
    backend: "origin_0"
  });
  // Send the backend response to the client.
  return backendResponse;
};