When I deployed a React Router app to AWS S3 and CloudFront and when I try to access React routes directly it gives the following error with 403 error code. I can access both the base URL(www.sample-app.com) and route URLs(www.sample-app.com/cart) when it flows through the app.
But If I try going directly to a React route(www.sample-app.com/cart) it produces a 403 Access Denied error as follows. The major pain point is it produces this error when I try to refresh a React route URL.
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>REQUEST_ID</RequestId>
<HostId>HOST_ID</HostId>
</Error>
Note: I'm using AWS load balancer and Lambda functions as backend. I have setup AWS ALB and Cloudfront to authenticate users with AWS Cognito.
Appreciate your help on this.
Easiest option, hands down, is to create a simple custom error in the your CloudFront instances "Error pages" tab. See the attached image. It's a 30 second fix and works as soon as it auto-deploys.

Because cloudfront can only access files that do exist in the bucket, and if a nonexisting object is request it will return 403, you need to add a custom error page, that returns the index.html file with a 200 status code. Then, because the index.html was returned, the React Router can do its job.
More info here:
https://www.codebyamir.com/blog/fixing-403-access-denied-errors-when-hosting-react-router-app-in-aws-s3-and-cloudfront
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With