Add a cross-origin resource sharing (CORS) header to the response - Amazon CloudFront
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

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

The following example 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.

This is a viewer response function.

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; }