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 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南