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"
}
]
}
}
}
}
]
}
I have followed these guides but they don't define request.origin, they define request and do origin = request.origin or just simply use request.origin instead of origin variable. https://aws.amazon.com/tr/blogs/networking-and-content-delivery/dynamically-route-viewer-requests-to-any-origin-using-lambdaedge/ https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html
I am going to try define request.origin fields for two origins.