Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return HTML page stored on AWS S3 bucket from a AWS Lambda function

My current situation: I have an AWS API Gateway with a resource /login. When there is a GET request on this resource, an AWS Lambda function is called which returns an HTML login form. The HTML for the login form is written inside a JavaScript string in the Lambda function (I'm using Node JS inside my Lambda functions). When the form is submitted, the same resource - /login with POST method calls another Lambda function which validates the login. If the login fails, it returns an HTML form with validation error messages, but again, the HTML code is written inside a JavaScript string.

My question: Is it possible to store an HTML file in an AWS S3 bucket, so when I hit /login the API Gateway calls the Lambda function, which then gets the HTML page from S3 bucket and returns it to the user? And when the form validation fails, then I'd like to return the same HTML from S3 bucket with added error messages.

Is it possible to interconnect these components in this way? The part I'm struggling with is storing HTML on S3 and accessing it from Lambda.

like image 386
Pixel1002 Avatar asked Aug 02 '16 12:08

Pixel1002


People also ask

How do I get data from S3 bucket in Lambda function?

Select the Lambda function that you created above. Provide a supporting S3 Access Point to give S3 Object Lambda access to the original object. Update your application configuration to use the new S3 Object Lambda Access Point to retrieve data from S3.


2 Answers

You do not need to involve any Lambda function. You can configure a method to proxy AWS API call, then the only thing you need is to create an API Gateway proxy which proxies to S3 API Object GET.

You should first create an IAM role which has access to your bucket/specific HTML object, note down its ARN, then create an integration like the image.

enter image description here

Note: Of course it is not a valid solution if you want to modify HTML's content on the fly and only works if your content is static. If you want to do it, you have to create a Lambda that downloads the S3 object, manipulates it and send back to the client.

like image 186
Çağatay Gürtürk Avatar answered Nov 15 '22 07:11

Çağatay Gürtürk


Yes, you can use Amazon S3 to store a "master" copy of your login HTML page, and use it in your Lambda functions.

Use this Lambda & S3 tutorial as a starting point:

http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html

The part you care about is reading the object from S3 in your Lambda function:

var AWS = require('aws-sdk');
var s3 = new AWS.S3();
s3.getObject({ Bucket: srcBucket, Key: srcKey }, ...);
like image 21
Matt Houser Avatar answered Nov 15 '22 08:11

Matt Houser