I am using Cloudflare R2 with @aws-sdk/client-s3
inside of a serverless function.
Here I attempt to add an object to my bucket ('my-bucket');
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
const s3Client = new S3Client({
region: "auto",
endpoint: R2_URL,
credentials: {
accessKeyId: R2_ACCESS_KEY_ID,
secretAccessKey: R2_SECRET_ACCESS_KEY,
},
});
const putObject = new PutObjectCommand({
Bucket: "my-bucket",
Key: "test.png",
Body: outputBuffer,
ContentType: "image/png",
});
s3Client.send(putObjectCommand);
In the Cloudflare R2 console I can see that my object was created in the correct bucket but the bucket name is present in the key as my-bucket/test.png
. I would expect the key to be simply test.png
.
What can I do to ensure the object is created with only the specified key?
I didn't realize that the S3 compatible URL in the R2 console includes the bucket name by default when you copy it from the UI.
Removing the
<BUCKET_NAME>
from myR2_URL
fixed my issue.