All Articles

Unexpected redirection with gatsby, s3 and cloudfront

You’ve come here because you probably already deployed a gatsby site to s3, are serving it with cloudfront but still you find some strange behavior related to redirections. I was certainly suffering it. Turns out almost everything was fine, nothing seemed off. Basically i had a simple page that rendered a simple component made with react-table, and another one that had custom routing (using reach-router, of course) and client-paths. The former was always redirecting to the root of the project (but it didn’t even have a redirection in it!); the latter was working just fine with its custom routing and redirections.

Long story short, i search for a while and, among other things i found two key pieces, one of them was a related issue in stack overflow: there was this comment referencing having this issue with gatsby, i wanted to comment but i didn’t have enough of a reputation to do it.

Meanwhile i kept searching and also found this issue, that seemed like my original problem. One comment by @JoshuaWalsh pointed towards this guide to setup cloudfront correctly.

Turns out the problem was the origin i had in my cloudfront distribution:

What i had was de s3 Origin one, instead of Custom Origin. When you add an origin to your cloudfront distribution the input autocompletes with your s3 buckets amongst other things, but what i really needed was the s3 endpoint from “static website hosting” property of the corresponding bucket, not the bucket itself.

One important detail is that if you are in the same boat as i was, you have that origin tied to cache behavior. In order to remove that origin you must:

  1. Add the new origin
  2. Edit the cache behavior to use the new origin
  3. Remove the old origin