Serving a React app with s3 and Cloudfront

amazon s3amazon-cloudfront

I'm wondering if this is feasible. I'm thinking about serving a React app using s3 and Cloudfront.

Some of the routes are prerendered, and can be served as static index.html files. Other routes, on the other hand, need to be handled by client side routing.

What I want s3 to do is if somebody asks for a route that isn't prerendered, I would want to serve a default index.html file instead of 404. I don't want to return a redirect response, because the url needs to stay the same to be handled by client side routing.

Is it possible to do this with s3? Or maybe from Cloudfront, it there a way to detect a 404 response from s3 and return a default file?

By "routes" I mean urls. So there are some urls for which I want to serve an html file, and for all others, I want to serve a default html file. (If the request has text/html mimetype)

Best Answer

If I understand your question correctly, you're wanting to forward all 404 errors to a specific HTML page, and return a 200 response rather than a 404 to the user.

This can easily be configured via CloudFront. Check out this blogpost on how to do it. Specifically, read the final section on CloudFront.

Basically, there's an area on the CloudFront configuration that allows you to do exactly what you're trying to do, and will allow you to map specific errors to files, and return whatever response code you want to.

In case you're using CloudFormation to outline your CloudFront distributions, and would like to update your CloudFormation templates to accomplish this, you would add the following under the DistributionConfig property of the Resource:

CustomErrorResponses:
  -
    ErrorCode: 404
    ResponseCode: 200
    ResponsePagePath: /index.html
Related Topic