addEventListener("fetch", event => {
  // Get the request from the client.
  const req = event.request;
  let url = new URL(req.url);
  const params = url.searchParams;

  if (params.get("user") && params.get('pw')) {
    // Get user and pw from URL
    const userValue = params.get('user');
    const pwValue = params.get('pw');

    // base64 encode
    const encodedauth = btoa(userValue+':'+pwValue);

    // Set to Authorization header
    req.headers.set("Authorization", 'Basic '+encodedauth);

    // Remove query string
    params.delete('user');
    params.delete('pw');

    // Clean up URL
    if (params.toString() == "") {
      url = location.pathname;
    }
  }

  const bereq = new Request(url, req);

  // Send the request to `origin_0`.
  const backendResponse = fetch(bereq, {
    backend: "origin_0"
  });

  // Send the backend response back to the client.
  event.respondWith(backendResponse);
});