Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AWS Lambda and API Gateway to serve static javascript?

I am writing a third party widget that executes javascript client side to add a button to the users site. Essentially, the user will include a tag on their site that includes a path to my widget. The URL for that path will include the app_id for the particular user calling the widget. For example

<script src="www.widget.com/widget/{USER_ID}">

I want to be able to use AWS Lambda and API Gateway to do some quick authentication that the user is allowed to download the widget and serve the javascript content. This is super simple with something like res.sendFile in Express.js, but API Gateway doesn't seem to support sending a file. Is there any way that I can use API Gateway to serve the javascript quickly, without having to stringify the entire file?

like image 658
JensenS Avatar asked Oct 18 '22 03:10

JensenS


2 Answers

You can setup api gateway to proxy all requests to s3 which hosts the file (S3 proxy example). Otherwise you can setup a Http Proxy integration and then run a backend http server that serves the entire file. To perform authentication on the request you can execute a lambda function as a custom authorizer

If you have a lambda integration type, the only was is to return the entire file in the response using callback lambda documentation for callback.

like image 119
Abhigna Nagaraja Avatar answered Oct 21 '22 04:10

Abhigna Nagaraja


First, you can respond something like this in your Lambda function:

{
    statusCode: 200,
    headers: { 
        "content-type": "text/javascript"
    },
    body: buildMyJavascriptFileInTextFormat(event.user_id),
    isBase64Encoded: false,
}

Then go to your API Gateway resource and set up the integration following these steps:

Method Request:

Add a query string called user_id.

Integration Request:

{
    "user_id": "$input.params('user_id')"
}

Integration Response

Go to Status code: 200, create a Mapping template called: text/javascript and set up this:

$input.path('body')

Method Response

In the box of Response Body for 200 change the Content-Type to text/javascript.

like image 39
Camilo Ortegón Avatar answered Oct 21 '22 06:10

Camilo Ortegón