Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Cookie in http response header from AWS lambda Node JS

I have a Lambda proxy integration enabled, and setting the response headers as part of Lambda output and API Gateway that will return them as part of the HTTP response to the client.

Sample code:

callback(null, {
    "statusCode": 302,
    "Location" : "https://somewebsite.com"
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
});

I need to send out 3 cookies in the headers. I tried. But, failed:

callback(null, {
    "statusCode": 302,
    "Location" : "https://somewebsite.com"
    "headers": { "Set-Cookie": [cookie1String, cookie2String, cookie3String] },
    "body": "..."
});

[Edit] I concatenated the cookie and passed in as the response, the client gets the cookie. But when the client calls the target in "location", the request does not have the cookie in the header.

callback(null, {
    "statusCode": 302,
    "Location" : "https://somewebsite.com"
    "headers": { "Set-Cookie": c1=cookie1String;c2=cookie2String; c3=cookie3String] },
    "body": "..."
});

Please help in sending these 3 cookies out to my client.

like image 810
Anil Pediredla Avatar asked Dec 02 '22 11:12

Anil Pediredla


1 Answers

Use multiValueHeaders instead of headers.

    const response = {
        isBase64Encoded: true,
        statusCode: 200,
        multiValueHeaders : {"Set-Cookie": [`language=${language}`, `theme=${theme}`]},
        body: JSON.stringify('User profile set successfully')
    };
    callback(null, response);

If you need it to be smarter, consider something like

function createHeaders(headers) {
  const defaultHeaders = {
    'Access-Control-Allow-Origin': '*',
  };
  const allHeaders = Object.assign({}, defaultHeaders, headers);
  const singleValueHeaders = {};
  const multiValueHeaders = {};
  Object.entries(allHeaders).forEach(([key, value]) => {
    const targetHeaders = Array.isArray(value) ? multiValueHeaders : singleValueHeaders;
    Object.assign(targetHeaders, { [key]: value });
  });

  return {
    headers: singleValueHeaders,
    multiValueHeaders,
  };
}

Then use it in the callback function.

callback(null, {
  statusCode: status || 200,
  body: JSON.stringify(body),
  ...createHeaders({ 'Set-Cookie': cookie }),
});
like image 92
Naijia Liu Avatar answered Dec 05 '22 18:12

Naijia Liu