How to setup CORS for Cloudflare R2 bucket using AWS CLI

Nov 20, 2022 | 2 minute read

As of 2022-11-20:

Currently, you have to use the S3 API PutBucketCors to configure CORS for your bucket. ~Cloudflare

The simplest way to setup CORS for your R2 bucket is to use AWS CLI. To make it work with R2 properly, you need to include --endpoint-url pointing to your R2 bucket URL.

First of all, configure CLI according to instructions on Cloudflare docs

You need to use put-bucket-cors command.

Create JSON file containing CORS rules. Following rule is accepting GET connections from all origins:

s3cors.json:


{
  "CORSRules": [
      {
          "AllowedOrigins": ["*"],
          "AllowedHeaders": ["*"],
          "AllowedMethods": ["GET"]
      }
  ]
}

Use following command as an example:

aws s3api put-bucket-cors --bucket my-bucket --endpoint-url https://abcdefghijklmnopqrstuvw.r2.cloudflarestorage.com --cors-configuration file:///Users/patryk/s3cors.json

--bucket: name of your bucket

--endpoint-url: URL of S3 API endpoint (find it in Cloudflare dashboard in bucket details), stripped of bucket name from the end

--cors-configuration: path to configuration JSON file prefixed with file:///

If successful, CLI will not return any message after run.


Development