cloudfront ESI / lambda html body replace

0

Hi,

as i know, now seem cloudfront not support ESI. and we are seeing whether we can use lambda to replace html body. eg: body = body.replace('<!-- NONCE_PLACEHOLDER -->', <script>var nonce = "${nonce}";</script>);

but, seem also not work.

any function we can call to replace?

since i think if we can replace, then we can write script in lambda and then get sth in server to replace ${nonce} variable and then send to client.

do u think is workable?

Regards

質問済み 2ヶ月前177ビュー
3回答
1

Hi Simon,

Lambda@Edge allows you to run Lambda functions to customize the content delivered through your CloudFront distribution.

Example of a Node.js Lambda@Edge function:

'use strict';

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

    // only modify HTML content !!
    if (headers['content-type'] && headers['content-type'][0].value.includes('text/html')) {
        let body = response.body;

        // generate a nonce value - you could generate a dynamic value
        const nonce = 'generatedNonceValue';

        // replace the placeholder in the body then update it
        body = body.replace('<!-- NONCE_PLACEHOLDER -->', `<script>var nonce = "${nonce}";</script>`);

        response.body = body;
    }

    // return
    callback(null, response);
};

Hope this helps.

profile picture
回答済み 2ヶ月前
profile picture
エキスパート
レビュー済み 2ヶ月前
0

Hi,

is it for lambda node v16, v18 or v20? and after make, i pout in Viewer request, Viewer response, Origin request or Origin response in cloudfront?

Regards

回答済み 2ヶ月前
  • For modifying HTML with Lambda@Edge, you can use Node.js versions 14.x or 16.x. Deploy the Lambda function to trigger on the Viewer Response or Origin Response events in CloudFront. If you encountered a 503 error, it might be due to handling large bodies or CloudFront limitations. Ensure your function doesn't exceed Lambda's memory and time limits, and check CloudWatch Logs for errors.

0

since i try to use body.replace before and seem make cloudfront return 503.

回答済み 2ヶ月前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ