How to Redirect particular url to homepage instead of redirecting to 404 using gatsby?

Viewed 154

I have one url for example mysite.com?utm_source=fb when user trigger this url need to redirect to home page. i have tried client-side-redirect plugin but didn't worked out

Thank you.

1 Answers

Use onClientEntry API (from Gatsby browser) to trigger a function once the user enters your site. In your gatsby-browser.js:

export const onClientEntry = () => checkUtm();

checkUtm() is your checker function, place it wherever you want and import it in your gatsby-browser.js. The function should look like this:

export const checkUtm = ()=>{
    if (typeof window !== "undefined"){
      const queryString = window.location.search;
      const urlParams = new URLSearchParams(queryString);
      const fromFb = urlParams.get('utm_source') === "fb";
    
      if(fromFb) navigate("/");
    }
}

typeof window !== "undefined" condition is important to avoid code-breaking, since, at the compiling time, window (or other global objects) may not be defined yet.

The rest of the code can be manipulated to fit your exact requirements, I've added navigate from Gatsby but change it as you need.

I have one more doubt in the same if i have url ex: mysite.com?utm_source=IwAR1AjzvBHLFOp0CeER8X1XdBgGbLDyK9hDh2dVBe15ZXnWjEAae-C0sT67M like this and every time string will change how to implement

This should work:

export const checkUtm = ()=>{
    if (typeof window !== "undefined"){
      const queryString = window.location.search;
      const urlParams = new URLSearchParams(queryString);
      const hasUtmSource = urlParams.get('utm_source');
    
      if(hasUtmSource) navigate("/");
    }
}

The const hasUtmSource = urlParams.get('utm_source'); statement will get any value of the utm_source parameter so, if it exists, it will validate the next condition, making the navigate("/").

Related