Getting started with serverless functions using NodeJS and AWS
Tags: node, aws, serverless, lambda
Published: 2019-12-15 06:02:15

---
title: Getting started with serverless functions using NodeJS and AWS
published: true
description: 
tags: #nodejs #aws #serverless #lambda
---

<i>Originally published at [medium.com/@ashwinsoni](https://medium.com/@ashwinsoni/getting-started-with-serverless-functions-using-nodejs-and-aws-eef8c84abbf3) on Dec 15, 2019</i>

![node-lambda-love](https://thepracticaldev.s3.amazonaws.com/i/vuzdkt40y71njkh2lhyo.png)
> Image Source: [Rubix](https://www.rubix.nl/blogs/how-setup-unit-testing-aws-lambda-serverless-functions-nodejs/)

## What are serverless functions?
- Serverless doesn’t mean an absence of servers, but it means they are actually on a cloud. The challenge of managing these servers is taken away from you.
- Breaking the [Monolithic app](https://en.wikipedia.org/wiki/Monolithic_application) into manageable [Microservices](https://microservices.io/) is necessary for the ease of maintenance
- Microservices can be further broken down into function as a service viz. serverless functions

![mono-micro-function](https://thepracticaldev.s3.amazonaws.com/i/w5g264ocf41yrl16ptty.png)
> Image Source: [Stackify](https://stackify.com/wp-content/uploads/2019/07/image-1.png)

- There are various cloud provider which helps us with the serverless function,
    - [Alibaba Function Compute](https://www.alibabacloud.com/products/function-compute)
    - [AWS Lambda Functions](https://aws.amazon.com/lambda/features/)
    - [Azure Functions](https://azure.microsoft.com/en-in/services/functions/)
    - [Google Cloud Functions](https://cloud.google.com/functions/)
    - [IBM Cloud Functions](https://cloud.ibm.com/functions/)

    ....and so on

- In this article, we will touch upon the [AWS Lambda Functions](https://aws.amazon.com/lambda/features/) and go through steps for creating an AWS Lambda and deploying the same  

## Why and when do we need serverless functions?
- When there is no need for server provisioning, monitoring, logging, or managing the underlying infrastructure. Instead, the focus is on your business logic, broken down into smaller, single-purpose functions
- In that way, a developer could dedicate most of the time on business logic which is very crucial for business and end-user
- There are many use cases like,
    1. Transforming the unstructured data into the structured one 
    2. Integrating the third party APIs
    3. Sending mail on successful operations
    4. Handling high transactional endpoint with high availability

    ....and so on


## What is AWS Lambda?

As per definition from [official site of AWS](https://aws.amazon.com/lambda/),

>"AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume - there is no charge when your code is not running. With Lambda, you can run code for virtually any type of application or backend service - all with zero administration. Just upload your code and Lambda takes care of everything required to run and scale your code with high availability. You can set up your code to automatically trigger from other AWS services or call it directly from any web or mobile app."
    

- In Laymen's term, Lambda functions are nothing but the piece of code/function which performs the stateless operation and can be run independently from main project codebase and deployed on cloud
- This flexibility of managing the piece of code independently helps us in ease of deployment

## Write serverless AWS Lambda function using NodeJS
Pre-requisite:
- Need an [AWS account](https://console.aws.amazon.com/)
- Need [AWS CLI installed](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) and [configured on local](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
- Need [serverless module](https://www.npmjs.com/package/serverless) globally installed on local along with [AWS serverless configuration](https://serverless.com/framework/docs/providers/aws/cli-reference/config-credentials/)


> The Hello World project is a time-honored tradition in computer programming ~ Github

So let us continue the tradition...

Let's understand the steps to create an AWS Lambda,

1. Add [serverless](https://www.npmjs.com/package/serverless) module globally on your local for managing serverless function
    > yarn global add serverless
2. Create a hello world template 
    > serverless create --template hello-world --path hello-world-function
    
    You should now have a folder structure as,
    ```  
    hello-world-function/
    ├── .gitignore
    ├── handler.js
    └── serverless.yml
    ```

    ```.gitignore
    # package directories
    node_modules
    jspm_packages

    # Serverless directories
    .serverless
    ```

    ```js
    'use strict';

    module.exports.helloWorld = (event, context, callback) => {
    const response = {
        statusCode: 200,
        headers: {
        'Access-Control-Allow-Origin': '*', // Required for CORS support to work
        },
        body: JSON.stringify({
        message: 'Go Serverless v1.0! Your function executed successfully!',
        input: event,
        }),
    };

    callback(null, response);
    };

    ```

    ```yml
    # Welcome to serverless. Read the docs
    # https://serverless.com/framework/docs/

    # Serverless.yml is the configuration the CLI
    # uses to deploy your code to your provider of choice

    # The `service` block is the name of the service
    service: hello-world-function

    # The `provider` block defines where your service will be deployed
    provider:
        name: aws
        runtime: nodejs10.x

    # The `functions` block defines what code to deploy
    functions:
        helloWorld:
            handler: handler.helloWorld
            # The `events` block defines how to trigger the handler.helloWorld code
            events:
                - http:
                    path: hello-world
                    method: get
                    cors: true

    ```

3. Test/invoke on local
    > serverless invoke local --function helloWorld
     
4. Deploy the code
    > serverless deploy

    The output of the above command will deploy our Lambda function and give you the HTTP endpoint something like,
    ```
    endpoints:
        GET - https://oyqliuc8hd.execute-api.us-east-1.amazonaws.com/dev/hello-world
    ```
    Also we can verify our code by going through the [AWS console](https://console.aws.amazon.com/) under [Lambda service](https://console.aws.amazon.com/lambda/) of the deployed region
![hello-world-code-on-aws](https://thepracticaldev.s3.amazonaws.com/i/pjm0nr45afsm09jrnlg6.png)

    Things to Note in `serverless.yml` file
    
    - To deploy on a specific region, we need to add `region: <region-name>` node under the provider section. Otherwise, deployed to default configured region
    - To trigger a Lambda function, we specify the type of trigger under `functions: events:` in the given `hello-world` template the trigger is an HTTP endpoint. We can always configure the triggering event as per our use case

The aforementioned is the minimal configuration that is required to get started with AWS serverless function and everything under the hood like zipping, uploading the code to cloud, defining roles and permissions gets self-managed.

One of the ways to manage and deploy serverless function manually by creating roles, permission, zipping and uploading code on the cloud. We may follow - [Create AWS Lambda function using AWS CLI](https://www.youtube.com/watch?v=3BlXU2zEzvY)

<center><i>Feel free to reach out in case of any queries or concern</i></center>

## References
- [AWS Serverless CLI](https://serverless.com/framework/docs/providers/aws/cli-reference/)
- [AWS Lambda with NodeJS a complete getting started guide](https://stackify.com/aws-lambda-with-node-js-a-complete-getting-started-guide/)
- [AWS Lambda Tutorial: Lambda + Serverless = HAPPY](https://www.youtube.com/watch?v=71cd5XerKss)