0

Can some please tell me how to route to 2 different origins based on cookies using Lambda@Edge? I tried below code, but it is not working. Thanks in advance.

 'use strict';

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

    //Setup the two different origins
    const originA = "site1.example.com";
    const originB = "site2.example.com";


    //Determine whether the user has visited before based on a cookie value
    //Grab the 'origin' cookie if it's been set before
    if (headers.cookie) {
        for (let i = 0; i < headers.cookie.length; i++) {
            if (headers.cookie[i].value.indexOf('origin=A') >= 0) {
                console.log('Origin A cookie found');
                headers['host'] = [{key: 'host',          value: originA}];
                origin.s3.domainName = originA;
                break;
            } else if (headers.cookie[i].value.indexOf('origin=B') >= 0) {
                console.log('Origin B cookie found');
                headers['host'] = [{key: 'host',          value: originB}];
                origin.s3.domainName = originB;
                break;
            }
        }
    }    

    callback(null, request);
};
dssenthil
  • 5
  • 1
  • 1
    Can you tell us what isn't working? – cementblocks Aug 31 '18 at 14:26
  • @cementblocks Thanks for your response. I get X-Cache: LambdaExecutionError from cloudfront after implementing the function and browsing the site with hosts file entry. – dssenthil Sep 01 '18 at 12:04
  • I would check a couple things. Do you have the correct trust policy for your lambda role? It should trust edgelambda.amazonaws.com and lambda.amazonaws.com. Test your function in the lambda console to make sure is executes without error. – cementblocks Sep 01 '18 at 20:08
  • @cementblocks Thanks for your time and suggestions, I will check and let you know. – dssenthil Sep 02 '18 at 07:20

1 Answers1

0

It looks like you are not using an s3 origin. Changing s3 to custom in your code will fix the problem.

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