Our WorkAbout UsOur ApproachThe Journal
Contact »
« Back to the journal
PHP, Javascript & React

Hosting a ReactJS app (with routing) on AWS S3

By:

Mark Biek
Mark Biek

on 4/8/2019

As you may or may not already know, it’s super simple to host a static website from an AWS S3 bucket.

It’s fast, cheap, and you can even use a custom domain.

This makes it a great candidate for hosting React single-page applications!

One small issue is handling routing on the front-end.

If you’re using react-router, you already have friendly urls (like /page1 and /page2) for the different “pages” of your React app.

The problem on S3 is, without server-side rendering, when you refresh the page on one of those virtual urls, you’ll either get a 404 or 403 error since there isn’t a corresponding file in the S3 bucket.

Luckily there is a simple, albeit strange way, to handle it.

The first step is adding Routing Rules to the “Static website hosting” properties of your bucket.

props.png

The rules should look something like

This will make S3, in the case of any 404 or 403 error, rewrite the url with a #!/ prefix.

For example, if you navigate to http://mystaticsite.com/page1 and that’s a React route, it’ll change the url to http://mystaticsite.com/#!/page1.

Then we need to add a little code to our React app to change the url back to our friendly format (because #!/ urls are gross).

We’ll add the code below, just before our React app is rendered.

We check to see if the url is in #!/something format.

If it is, we grab the /something portion of the url and use the browser history API to replace the url.

Share to

Related Posts

PHP, Javascript & React
Wordpress to Sanity Data Script

By:Nick Stewart on 3/11/2021

One of the biggest challenges of moving from one CMS to another is getting your existing data to the new platform. In our case, we were moving our existing WordPress platform, which had been around for years, over to the Sanity.io platform.

Read More »
Developing the New via.studio

By:Alec Robertson on 6/14/2021

A deep dive into creating a fast, user-focused experience on the latest web technology stack for the new via.studio website.

Read More »