Cookie based routing on CloudFront

0

Hello All!

I'm trying to route traffic based on a cookie with a Lambda function. But getting this error message when I test it and I couldn't figured out why. I would be glad if anyone can point me to right direction.

ERROR Invoke Error {"errorType":"TypeError","errorMessage":"Cannot read properties of undefined (reading 's3')","stack":["TypeError: Cannot read properties of undefined (reading 's3')"," at Runtime.exports.handler (/var/task/index.js:16:32)"," at Runtime.handleOnce (file:///var/runtime/index.mjs:548:29)"]}

or it says "Cannot read properties of undefined (reading 'custom')" when I send another cookie value.

My code is this and using runtime Node.Js 16.x

'use strict';

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

    //Setup the two different origins
    const originA = '<s3 origin url>';
    const originB = '<load balancer url>';

	//check v2=true cookie if exists
    if (request.headers.cookie) {
        for (let i = 0; i < request.headers.cookie.length; i++) {
            if (request.headers.cookie[i].value === 'v2=true') {
                console.log('Origin A cookie found');
                request.headers['host'] = [{key: 'host', value: originA}];
                request.origin.s3.domainName = originA;
                break;
            } 
            else {
                console.log('Origin B cookie found');
                request.headers['host'] = [{key: 'host', value: originB}];
                request.origin.custom.domainName = originB;
                break;
            }
        }
    }
    
        callback(null, request);
};

I am testing it with the below code.

{
  "Records": [
    {
      "cf": {
        "config": {
          "distributionId": "<my distrubitonid>"
        },
        "request": {
          "uri": "/",
          "method": "GET",
          "clientIp": "<my ip>",
          "headers": {
            "cookie": [
              {
                "key": "Cookie",
                "value": "v2=true"
              }
            ]
          }
        }
      }
    }
  ]
}
1개 답변
0

I believe the issue is that request.origin is never defined, so the following lines are going to fail as undefined.

request.origin.s3.domainName = originA;
request.origin.custom.domainName = originB;

To quickly test this, add an empty request.origin object in your test object. It should pass.

The fix is to define request.origin. You could do something like the following right after your const request variable definition.

let request.origin

profile pictureAWS
답변함 2년 전

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

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

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

관련 콘텐츠