How can I modify a page's HTML with AWS Cloudfront running a Lambda@Edge function?

Viewed 1246

I'm running a CloudFront distribution, which has a Lambda@Edge function running on it.

I'd like to manipulate the DOM of the page that CloudFront is in front of. Specific example: add a custom script to the page inside the head.

On Cloudflare this can be done easily in a worker (roughly equivalent product) using their HTMLRewriter class.

How can I do this on AWS CloudFront?

My working theory is:

  • Observe the request for the HTML page
  • Do some kind of manipulation of the body of the response - parse it into the DOM object and manipulate as needed

I haven't managed to get this working yet. Interested in other approaches or if I'm missing something obvious.

2 Answers

Do a replace on the body of the request where uri === '/', to modify the string of HTML.

I tried that and it works fine.

The request where uri === '/' should be the request for the HTML page.

So in my specific case, I simply did a replace on the body of that request (which is stringified HTML):

body.replace(
      `</head>`,
      `<script>
      console.log('my script')
      </script></head>`
    )

And this worked.

You could also bring in some kind of DOM-parsing library to do this kind of manipulation in a more elegant fashion.

I've created a method to add GTM scripts inside <header> and <body>, using the @lou1989 response. Here are the code and some explanation.

Related