Search code examples
jsonamazon-web-servicescookiesaws-lambdaaws-api-gateway

How can I send multiple Set-Cookie headers from API Gateway using a proxied Lambda


I'm using API Gateway's Proxy integration to call a Lambda. The output format specification is this follow JSON format:

{
  "statusCode": httpStatusCode,
  "headers": { "headerName": "headerValue", ... },
  "body": "..."
}

In one response I wish to set two cookies (two different auth cookies) but JSON doesn't allow having two identical keys in the headers object (OK, technically the spec does but most libraries do not).

RFC 7230 notes that Set-Cookie should be handled specially but I can't see how I can send multiple Set-Cookie values through API gateway.

Does anyone know whether this is possible?


Solution

  • Please note that in 09/2022 AWS Api Gateway by default uses a new payload format (version 2.0) that no longer recognizes multiValueHeaders as proposed by all the top answers, including the accepted answer. I just spent 40 minutes trying to figure out why it doesn't return my cookies :).

    From AWS Documentation:

    Format 2.0 doesn't have multiValueHeaders or multiValueQueryStringParameters fields. Duplicate headers are combined with commas and included in the headers field. Duplicate query strings are combined with commas and included in the queryStringParameters field.

    Format 2.0 includes a new cookies field. All cookie headers in the request are combined with commas and added to the cookies field. In the response to the client, each cookie becomes a set-cookie header.

    https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html

    So the actual solution should now be:

        return {
          statusCode: 302,
          headers: {
            Location: location,
          },
          cookies: [
             "cookie1=value1;",
             "cookie2=value2;"
          ]
        };