Hi @siddhant1!
I’m seeing the CORS errors when I try to upload to R2 using a presigned post request. Using using AWS S3 everything works, but when I switch over to R2 I start getting CORS errors.
Here’s what I’m doing:
My server side code is using the @aws-sdk/s3-presigned-post
library to generate params needed to post a file upload to R2.
import { S3Client } from '@aws-sdk/client-s3';
import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
let accountId = "XXX";
let accessKeyId = "XXX";
let secretAccessKey = "XXX";
let s3Client = new S3Client({
credentials: {
accessKeyId,
secretAccessKey,
},
region: "auto",
endpoint: `https://${accountId}.r2.cloudflarestorage.com`
});
let presignedPost = await createPresignedPost(s3Client, {
Bucket: bucket,
Key: key,
Fields: {
'Content-Type': "image/jpeg",
},
Expires: 60 * 60, // 1 hour
});
Next, the browser is using the data in presignedPost
to send the following XHR request to R2:
let file = "..." // the selected jpeg file from the file <input>
let formData = new FormData();
Object.entries({ ...presignedPost.fields, file }).forEach(
([field, value]) => {
formData.append(field, value);
}
);
let xhr = new XMLHttpRequest();
xhr.open('POST', presignedPost.url, true);
xhr.send(formData);
This sends a POST request to the URL: https://XXX.r2.cloudflarestorage.com/
with the following as form data:
Content-Type: image/jpeg
bucket: XXX
X-Amz-Algorithm: AWS4-HMAC-SHA256
X-Amz-Credential: XXX
X-Amz-Date: 20221201T030934Z
key: XXX
Policy: XXX
X-Amz-Signature: XXX
file: (binary)
And I receive the following error from R2.
Access to XMLHttpRequest at 'https://XXX.r2.cloudflarestorage.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have confirmed that my R2 bucket has been setup to allows CORS requests using:
await s3Client.send(
new PutBucketCorsCommand({
Bucket: "XXX",
CORSConfiguration: {
CORSRules: new Array({
AllowedHeaders: ["*"],
// Also tried using:
// AllowedHeaders: ["Content-Type"],
AllowedMethods: ["GET", "PUT", "POST", "HEAD"],
AllowedOrigins: ["*"],
ExposeHeaders: [],
MaxAgeSeconds: 3000
})
}
})
);
I’ve commented out my api keys, account id, bucket name, and other sensitive information with XXX
. Just to confirm, this all works when I use S3, but when I switch to R2 I start getting errors.
Hopefully this helps, but please let me know if there’s any more information I should provide.