In this video you'll learn how to share NPM modules across multiple Serverless functions using AWS Amplify and Lambda layers. You'll create a layer that contains the uuid library, then create a Serverless API that consumes the library from another function.
Nader Dabit: [0:00] To get started, create a new Amplify project by runing amplify init. Give the project a name, the environment a name, choose your default text editor, and then choose the defaults for the rest of the options. When prompted for your AWS profile, choose the AWS profile that you'd like to use.
[0:22] Next, run amplify add function. Here, you'll be given the option to choose a Lambda layer. Here, we'll give the Lambda layer a name and choose NodeJS as the runtime. For the optional access configuration, we'll just choose the default.
[0:46] Next, we'll add a dependency by changing into the function directory. Using either npm or yarn, install the uuid package. Once the package has been installed, change back into the base directory.
[1:06] To test out the layer, we'll add a new API and a function. To do so, we'll run amplify add api. For the type of API, choose REST. For the name of the API, I'll choose greetingapi because this API will be returning a greeting along with an id. For the path, we'll choose /hello.
[1:26] Next, we'll create a new Lambda function. We'll call this function greetingfunction. For the runtime, choose NodeJS, and for the function template, choose Hello World.
[1:42] When prompted for a configuration of Lambda layers for this function, choose Yes. Here, you should be prompted to choose the layer that we created in the previous step. We'll choose Yes when prompted to edit the function. Here, we can require the uuid library from the associated layer.
[2:05] Next, we'll create a greeting object containing an id and a message as the response for our function. The last thing we'll do is configure Access-Control-Allow-Origin headers to enable CORS.
[2:26] To deploy the API, the function, and the layer, we can now run amplify push. To test everything out, we can now curl the URL using the /hello path.