AWS Mobile Blog

How to use Lambda layers with the Amplify CLI

This post was written by Rene Brandel, Senior Product Manager, AWS

In this guide you will learn how to create, deploy and leverage Lambda layers & the Amplify CLI to reuse code & assets across serverless functions.

AWS Amplify enables mobile & web developers to build full stack serverless apps. The Amplify CLI helps developers to create backend resources through a guided workflow.

Today, we are announcing the general availability of Lambda layer support in Amplify CLI. A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies. Lambda layer provides a few major benefits for your full stack serverless codebase:

  1. Re-use your code! Your Lambda functions can leverage these layers to reuse shared code & assets across functions. A developer’s dream – no more messy code duplication!
  2. Faster deployments! Iterating on your Lambda function will be significantly faster because it can be independently updated from the layer which usually contains the bulk of large static content!

Figure 1: Architecture diagram - With vs. without Lambda layer

Amplify CLI provides a guided creation, update and deployment process for Lambda layer designed for NodeJS, and Python.

What we’ll learn:

  • Use Amplify CLI to set up a new Lambda layer with a node module
  • Add a Lambda layer to a Lambda function

What we’ll build:

  • A Lambda layer that packages the Moment.js library (a time utility library)
  • A Lambda function that uses this layer to access Moment.js to generate a timestamp as a response

Pre-requisites:

  • Install the latest Amplify CLI version
    • Open terminal and run npm install -g @aws-amplify/cli to update to the latest Amplify CLI.
  • Amplify CLI is already configured
    • If you haven’t configured the Amplify CLI yet, follow this guide on our documentation page.

1. Setup your environment

First, create your project directory. If you have an existing Amplify project, you can skip to the next section.

Open your Terminal and create a project directory by running the following command.

mkdir amplify-layer

Next change directory into the newly created project

cd amplify-layer

In the project directory initialize Amplify by running

amplify init

For this example, accept all of the default values. The selection & output should look something like this.

? Enter a name for the project (amplify-layer)
? Enter a name for the environment (dev)
? Choose your default editor: (your editor type)
? Choose the type of app that youre building (javascript)
? What javascript framework are you using (none)
? Source Directory Path: (src)
? Distribution Directory Path: (dist)
? Build Command: (npm run-script build)
? Start Command: (npm run-script start)
? Do you want to use an AWS profile? (Yes)
? Please choose the profile you want to use: (default)

2. Create your Lambda layer

Now that you’ve got your project setup you can add your first Lambda layer. This is where you’ll place all the shared code & assets for your Lambda functions. To add your first layer run the following command in your Terminal:

amplify add function

Choose Lambda layer (shared code & resource used across functions)

? Select which capability you want to add:
> Lambda layer (shared code & resource used across functions)

Now you can provide a name for your layer. For this project, select NodeJS (using the space bar) and then follow the remaining defaults.

? Provide a name for your Lambda layer: layerblog4dac28df
? Select up to 2 compatible runtimes: NodeJS

Next, you can configure who has access to your Lambda layer in addition to the current account. If you don’t want to set up any additional permissions, you can hit Enter to skip.

? The current AWS account will always have access to this layer.
Optionally, configure who else can access this layer. (Hit <Enter> to skip)
❯◯ Specific AWS accounts
 ◯ Specific AWS organization
 ◯ Public (Anyone on AWS can use this layer)

The layer is setup! In the next step you’ll add a library to your layer.

3. Add node modules to your lambda layer

Next, change into the new directory:

cd amplify/backend/function/layerblog4dac28df/lib/nodejs/

For NodeJS projects, Amplify CLI automatically places a package.json file in the nodejs folder. This allows you to add node_modules to your layer by running npm install <your modules>. For this project, install the moment package and leverage in our Lambda function.

Run the following command to install moment:

npm install moment

Then, change back into the top level directory.

4. Create a Lambda function and use it with your layer

Now that you’ve got your Lambda layer created, let’s add it to a Lambda function to unlock all the benefits of Lambda layers. To create a new Lambda function run amplify add function. Make sure to create a NodeJS – Hello World function.

❯ amplify add function
? Select which capability you want to add:
> Lambda function (serverless function)
? Provide a friendly name for your resource to be used as a label for this category in the project:
> myfunction
? Provide the AWS Lambda function name:
> myfunction
? Choose the runtime that you want to use:
> NodeJS
? Choose the function template that you want to use:
> Hello World
? Do you want to access other resources in this project from your Lambda function?
> No
? Do you want to invoke this function on a recurring schedule?
> No

Make sure to answer Yes to configuring a Lambda layer and use the space bar to select the newly created layer.

? Do you want to configure Lambda layers for this function?
> Yes
? Provide existing layers or select layers in this project to access from this function (pick up to 5):
> layerblog4dac28df
? Select a version for layerblog4dac28df:
> 1

When prompted to edit the local Lambda function now, choose Yes.

? Do you want to edit the local lambda function now?
> Yes

Now, edit the function code to use the moment node module. Replace the Lambda function file with the content below:

// importing the node_modules that are in the layer's node_modules folder
const moment = require('moment');

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify(moment().format()),
    };
    return response;
};

You can still import or require node_modules in the same way as if they are bundled directly within your function.

This level of abstraction makes it super easy for you to migrate your existing functions to start using Lambda layers, since there aren’t any code changes.

Now let’s wrap this up and go back to your Terminal to complete the process of creating a Lambda function.

? Press enter to continue
Successfully added resource layerblogb38b3c53 locally.

Next steps:
Check out sample function code generated in <project-dir>/amplify/backend/function/layerblogb38b3c53/src
"amplify function build" builds all of your functions currently in the project
"amplify mock function <functionName>" runs your function locally
"amplify push" builds all of your local backend resources and provisions them in the cloud
"amplify publish" builds all of your local backend and front-end resources (if you added hosting category) and provisions them in the cloud

5. Push your function and layer to the cloud & test them!

Now that you’ve setup your Lambda function and layer, you can push it to the cloud. To do that, run:
amplify push -y

Once the Lambda layer & function are deployed, you can test it inline within the Lambda Console by running amplify console function . Select your function in the Lambda Console and run a test!

Note: amplify mock function <function-name> will not work for functions that use layers.

6. 🥳 Success

After running Test, you can see the response contains the timestamp generated by moment’s .format() function.

Next steps

This is how easy it is to start using Lambda layers in your full stack serverless application with Amplify CLI! Review the Lambda layers capability in full by checking out the documentation.

If you have any feedback or enhancement requests, please create an issue in the Github repository.