Some of R2’s extensions require setting a specific header when using them in the S3 compatible API. For some functionality you may want to set a request header on an entire category of requests. Other times you may want to configure a different header for each individual request. This page contains some examples on how to do so with boto3 and with aws-sdk-js-v3.
Setting a custom header on all requests
When using certain functionality, like the cf-create-bucket-if-missing header, you may want to set a constant header for all PutObject requests you’re making.
Set a header for all requests with boto3
Boto3 has an event system which allows you to modify requests. Here we register a function into the event system which adds our header to every PutObject request being made.
Set a header for all requests with aws-sdk-js-v3
aws-sdk-js-v3 allows the customization of request behavior through the use of its middleware stack ↗. This example adds a middleware to the client which adds a header to every PutObject request being made.
Set a different header on each request
Certain extensions that R2 has provided in the S3 compatible api may require setting a different header on each request. For example, you may want to only want to overwrite an object if its etag matches a certain expected value. This value will likely be different for each object that is being overwritten, which requires the If-Match header to be different with each request you make. This section shows examples of how to accomplish that.
Set a header per request in boto3
To enable us to pass custom headers as an extra argument into the call to client.put_object() we need to register 2 functions into boto3’s event system. This is necessary because boto3 performs a parameter validation step which rejects extra method arguments. Since this parameter validation occurs before we can set headers on the request, we first need to move the custom argument into the request context before the parameter validation happens. In a subsequent step we can now actually set the headers based on the information we put in the request context.
Set a header per request in aws-sdk-js-v3
Here we again configure the header we would like to set by creating a middleware, but this time we add the middleware to the request itself instead of to the whole client.