Search code examples
javascriptamazon-web-servicesamazon-cloudfrontcloudfront-functions

Avoid export error for AWS CloudFront Function and doing unit tests


How can I avoid this error: "The CloudFront function associated with the CloudFront distribution is invalid or could not run. SyntaxError: Illegal export statement", and still be able to unit test a function?

Example function for CloudFront function

//myfun.js

function handler (event) {
   return event.request;
}

Test code for jest

const handler = require('./myfun.js');

test('handler runs', () => {
  expect(handler({request: {}})
  ).toStrictEqual({});

});

Running jest, would generate an error like : TypeError: rewrite is not a function


Solution

  • Due to limitations in CloudFront functions runtime, it is not possible at the moment to run functions with export and other mechanisms.

    A quick workaround is to avoid deploying the code from file and read it with an IaC tool that allows preprocessing, eg: cdk.

    Example in python cdk

    Where the extra line was added at the end of myfun.js

    ...
    
    module.exports = handler;
    

    And the CDK code to create the CFN Function resource is:

    CF_FUNCTION_FILE = "./myfun.js"
    
    output = []
    with open(CF_FUNCTION_FILE) as f:
      output += f.readlines()[:-1]  # Skip last line
    
    aws_cloudfront.Function(
      self, "myCFfun",
      code=aws_cloudfront.FunctionCode.from_inline("\n".join(output))
    )