2

Cloudflare's R2 has an extension that prevents a NoSuchBucket error, by creating the bucket if it does not exist. To enable it, you're supposed to add a cf-create-bucket-if-missing: true header on the PutObject request. Can this header be set if we're using the @aws-sdk/client-s3 npm package? If so, how?

If the answer is no, is there an alternative workaround that you would recommend?

If it helps, I'm creating a backend nestjs API, and would like to include this header in outgoing requests.

3
  • 1
    Take a look at the middleware example.
    – jarmod
    Aug 9, 2022 at 16:39
  • @jarmod Brilliant! This is the answer. Aug 9, 2022 at 16:46
  • 1
    I'll add an answer and maybe you can review and correct as needed.
    – jarmod
    Aug 9, 2022 at 16:46

1 Answer 1

2

The AWS SDK v2 allows you to modify requests via Middleware.

Here’s an example of adding a custom header using middleware:

const client = new S3({ region: "us-east-1" });

client.middlewareStack.add(
  (next, context) => (args) => {
    args.request.headers["cf-create-bucket-if-missing"] = "true";
    return next(args);
  },
  {
    step: "serialize",
  }
);

const params = {}; // TODO: fill in usual PutObject params

await client.PutObject(params);

There's a good article that dives into the middleware stack here.

1
  • 1
    Thank you. The only thing I had to change was to set the middleware in the serialize step, rather than build. While both work for PutObject, the latter would cause my GetObject presigned url's to return a SignatureDoesNotMatch Error. Aug 9, 2022 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.