Add a cross-origin resource sharing (CORS) header to the response - Amazon CloudFront

Add a cross-origin resource sharing (CORS) header to the response

The following viewer response function adds an Access-Control-Allow-Origin HTTP header to the response if the response doesn’t already contain this header. This header is part of cross-origin resource sharing (CORS). The header’s value (*) tells web browsers to allow code from any origin to access this resource. For more information, see Access-Control-Allow-Origin on the MDN Web Docs website.

See this example on GitHub.

JavaScript runtime 2.0
async function handler(event) { const request = event.request; const response = event.response; // If Access-Control-Allow-Origin CORS header is missing, add it. // Since JavaScript doesn't allow for hyphens in variable names, we use the dict["key"] notation. if (!response.headers['access-control-allow-origin'] && request.headers['origin']) { response.headers['access-control-allow-origin'] = {value: request.headers['origin'].value}; console.log("Access-Control-Allow-Origin was missing, adding it now."); } return response; }
JavaScript runtime 1.0
function handler(event) { var response = event.response; var headers = response.headers; // If Access-Control-Allow-Origin CORS header is missing, add it. // Since JavaScript doesn't allow for hyphens in variable names, we use the dict["key"] notation. if (!headers['access-control-allow-origin']) { headers['access-control-allow-origin'] = {value: "*"}; console.log("Access-Control-Allow-Origin was missing, adding it now."); } return response; }