amazon-web-servicesaws-lambda-edge

Setting HTTP Headers with Lambda@Edge


I am trying to add some new http headers for security purposes on my site. The site uses Cloudfront for the CDN and Im using Lamdba@Edge to run the following node function on the origin response:

exports.handler = async (event, context) => {
    const response = event.Records[0].cf.response;
    const headers = response.headers;

//Set new headers 
 headers['strict-transport-security'] = [{key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubdomains; preload'}]; 
 headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'"}]; 
 headers['x-content-type-options'] = [{key: 'X-Content-Type-Options', value: 'nosniff'}]; 
 headers['x-frame-options'] = [{key: 'X-Frame-Options', value: 'DENY'}]; 
 headers['x-xss-protection'] = [{key: 'X-XSS-Protection', value: '1; mode=block'}]; 
 headers['referrer-policy'] = [{key: 'Referrer-Policy', value: 'same-origin'}]; 


    return response;
};

Im adding a CloudFront trigger to the function and redeploying the CDN successfully (accordingly to the AWS console), but the new headers are not being added to the site as needed. I feel like Im viewing the cache site and not the latest. Do I need to empty a cache or something similar prior to the CDN adding the new headers?


Solution

  • If there is a cache these headers will not be attached. If they must attached outside of the caching later instead move this to the viewer response.

    Invalidating the cache should get these to display, but they’ll be cached after