AWS Compute Blog

Simply Serverless: Using AWS Lambda to Expose Custom Cookies with API Gateway

Simply Serverless

Welcome to a new series on quick and simple hacks/tips/tricks and common use cases to using AWS Lambda and AWS API Gateway. As always, I’m listening to readers (@listonb), so if you have any questions, comments or tips you’d like to see, let me know!

This is a guest post by Jim Warner from Survata.

This first tip describes how Survata uses Lambda to drop a new cookie on API Gateway requests. Learn more about how Survata is using this during Serverless Day at the San Francisco Loft on April 28th. Register for Serverless Day now.

Step 1: Return a cookie ID from Lambda

This walkthrough assumes you have gone through the Hello World API Gateway Getting Started Guide code.

Expand upon the “Hello World” example and update it as follows:

'use strict';
exports.handler = function(event, context) {
  console.log("{'Cookie':event['Cookie']}");
  var date = new Date();

  // Get Unix milliseconds at current time plus 365 days
  date.setTime(+ date + (365 \* 86400000)); //24 \* 60 \* 60 \* 100
  var cookieVal = Math.random().toString(36).substring(7); // Generate a random cookie string
  
  var cookieString = "myCookie="+cookieVal+"; domain=my.domain; expires="+date.toGMTString()+";";
  
  context.done(null, {"Cookie": cookieString}); 

};

This makes a random string and returns it in JSON format as a proper HTTP cookie string. The result from the Lambda function is as follows:

{"Cookie": "myCookie=t81e70kke29; domain=my.domain; expires=Wed, 19 Apr 2017 20:41:27 GMT;"}

Step 2: Set the cookie in API Gateway

In the API Gateway console, go to the GET Method page and choose Method Response. Expand the default 200 HTTP status, and choose Add Header. Add a new header called “Set-Cookie.”

On the GET Method page, choose Integration Response. Under the Header Mappings section of the default 200 HTTP status, choose the pencil icon to edit the “Set-Cookie” header. In the mapping value section, put:

integration.response.body.Cookie

Make sure to save the header by choosing the check icon!

For a real production deployment, use a body mapping template to return only the parts of the JSON that you want to expose (so the cookie data wouldn’t show here).

Deploying both the Lambda function and API Gateway gets you up and cookie-ing.