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 réponse
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
répondu il y a 2 ans

Vous n'êtes pas connecté. Se connecter pour publier une réponse.

Une bonne réponse répond clairement à la question, contient des commentaires constructifs et encourage le développement professionnel de la personne qui pose la question.

Instructions pour répondre aux questions