Redirect on UTM & 404

I’m not a developer (designer really) but I’m needing to setup a worker that will redirect to a specific location if 2 items are true.

  1. I need a specific UTM parameter in the URL to be found.
  2. I need the page in question to return a status of 404.
    If both of those exists then redirect to a new pre-determined URL.

Currently it is redirecting on any page not found and I only need it to do that if the page is not found and the UTM is in the URL.

Here’s the code:

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

  async function handleRequest(request) {

    const response = await fetch(request);
    const params = new URLSearchParams(request);
      
    if  ( params.getAll('geo-targetly') && response.status === 404) {

      const base = "https://www.newsite.com/";
      const statusCode = 301;
  
      const destinationURL = `${base}`;
      console.log(destinationURL);
  
      return Response.redirect(destinationURL, statusCode);
    }
  
    return response;
  }

Any help is appreciated.

I was able to get it resolved.

addEventListener('fetch', (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);

  // Check if the URL contains the 'utm_source=geo_targetly' parameter
  if (url.searchParams.get('utm_source') === 'geo_targetly') {
    // Fetch the original resource
    const response = await fetch(request);

    // Check if the response status code is 404
    if (response.status === 404) {
      // Redirect to the root domain and the first subfolder with a 301 status code
      const rootDomain = `${url.protocol}//${url.hostname}`;
      const firstSubfolder = url.pathname.split('/')[1]; // Get the first subfolder
      const redirectTo = `${rootDomain}/${firstSubfolder}`;
      return Response.redirect(redirectTo, 301);
    }

    // If the response status code is not 404, return the original response
    return response;
  }

  // If the 'utm_source' parameter is not present, simply return the original request
  return fetch(request);
}

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.