Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby client side redirects to external URL not working on Netlify

I need to do a simple client side redirect to an external URL from a page on my Gatsby site hosted on Netlify. It works fine locally, but nothing seems to work when deployed. There also seems to be a bug with Gatsby's native createRedirect-functionality so that it doesn't allow redirecting to external URLs.

I've tried the three methods below in componentDidMount, in render as well as in callbacks from a recurring (setInterval) function call. I've also tried hijacking clicks on the links that leads to the redirect page and doing window.open(url), but nothing involving window seems to be working when deployed. Any ideas?

window.location.replace(url)
window.location.href = url
window.location = url
like image 407
oskare Avatar asked Mar 05 '23 17:03

oskare


1 Answers

You want to redirect from a url like /foo on your site to some external URL like domain.tld/bar, is that correct? If so, and you're using Netlify, then you probably want to use the Netlify _redirects file.

However, if you really want to do this inside of Gatsby, you should be able to use the componentDidMount() hook to call window.location.replace(). I've just tested on our v2 site and this works.

class About extends React.Component {
  componentDidMount() {
    window.location.replace("https://www.gatsbycentral.com/");
  }

There are some quirks during development, but this should work in production. I tested with a preview branch on Netlify and it worked for me.

If you have a specific error message you could post that as a new question.

like image 65
chmac Avatar answered Mar 09 '23 06:03

chmac