Creating a cloudfront function in typescript using the CDK

0

I am trying to figure out how to write a cloudfront edge function in typescript using cdk 2.94.0. The way you specify these functions is weirder than a regular lambda you'd use with some other service like API Gateway. In this case, what i get is:

Error: Asset must be a .zip file or a directory (C:\work\i4academy\lib\redirect-handler.ts)

That's telling me that it won't really work with a higher level function wrapper like NodejsFunction. Unfortunately, that's what I need if I'm starting with typescript, as I need something to compile the typescript into javascript then build an appropriate distribution .zip.

I think I'm close to having this, just not quite figuring out the last piece, which is to make cloudfront use the lambda:

        const fnRole = new iam.Role(this, "redirect-function-role-id", {
            roleName: "redirect-function-role",
            assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com')
        })
        fnRole.grantAssumeRole(new iam.ServicePrincipal('edgelambda.amazonaws.com'))

        const fnOpts: NodejsFunctionProps = {
            // ...props.baseLambdaConfig.baseLayers,
            functionName: "",
            runtime: lambda.Runtime.NODEJS_LATEST,
            bundling: {
                minify: true
            },
            entry: path.join(__dirname, "redirect-handler.ts"),
            handler: "handler",
            role: fnRole,
            architecture: lambda.Architecture.ARM_64,
            memorySize: 128,
            timeout: cdk.Duration.seconds(2),
            reservedConcurrentExecutions: undefined /* impacts cost */,
        }
        const redirectFunction = new nodejs.NodejsFunction(this, "redirect-function-id", fnOpts);


        const cfdist = new cloudfront.Distribution(this, 'cloudfront-dist', {
            defaultBehavior: {
                origin: new origins.HttpOrigin("www.something.com"),
                functionAssociations: [{
                    function: redirectFunction,
                    eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
                }]
            },
        });

I'm thinking maybe this is not possible if I want to use a cloud function. I think I could convert it to a lambda@edge but it would be six times the cost per request. That should not really be necessary, it's a really simple function - it looks at the incoming request then makes a decision about where to 301 redirect.

So is it even possible to write a cloudfront function (not lambda@edge) in typescript?

2개 답변
1
수락된 답변

CloudFront Functions only support a restricted subset of JavaScript. TypeScript is not natively supported for CloudFront Functions. You can write your function in TypeScript and then transpile it down to JavaScript, but you have to ensure that the generated JavaScript code adheres to the limitations imposed by CloudFront Functions.

AWS CDK does support CloudFront Functions, but the CDK constructs for CloudFront Functions expect the function code to be a simple string containing the JavaScript code or a path to a .js file.

To use TypeScript for this, you could:

  1. Write your function logic in TypeScript.
  2. Transpile it to JavaScript.
  3. Make sure the generated JavaScript adheres to CloudFront Function's limitations.
  4. Use the JavaScript code as the code parameter for your EdgeFunction in CDK.
AWS
답변함 8달 전
profile picture
전문가
검토됨 4달 전
0

I think I'm going to answer my own question and reflect upon the limitations of a Javascript that runs as a Cloudfront Function and all the associated limitations. Based on that, what I asked doesn't make a whole lot of sense. The code is small, I just preferred it be fully typed. I decided to live without.

profile picture
wz2b
답변함 8달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠