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
/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.
The rules should look something like
This will make S3, in the case of any 404 or 403 error, rewrite the url with a
For example, if you navigate to
http://mystaticsite.com/page1 and that’s a React route, it’ll change the url to
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
If it is, we grab the
/something portion of the url and use the browser history API to replace the url.