Setting Cookie in http response header from AWS lambda Node JS

12,984

Solution 1

API gateway does not let you map the same header more than once. I got around by using different casing to set-cookie method.

callback(null, {
    "statusCode": 302,
    "Location" : "https://somewebsite.com"
    "headers": { "Set-Cookie": cookie1, "set-Cookie": cookie2 },
    "body": "..."
});

Solution 2

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 }),
});
Share:
12,984
Anil Pediredla
Author by

Anil Pediredla

I'm Ron Swanson

Updated on June 07, 2022

Comments

  • Anil Pediredla
    Anil Pediredla 7 months

    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.