Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 403 Access Denied Errors When Hosting a React Router App in AWS S3 and CloudFront

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.

like image 399
Chamin Wickramarathna Avatar asked Nov 22 '25 05:11

Chamin Wickramarathna


2 Answers

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.

CloudFront - Error pages tab.  Create custom error response.

like image 179
Mark Hall Avatar answered Nov 24 '25 19:11

Mark Hall


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

like image 20
aleochoam Avatar answered Nov 24 '25 19:11

aleochoam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!