2021-03-29

Redirect URL through AWS Lambda and CloudFront

I have a lambda function and I wish to perform a 301 redirect from https://foo.test.com/user_id/bar/ to https://app.test.com/user_id/new

The user's request has an user_id that set as a variable (${userId}) and passed to the target URI (${newUri}).

The value of the user_id is numbers and letters (12-qw12)

I wrote the following code, which sets the ID as a variable and passes it to the Response Headers:

exports.handler = function handler(event, context, callback) {
    let request = event.Records[0].cf.request;
    let uri = request.uri;
    let userId = uri.split('/')[3];
    let newUri = `https://app.test.com/` + userId + `/new`;
    const response = {
        headers: {
            'location': [{
                key: 'Location',
                value: newUri,
            }],
        },
        status: '301',
        statusDescription: 'Moved Permanently',
    };
    callback(null,response);
};

Unfortunately, I get an empty value from the ${userId} that passed to the Response headers:

https://app.test.com//new

If I write the value in the response headers as a string (value: 'https://app.test.com/12-qw12/new') then it works properly.

How can I pass a variable (${userId}) to the response headers without getting an empty value?



from Recent Questions - Stack Overflow https://ift.tt/3dbRZnj
https://ift.tt/eA8V8J

No comments:

Post a Comment