AWS Lambda Layers - Node Js

by Revathi Ganapuram

 Adding Layers in AWS Lambda


Overview : A Lambda layer is an archive containing additional code, such as libraries, dependencies, or even custom runtimes. The layer later can be used by adding in Layers option in AWS Lambda.

    In this post, we will learn how to create and add layers for node js functions in AWS Lambda.

  • Firstly, we will create a sample code of printing current data and time like below
      • For this we have created  a folder named AWSLAYERS, in that we have added initialized 'npm init'.
      • Next, for printing date and time we need moment module, let's install it.
        • npm install moment --save. 
      • After successful installation of `moment` a node module package will be created inside folder and also package.json file.
    • Now here comes the actual part, create a folder names 'nodejs' and move nodemodules, package.json (package-lock.json also , if present) inside nodejs folder.
    • After moving the folder structure should be as below.

    • Zip the nodejs folder and keep it.

    Creating Layer in AWS Lambda :

                    The main requirement for creating Layers in AWS, you should have an AWS Account, one can create here.
     
    • After successful creation of accout, login into it and search for Lambda , in services.
    • At left side you will find 'Layers', click it.
    • Click on Create Layer , you will find a screen as below.

    • Mention name of the layer , for example demo 
      • select on 'upload a .zip file'. here we will upload our nodejs.zip .
      • Choose runtime , here we choose 'Node.js 10.x,12.x,14.x', click Create.
      • Then the below screen will appear after successful creation of Layer.
        

    Adding Layer to Lambda Function:

    • Go to Dashboard, click on 'Create Function'
    • Give a function name , for example demolayer and choose runtime as Node.js 14.x, Click create Fucntion.
    • After successful creation of function , a screen will open up with default 'Hello World' program in index.js file.
      • Replace the default code with code as shown below and click deploy.


    • Click Test , you will get below error.
            

    • This is because we didn't include node module related to 'moment' here.
    • Now scroll down , select 'Add a Layer', select Custom layers under it choose the layer we have created 'demo', select version and Click ADD.


    • Refresh the page, and run 'Test', that's it you will get current date and time as result which means our layer has been successfully integrated with our code. 


    Thank you...




    Comments

    Post a Comment

    Popular posts from this blog

    AWS Lambda Function - Node Js