I am hosting a react app on AWS using AWS CloudFront and AWS S3.
Specifically, the S3 contains the built react app code. The bucket itself doesn’t use S3 Static website hosting: instead, the files of the bucket should be available to CloudFront, since the Bucket policy looks similar to this:
{
"Version": "2008-10-17",
"Id": "PolicyForCloudFrontPrivateContent",
"Statement": [
{
"Sid": "AllowCloudFrontServicePrincipal",
"Effect": "Allow",
"Principal": {
"Service": "cloudfront.amazonaws.com"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::react-app/*",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::xxx:distribution/xxx"
}
}
}
]
}
The CloudFront distribution has an origin that looks like this:
Origin name: react-app.s3.us-east-1.amazonaws.com
Origin domain: react-app.s3.us-east-1.amazonaws.com
Origin type: S3
The website seems to be successfully hosted and working. However sometimes (for example when I try to do a Lighthouse scan), CloudFront returns, rather than the actual page, an error that looks like this:
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>AAF5Y58QHZEAR6BS</RequestId>
<HostId>Z7/3LgKA4JAQMwuzsgIQqRop37/f70H8sdZxZIcpZTKJCYZUDgFHds5jnPxZPbPEea466qwH8OY=</HostId>
</Error>
The error goes away whether I refresh the page or I navigate to another URL. Why does this happen? Am I doing something wrong? How can I fix this?
Thanks in advance.