Since you need to run Lambda from the browser, you have two options you can achieve it.

  1. Use AWS Javascript SDK, set it up with user via static configuration or Cognito with IAM Permissions to your Lambda. You can also consider subscribing your Lambda functions to SNS Topic and run the Lambda by sending a message to the topic. This SNS approach would also require you to store and retrieve the submission state via separate call.

  2. Use AWS API Gateway to create RESTful endpoint with proper CORS configuration that you can ping from the browser using AJAX.

Both options have their pros and cons. More information about your use-case would be necessary to properly evaluate which one suits you best.

Answer from adamkonrad on Stack Overflow
🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › building lambda functions with node.js › define lambda function handler in node.js
Define Lambda function handler in Node.js - AWS Lambda
You can configure Node.js in Lambda to detect automatically whether a .js file should be treated as CommonJS or as an ES module by adding the —experimental-detect-module flag to the NODE_OPTIONS environment variable. For more information, see Experimental Node.js features. The following examples show function handlers written using both ES modules and CommonJS modules. The remaining examples on this page all use ES modules. ... const url = "https://aws.amazon.com/"; export const handler = async(event) => { try { const res = await fetch(url); console.info("status", res.status); return res.status; } catch (e) { console.error(e); return 500; } };
🌐
AWS
docs.aws.amazon.com › aws sdk for javascript › developer guide for sdk version 3 › work with aws services in the sdk for javascript › sdk for javascript code examples › aws lambda examples
AWS Lambda examples - AWS SDK for JavaScript
The JavaScript API for AWS Lambda is exposed through the LambdaService client class. Here are a list of examples that demonstrate how to create and use Lambda functions with the AWS SDK for JavaScript v3:
Discussions

Need example of calling AWS Lambda from JavaScript - Stack Overflow
Just need an example of how to call AWS Lambda from JavaScript running in a browser and display function result in JavaScript console. Incredibly, I cannot find any examples on Google or from AWS More on stackoverflow.com
🌐 stackoverflow.com
Finding an AWS JavaScript Lambda module regardless of whether the lambda is hot or cold

../src/common

Remember that these are Unix file paths.

Also, if possible, minify your JS/TS before deployment.

More on reddit.com
🌐 r/aws
3
0
March 12, 2023
Why would I use Node.js in Lambda? Node main feature is handling concurrent many requests. If each request to lambda will spawn a new Node instance, whats the point?
That’s not really unique to Node. The majority of languages and web app platforms have concurrency mechanisms that will process multiple requests simultaneously. That is certainly a drawback of Lambda if you’re looking at raw CPU cycle efficiency and your application spends a lot of time waiting on synchronous downstream calls, but in most cases that doesn’t really matter. In practice, there are a lot of apps that can either use really fast data stores like Dynamo or use asynchronous processing models that minimize the amount of idle CPU time for a given request. Also, even with some inefficiencies when looking at high concurrency time periods, sometimes the ability for Lambda to immediately scale down during troughs in your load pattern makes up for it when looking at the global efficiency of the system (especially when you consider other operational overhead like patching servers.) Bottom line, people use Node with Lambda because they like the language and are familiar with it. Using the same language for the front end browser code and the backend is nice for teams that build full stack web apps. More on reddit.com
🌐 r/aws
82
56
February 8, 2020
Invoking a lambda function from the Javascript SDK vs API Gateway?

I think API gateway, you can set it up to function exactly like a normal back end service. Define an endpoint signature, handle authentication, and use any http client you want.

More on reddit.com
🌐 r/aws
3
1
November 13, 2019
🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › building lambda functions with node.js
Building Lambda functions with Node.js - AWS Lambda
For Node.js runtime versions up ... interact with other AWS services. For example, Lambda includes the Amazon RDS certificates necessary for validating the server identity certificate installed on your Amazon RDS database....
🌐
AWS
docs.aws.amazon.com › aws sdk for javascript › developer guide for sdk version 3 › sdk for javascript (v3) code examples › lambda examples using sdk for javascript (v3)
Lambda examples using SDK for JavaScript (v3) - AWS SDK for JavaScript
For API details, see ListFunctions in AWS SDK for JavaScript API Reference. The following code example shows how to use UpdateFunctionCode. ... There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository ... const updateFunctionCode = async (funcName, newFunc) => { const client = new LambdaClient({}); const code = await readFile(`${dirname}../functions/${newFunc}.zip`); const command = new UpdateFunctionCodeCommand({ ZipFile: code, FunctionName: funcName, Architectures: [Architecture.arm64], Handler: "index.handler", // Required when sending a .zip file PackageType: PackageType.Zip, // Required when sending a .zip file Runtime: Runtime.nodejs16x, // Required when sending a .zip file }); return client.send(command); };
🌐
Medium
medium.com › @wwdhfernando › introduction-to-aws-lambda-and-a-simple-javascript-example-6002940471fe
Introduction to AWS Lambda and a Simple JavaScript Example | by Dilshan Fernando | Medium
January 16, 2025 - Lambda supports multiple programming languages, including Node.js, Python, Java, Go, and Ruby. In this article, we’ll explore the basics of AWS Lambda and provide a practical JavaScript example using Node.js.
🌐
AWS
docs.aws.amazon.com › aws sdk code examples › code library › code examples by sdk using aws sdks › code examples for sdk for javascript (v3) › lambda examples using sdk for javascript (v3)
Lambda examples using SDK for JavaScript (v3) - AWS SDK Code Examples
For API details, see ListFunctions in AWS SDK for JavaScript API Reference. The following code example shows how to use UpdateFunctionCode. ... There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository ... const updateFunctionCode = async (funcName, newFunc) => { const client = new LambdaClient({}); const code = await readFile(`${dirname}../functions/${newFunc}.zip`); const command = new UpdateFunctionCodeCommand({ ZipFile: code, FunctionName: funcName, Architectures: [Architecture.arm64], Handler: "index.handler", // Required when sending a .zip file PackageType: PackageType.Zip, // Required when sending a .zip file Runtime: Runtime.nodejs16x, // Required when sending a .zip file }); return client.send(command); };
Find elsewhere
Top answer
1 of 5
12

Since you need to run Lambda from the browser, you have two options you can achieve it.

  1. Use AWS Javascript SDK, set it up with user via static configuration or Cognito with IAM Permissions to your Lambda. You can also consider subscribing your Lambda functions to SNS Topic and run the Lambda by sending a message to the topic. This SNS approach would also require you to store and retrieve the submission state via separate call.

  2. Use AWS API Gateway to create RESTful endpoint with proper CORS configuration that you can ping from the browser using AJAX.

Both options have their pros and cons. More information about your use-case would be necessary to properly evaluate which one suits you best.

2 of 5
10

I see people have used AWS SDK for Javascript but it is not required specially since you need to create Amazon Cognito identity pool with access enabled for unauthenticated identities (Atleast for beginners like me). Below code works fine for me -

<html>
    <head>
<script>
    function callAwsLambdaFunction() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("myDiv").innerHTML = this.responseText;
            }
        };
        xhttp.open("GET", "https://test123.ap-south-1.amazonaws.com/dev", true);
        xhttp.send();

    }
    </script>   
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello world!</h1>
        <h1>Click below button to call API gatway and display result below!</h1>
        <h1><div id="myDiv"></div></h1>
        <button onclick="callAwsLambdaFunction()">Click me!</button><br>
        Regards,<br/>
        Aniket
    </body>
</html>

Above is sample index.html that I have added to my S3 bucket and made a static site. Couple of points to note -

  1. Make your index.html open from outside if you are using S3 for static site hosting.
  2. Make sure you turn on CORS for your API gateway if your website domain is not same as API gateway domain. Else you might get -

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://test123.ap-south-1.amazonaws.com/dev. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

🌐
Claudia.js
claudiajs.com › tutorials › hello-world-lambda.html
Hello World AWS Lambda function
Send this function to AWS using Claudia. You will need to specify the main method for the Lambda to execute (in the Lambda terminology, that’s the handler). The syntax is module.method. Because the main micro-service module is lambda.js, and the method is handler, this argument should be lambda.handler.
🌐
AWS
docs.aws.amazon.com › javascript sdk › developer guide for sdk v2 › tutorials › tutorial: creating and using lambda functions
Tutorial: Creating and Using Lambda Functions - AWS SDK for JavaScript
Call another service within a Lambda ... resources needed by the Lambda function. In this example, a simulated browser-based slot machine game invokes a Lambda function that generates the random results of each slot pull....
🌐
AWS
docs.aws.amazon.com › aws sdk for javascript › developer guide for sdk version 3 › work with aws services in the sdk for javascript › sdk for javascript code examples › invoking lambda with api gateway
Invoking Lambda with API Gateway - AWS SDK for JavaScript
For example, you'll learn how to read a database to determine which employees have reached the one year anniversary date, how to process the data, and send out a text message all by using a Lambda function. Then you’ll learn how to use API Gateway to invoke this AWS Lambda function by using ...
🌐
Stackify
stackify.com › aws-lambda-with-node-js-a-complete-getting-started-guide
AWS Lambda with Node.js: A Complete Getting Started Guide - Stackify
May 1, 2023 - # filename: serverless.yml service: ImageUploaderService # The `provider` block defines where your service will be deployed custom: bucket: getting-started-lambda-example provider: name: aws runtime: nodejs8.10 region: eu-west-1 stackName: imageUploader iamRoleStatements: - Effect: "Allow" Action: - "s3:PutObject" Resource: - "arn:aws:s3:::${self:custom.bucket}/*" # The `functions` block defines what code to deploy functions: UploadImage: handler: uploadImage.handler # The `events` block defines how to trigger the uploadImage.handler code events: - http: path: upload method: post cors: true environment: Bucket: ${self:custom.bucket} resources: Resources: StorageBucket: Type: "AWS::S3::Bucket" Properties: BucketName: ${self:custom.bucket}
🌐
GitHub
github.com › aws-samples › aws-lambda-demo-with-node-express
GitHub - aws-samples/aws-lambda-demo-with-node-express · GitHub
The purpose of this repository is to demonstrate how to deploy a simple web application built by Express - Node.js web application framework on AWS Lambda.
Starred by 21 users
Forked by 20 users
Languages   JavaScript 52.7% | HTML 47.3%
🌐
Medium
medium.com › hackernoon › getting-started-with-aws-lambda-and-node-js-4ce3259c6dfd
Getting Started with AWS Lambda and Node.js | by Adnan Rahić | HackerNoon.com | Medium
August 16, 2018 - You’ll land on the Lambda homepage with a big orange button prompting you to create a new function. Well, don’t keep it waiting any longer, press it. ... This will take you to the main function creation wizard. As this example will cover a basic function that will simulate a dice throw, let’s forget about the blueprints and just author one from scratch. Awesome!
🌐
AWS
docs.aws.amazon.com › aws sdk for javascript › developer guide for sdk version 3 › work with aws services in the sdk for javascript › sdk for javascript code examples › creating scheduled events to execute aws lambda functions
Creating scheduled events to execute AWS Lambda functions - AWS SDK for JavaScript
In the Schedule expression field, enter a cron expression. For example, cron(0 12 ? * MON-FRI *). Choose Add. For more information, see Using Lambda with CloudWatch Events. Congratulations! You have invoked a Lambda function through Amazon CloudWatch scheduled events using the AWS SDK for JavaScript.
🌐
AppSignal
blog.appsignal.com › 2022 › 03 › 23 › build-serverless-apis-with-nodejs-and-aws-lambda.html
Build Serverless APIs with Node.js and AWS Lambda | AppSignal Blog
August 9, 2023 - For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: N Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment) ----------------------- Generating application: ----------------------- Name: aws-lambda-nodejs-example Runtime: nodejs18.x Architectures: x86_64 Dependency Manager: npm Application Template: hello-world Output Directory: .
🌐
RisingStack
blog.risingstack.com › home › hírek, események › getting started with aws lambda & node.js
Getting Started with AWS Lambda & Node.js - RisingStack Engineering
May 29, 2024 - AWS Lambda handles differently what happens when you call a Lambda function for the first time, and consequent calls to the same Lambda function. When you deploy your Lambda function (or update an existing one), a new container will be created for it. Your code will be moved into the container, and the initialization code will run before the first request arrives to the exposed handler function. The Lambda function can complete in one of the following ways:
🌐
Medium
medium.com › intrinsic-blog › basic-node-js-lambda-function-concepts-c0d1e00d4528
Basic Node.js Lambda Function Concepts | by Thomas Hunter II | intrinsic | Medium
May 29, 2018 - Lambda Functions have a Name, which is a string to represent the function throughout AWS. Lambda Functions also have a Handler Name, which is also a string. When working with Node.js applications the Handler Name has two parts. The first part is the name of the JavaScript file in the root of ...
🌐
Hevo
hevodata.com › home › learn › data strategy
NodeJS Lambda | The Complete Guide to Get Started 101
January 12, 2026 - # filename: serverless.yml service: ImageUploaderService # The `provider` block defines where your service will be deployed custom: bucket: getting-started-lambda-example provider: name: aws runtime: nodejs8.10 region: eu-west-1 stackName: imageUploader iamRoleStatements: - Effect: "Allow" Action: - "s3:PutObject" Resource: - "arn:aws:s3:::${self:custom.bucket}/*" # The `functions` block defines what code to deploy functions: UploadImage: handler: uploadImage.handler # The `events` block defines how to trigger the uploadImage.handler code events: - http: path: upload method: post cors: true environment: Bucket: ${self:custom.bucket} resources: Resources: StorageBucket: Type: "AWS::S3::Bucket" Properties: BucketName: ${self:custom.bucket}