How to setup custom response header in AWS S3

user2757853 picture user2757853 · Aug 15, 2016 · Viewed 9k times · Source

I want to take my application to offline mode, and I want to register a service worker. My files are hosted in AWS S3 and I've created worker.js in the root of my bucket. I may need to return custom header "Service-Worker-Allowed" in response from AWS S3 for worker.js Currently custom headers are requiring to have x-amz-meta headers, which I can not use. Are there anyway to add that header by using Cloudfront or Cloudfare? Or any other suggestions?

Answer

Learner picture Learner · Jul 1, 2017

You can not set custom response headers with s3 or cloudfront.

You have 2 possible workarounds when using AWS.

  1. Proxy your requests. I.e. using nginx/haproxy running on ec2
  2. Using lambda@edge.

Option 2, lambda@edge is a simpler solution. It is designed to run a lambda function from a cloudfront edge node. You can use lambda@edge to run custom javascript code. You can configure your code to run before a http request is sent to cloudfront or after a http response is received from cloudfront. This allows you to set custom request or response headers. See https://medium.com/@tom.cook/edge-lambda-cloudfront-custom-headers-3d134a2c18a2 for a good write-up on how to do this.