CORS Error on CloudFront + S3

ruucm
Today I Solved
Published in
May 31, 2021

What

When you need to access a distributed files on the CloudFront directly in the code, you need to config CORS settings.

For example.

import { appendDiv } from "https://module.harbor.school/dist/examples/append-div.js";appendDiv("Hello from inline script");

Or it emits wtf CORS errors.

How

  1. Set a CORS Configuration for your S3 bucket, including

<AllowedOrigin>*</AllowedOrigin>

[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"HEAD"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [],
"MaxAgeSeconds": 3000
}
]

2. In CloudFront -> Distribution -> Behaviors for this origin

  • Allowed HTTP Methods: +OPTIONS
  • Cached HTTP Methods +OPTIONS
  • Cache Based on Selected Request Headers: Whitelist the Origin header.

3. Wait for ~20 minutes while CloudFront propagates the new rule.

That’s it!

Credit

https://stackoverflow.com/questions/12358173/correct-s3-cloudfront-cors-configuration

--

--