DEV Community

Ashwin Soni
Ashwin Soni

Posted on

Getting started with serverless functions using NodeJS and AWS

Originally published at medium.com/@ashwinsoni on Dec 15, 2019

node-lambda-love

Image Source: Rubix

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 into manageable Microservices is necessary for the ease of maintenance
  • Microservices can be further broken down into function as a service viz. serverless functions

mono-micro-function

Image Source: Stackify

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,

"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:

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 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

```
  1. Test/invoke on local

    serverless invoke local --function helloWorld

  2. 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 under Lambda service of the deployed region
    hello-world-code-on-aws

    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

Feel free to reach out in case of any queries or concern

References

Top comments (0)