Removing HTML comments via CloudFront

To remove HTML comments in CloudFront, you can use Lambda@Edge to modify the response before it is returned to the viewer.

Here’s an example of how you can configure a Lambda function to remove HTML comments in CloudFront:

1. Create a new Lambda function in the AWS Lambda console:

  • Go to the AWS Lambda console: https://console.aws.amazon.com/lambda/
  • Click on “Create function”.
  • Choose an appropriate name, runtime (e.g., Node.js 14.x), and execution role for your function.
  • Click “Create function” to create the Lambda function.

2. Configure the Lambda function:

In the Lambda function code editor, replace the default code with the following example code:

  • exports.handler = async (event) => {
    const response = event.Records[0].cf.response;
    const headers = response.headers;const contentType = headers['content-type'][0].value;
    if (contentType.includes('text/html')) {
    const body = response.body;
    const decodedBody = Buffer.from(body, 'base64').toString('utf-8');
    const modifiedBody = decodedBody.replace(/<!--[\s\S]*?-->/g, '');
    response.body = Buffer.from(modifiedBody, 'utf-8').toString('base64');
    headers['content-length'] = [{ key: 'Content-Length', value: response.body.length.toString() }];
    } return response;
    };
  • This example code checks if the response content type is HTML (text/html). If so, it removes all HTML comments from the response body using a regular expression.
  • Click “Deploy” or “Save” to save the Lambda function.

3. Create a CloudFront trigger for the Lambda function:

  • Go to the CloudFront console: https://console.aws.amazon.com/cloudfront/
  • Select your CloudFront distribution.
  • Click on the “Behaviors” tab.
  • Select the behavior for which you want to remove HTML comments.
  • Click on “Edit” to modify the behavior settings.
  • In the “Lambda Function Associations” section, add a new “Viewer Response” event trigger.
  • Select the Lambda function you created earlier from the dropdown list.
  • Click “Save changes” to update the behavior settings.

After you have completed these steps, the Lambda function will be triggered for each viewer response from the selected CloudFront behavior, removing HTML comments from the response body.

Keep in mind that this example removes all HTML comments from the response. If you have specific requirements or want to preserve certain types of comments, you can modify the regular expression accordingly.

You may also read these articles