Proxying Signed AWS S3 URLs using CloudFlare Workers

A common use case for S3 is hosting content that should not be available to the public, but needs to be made available to specific user(s) or for a specific length of time. A great example of this is granting access to digital files after a purchase or subscription payment.

In this case, I needed the domain to be a first-party subdomain, rather than a default Amazon AWS domain, due to same-origin policy requirements.

Hat-tip to Fershad Irani for an initial version, which I modified to suit my needs.

Set up the AWS Bucket

  1. Create a bucket
  2. Prevent all public access to objects in the bucket
  3. Upload files

Configure a Cloudflare Worker

  1. Go to CloudFlare > Workers & Pages > Overview and create a new application
  2. Add the worker code below, modifying line 8 to use your bucket name
  3. Publish the worker
  4. If you already added the subdomain under the DNS tab pointing to anywhere, delete that before proceeding
  5. View the worker and go to the Triggers tab
  6. Under Custom Domains, add a custom domain (documentation) and enter your custom subdomain
  7. Under Routes, add a route for your custom subdomain