Skip to content

Using JavaScript for on-demand functions with AWS Lambda

I’ve recently started working often with AWS Lambda, one of the many providers you can use to do “serverless” programming, that is, writing apps without running your own infrastructure (if you want a quick overview of the “serverless” paradigm, there’s a nice one over here).

The AWS Lambda documentation leaves something to be desired (as mocked in this graphic from Auth0, who has a competing service), so in getting started, I would recommend basically ignoring that documentation until you’ve tried working around it, as I found it a bit easier to understand once I’d already deployed a function.

How to deploy a Node.js function to AWS Lambda

I used (and would recommend) a tool that makes things drastically easier, Apex, to get started. It’s right in the command line and easy to use.

1. Install Apex (follow the instructions on the site). At the time of this writing, that’s running curl | sh.

2. Run apex init in your project directory and follow the prompts. This interfaces directly with AWS Lambda to create an appropriate IAM role for your function to execute, so you might need to fiddle with getting your environment variables set up properly.

3. Check out the sample function in functions/hello, modifying or making a new function as you want. The sample function will look something like this:

console.log('starting function')
exports.handle = function(e, ctx, cb) {
  console.log('processing event: %j', e)
  cb(null, { hello: 'world' })

You can modify this function, or you can copy its directory (ex. to functions/YOUR_FUNCTION_NAME.

When you ask AWS Lambda to invoke the function (eventually by something like an API gateway), it executes the function exported here. The arguments to that function are the event, context, and callback, where the event is what is sent when invoking the function, context is about the function’s running environment, and the callback is what you want to execute on success or failure.

Right away, I’d recommend updating the callback in the sample to cb(error, { hello: 'world'}) if nothing else. Passing errors back is a generally good idea, and you can see logs from your functions in CloudWatch.

4. Deploy the function! You can run apex deploy to deploy all functions in a project, or use apex deploy hello to only deploy the hello function (or any other function, by its folder name in functions/). You can then run it from the command line using apex invoke hello.


One Reply to “Using JavaScript for on-demand functions with AWS Lambda”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.