Invoking AWS Lambdas On Frontend

For this post, lets invoke an AWS Lambda on the browser.

To invoke an AWS Lambda on the browser client you are going to need to do the following :

  • Create a Cognito Federated User pool
  • Create a policy that has the permission to execute that Lambda
  • Write a little bit of code

Lets Get Started

For this example, I'm just going to use a Lambda that returns a mouse "squeek".

Create Cognito Federated User Pool

To invoke it on the browser, we need to obtain temporary credentials from AWS Cognito service. Those credentials are going to be bound to an IAM policy allows us to invoke Lambdas on the client.

Navigate to create AWS Federated Pool service and give that user pool a good name. I named mine lambda.

Click create new role button to create a new IAM role and update the policy to include Lambda invocation. The policy should look similar to this :

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1500624793000",
            "Effect": "Allow",
            "Action": [
                "lambda:InvokeAsync",
                "lambda:InvokeFunction"
            ],
            "Resource": [
                "arn:aws:lambda:us-east-1:171566796811:function:test3"
            ]
        }
    ]
}

Write Some Code!

This is the fun part. Include the AWS Cognito library and the AWS Client SDK in your application.

AWS SDK
https://sdk.amazonaws.com/js/aws-sdk-2.77.0.min.js"

AWS Cognito Library
https://s3.amazonaws.com/myjsfiddles-sourcefiles/Cognito+Identity+Use+Cases/amazon-cognito-identity.min.js

Using the Cognito library, get temporary credentials

var poolId = 'us-east-1:251959dd-66e2-40a7-b936-335c03e65386'; /// This should be your federated pool Id. 

AWS.config.update({  
  credentials: new AWS.CognitoIdentityCredentials({
    IdentityPoolId: poolId
  }),
  region: 'us-east-1'
});

Invoke the AWS Lambda :

var lambda = new AWS.Lambda({region: 'us-east-1', apiVersion: '2015-03-31'});  
// create JSON object for parameters for invoking Lambda function
var pullParams = {  
  FunctionName : 'test3',
  InvocationType : 'RequestResponse',
  LogType : 'None'
};
// create variable to hold data returned by that Lambda function
var pullResults;



lambda.invoke(pullParams, function(error, data) {  
console.log(error,data)  
  if (error) {
    prompt(error);
  } else {
    pullResults = JSON.parse(data.Payload);
  }
});

I got a successful response from that Lambda :)

Here is a jsFiddle (http://jsfiddle.net/oxybbatu/10/) of the working code. Make sure to replace its Lambda name with your Lambda name and its poolId with your poolId or else it will not work as expected.