Skip to content

Instantly share code, notes, and snippets.

@mikeesto
Last active October 4, 2022 17:45
Show Gist options
  • Save mikeesto/a702290925d90ee32b550a8981a657d2 to your computer and use it in GitHub Desktop.
Save mikeesto/a702290925d90ee32b550a8981a657d2 to your computer and use it in GitHub Desktop.
Set CORS for Cloudflare R2
import aws from "aws-sdk";
const s3 = new aws.S3({
endpoint: `https://${process.env.CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com`,
accessKeyId: process.env.CLOUDFLARE_ACCESS_KEY,
secretAccessKey: process.env.CLOUDFLARE_SECRET_ACCESS_KEY,
signatureVersion: "v4",
});
const config = {
AllowedHeaders: ["content-type"], // This seems to be necessary! Not including it gives errors. Putting it as * still gives CORS errors
AllowedMethods: ["PUT"],
AllowedOrigins: ["*"],
};
const bucketParams = {
Bucket: process.env.CLOUDFLARE_BUCKET_NAME,
CORSConfiguration: { CORSRules: new Array(config) },
};
s3.putBucketCors(bucketParams, function (err, data) {
if (err) {
console.log("Error", err);
} else if (data) {
console.log("Success", JSON.stringify(data.CORSRules));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment