How to Deploy an Express.js Application to AWS Lambda

  Reading Time:

In this post, we will learn how to set up a simple Express API application powered by an AWS Lambda function. We will use Serverless Framework to automate our deployment process. So we will:

  • Create a simple Express application
  • Convert the Express app to make it ready to deploy on Lambda environment
  • Set up Serverless Framework and deploy the application to AWS Lambda
  • Finally, test our application

But before we dive into application creation, we should know about Serverless and AWS Lambda.

What is Serverless?

Serverless is the latest cloud computing architecture where the application owner does not purchase, rent, manage, or provision the servers. Instead, the cloud partner manages the infrastructure side of things for the applications. The most powerful advantage of this architecture is that the cloud partner dynamically manages the provisioning of servers to meet the real-time computing demand.

Despite the name, Serverless apps do not run without the servers. However, businesses need not bother themselves about the server side of things and instead, focus on front end development.

Why use Serverless?

1.Cost-effective:

With a Serverless architecture, you pay only for what you use. There is no idle capacity, no wasted resources, or money.

2.No Server Management:

Say goodbye to backend infrastructure management. No downtime, no provisioning or maintaining of servers ever again.

3.Virtually limitless scalability:

Scale only functions and not the application. Scaling up or down is as simple as executing a few lines of code.

4.High availability:

Extreme fault tolerance, which is made possible by multiple redundancies, is baked into the Serverless architecture.

What is AWS Lambda?

  • AWS Lambda is a Serverless computing service that lets you run code without provisioning or managing servers.
  • AWS Lambda executes your code only when needed and scales automatically.
  • You pay only for the compute time you consume - there is no charge when your code is not running.
  • AWS Lambda performs all of the administration of the resources, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring and logging.

Prerequisites

  • AWS account with access to IAM and Lambda.
  • Node.js 8  or later.
  • NPM

Create a simple Express application

We need an express application. Let’s create a simple one by running the below commands on terminal

mkdir sample-app && cd sample-app
npm init -y
npm install express
touch app.js

The following code goes to app.js

const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/api/info', (req, res) => {
  res.send({ application: 'sample-app', version: '1.0' });
});
app.post('/api/v1/getback', (req, res) => {
  res.send({ ...req.body });
});
app.listen(3000, () => console.log(`Listening on: 3000`));

The above sample application exposes two API’s

  1. GET /api/info returns information about current API
  2. POST /api/v1/getback returns the request body whatever we sent

Convert the express app to make it ready to deploy on Lambda environment

We need a serverless-http module which allows us to 'wrap' our express app for Serverless use. So let's install this module by running the below command

npm i serverless-http

Now update the app.js

const serverless = require('serverless-http');
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get('/api/info', (req, res) => {
  res.send({ application: 'sample-app', version: '1' });
});
app.post('/api/v1/getback', (req, res) => {
  res.send({ ...req.body });
});
module.exports.handler = serverless(app);

Our app is ready to deploy on Lambda environment. Let’s continue with deployment.

Set up Serverless Framework and deploy the application to AWS Lambda

Deploying a Serverless app manually using API Gateway and AWS Lambda will be a tedious job. There are tools available which makes the deployment job easy. One such tool is Serverless Framework. So we use Serverless Framework to deploy our app. To install Serverless, run the following command in the terminal.

npm install -g serverless

Verify that Serverless is installed successfully by running the following command in the terminal

serverless –version

Allow Serverless to access your AWS account

serverless config credentials --provider aws --key ACCESS_KEY –secret SECRET_KEY

Replace ACCESS_KEY and SECRET_KEY with your AWS access and secret keys.

Let’s create a Serverless framework config file on application root folder:

touch serverless.yml

The following code goes to serverless.yml

service: sample-app
provider:
  name: aws
  runtime: nodejs8.10
  stage: dev
  region: us-east-1
  memorySize: 128
functions:
  app:
    handler: app/app.handler
    events: 
      - http: 
          path: /
          method: ANY
          cors: true
      - http: 
          path: /{proxy+}
          method: ANY
          cors: true

Now we are all set to deploy our application. Run the following command to deploy.

serverless deploy

If everything goes well you should see output like:

Backup MySQL database and directly upload to AWS S3 bucket

In this post we will learn how to backup MySQL database and upload it to Amazon S3 server. We will be using Ubuntu Server 18.04....

How to create SaaS style multi tenant web app with Spring Boot 2 ,Spring Security 5 and MySQL

PrerequisitesJava 8Spring Boot 2MySQLOverviewWe are going to see how to build JPA Multi Tenancy in Spring boot 2 and use Flyway for DB migration We are...

App & Geek   Never miss a story from App & Geek, get updates in your inbox.