DEV Community

Eetu Tuomala for AWS Community Builders

Posted on

Serve a React App from the S3 Bucket

An S3 bucket is a great place to serve static content like a web app build with React. Here are a few tips and tricks that will help you to get started.

The S3 bucket has a feature that allows static website serving, but the downside is that it doesn't support HTTPS. Nowadays, plain HTTP is not an option. So for HTTPS support, a CloudFront distribution is needed. It also enables custom domain name, Web Application Firewall and a lot of other cool features. And if you have an API in your service, you can add that to CloudFront and serve everything from the same origin to mitigate the CORS pain.

The S3 bucket is not a web server, so routing causes some issues. When using React router, routing works fine when you enter the site, but a 403 error is returned when opening an URL with a route resource, like mydomain.com/users. This is because the browser tries to access the /users file from the bucket, and as it's a React router path, the file doesn't exist in the S3 bucket. If you are wondering why it's 403 instead of 404 is because the bucket is not public.

How to prevent this is to modify the CloudFront error response in case of 403 error to be index.html, which routes all failed requests to the index.html and returns 200 status code.

 errorResponses: [
  {
    httpStatus: 403,
    responseHttpStatus: 200,
    responsePagePath: "/index.html",
    ttl: Duration.seconds(0),
  },
]
Enter fullscreen mode Exit fullscreen mode

This way, every time a file is not found from the path, it returns index.html and React router kicks in and handles the routing.

In the example repository https://github.com/laardee/deploy-react-app there is an infra stack build with AWS CDK and a simple React app that has router included.

Top comments (0)