Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set FunctionCode property for a CloudFront Function in a template file?

I'm trying to use cloud formation (YAML template file) to deploy a CloudFront Function in my stack. How do I specify the FunctionCode (AWS docs) property for my CloudFront Function?

AddHTMLPostfixFunction:
    Type: AWS::CloudFront::Function
    Properties:
      Name: !Sub "${ApplicationName}-add-html-postfix"
      AutoPublish: true
      FunctionCode: "---> Path to my .js-file? <---"
      FunctionConfig:
        Comment: "Adds .html postfix to viewer requests"
        Runtime: cloudfront-js-1.0

I'm unable to find any examples of this, other than the CLI commands that has been documented from AWS.

like image 334
borgerodsjo Avatar asked Oct 21 '25 16:10

borgerodsjo


1 Answers

It's possible to use inline code!

AddHTMLPostfixFunction:
    Type: AWS::CloudFront::Function
    Properties:
      Name: !Sub "${ApplicationName}-add-html-postfix"
      AutoPublish: true
      FunctionCode: |
        function handler(event) {
          var hasExtension = /(.+)\.[a-zA-Z0-9]{2,5}$/
          var request = event.request
          var uri = request.uri

          // If the request does not have any extension, add '.html'
          if (uri && !uri.match(hasExtension)) {
            request.uri = `${uri}.html`
          }

          return request
        }
      FunctionConfig:
        Comment: "Adds .html postfix to viewer requests"
        Runtime: cloudfront-js-1.0
like image 193
borgerodsjo Avatar answered Oct 26 '25 19:10

borgerodsjo