Use Lambda to Fix CloudFront/S3 CORS Issues
If you use S3 to serve static assets, you're going to have to configure S3 to deal with CORS issues.
Unfortuantly, S3 doesn't return Vary: Origin
unless an Origin
request header is present. This
causes CORS issues for browsers like Chrome since the original cached response from the GET request
will get reused for CORS evaluation due to the lack of Vary: Origin
.
The solution is to use a Lambda@Edge function to add the correct response headers from S3.
Steps to set up Lambda/CloudFront/S3:
- Make/update and S3 bucket and set the CORS policy to
s3_cors_policy.xml
. - Create a Lambda function with the code in
index.js
.- Create a new role using the default Lambda role.
- Modify the trust policy on the role use
trust_policy.json
. - Publish a version of the lambda function.
- Copy the Lambda ARN (make sure it included the version number)
- Create a CloudFront distro with your S3 bucket as the origin.
- Cache GET, HEAD, & OPTIONS requests
- Whitelist the
Origin
,Access-Control-Request-Headers
, andAccess-Control-Request-Method
headers. - Add the Lambda ARN copied above to the CloudFront Origin Response Event.
- Curl an asset from the distro and confirm that
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
is present for GET requests.
Information: