Express in AWS Lambda

Ashiq Sultan

Developing APIs are exciting but managing servers are not but that is no more with the power of cloud functions.

Though many providers offer their own cloud functions I went with AWS Lambda and gave it a try.

If you create a new Lambda function from within AWS console it provides you a simple code editor which you will hate, takes a long time to save and you don’t have any idea how to run npm commands there. Listen lambda console is not designed that you do development there.

In this tutorial, I will walk you through a step by step process which will help you to set up a strategy to develop an express app in your computer, test them locally and deploy it to AWS lambda.

Overview of what we are going to do?

  • Create a new express app with a simple GET request
  • Create files to deploy the app to AWS Lambda
  • Install and configure AWS CLI
  • Deploy our app to AWS

GitHub Repo

You can find the finished work of this tutorial in this repository. It is a boilerplate code which I keep as a reference for myself.

https://github.com/ashiqdrive/express-aws-lambda

Disclaimer: This tutorial assumes that you already know the basics of JavaScript programming and Express JS. You should have an AWS account. Also, I have used express app and API interchangeably.

Step 1 : Create new project and install dependencies

Open command line in a new folder and initiate a new npm project

npm init -y

Install the below two packages as main dependencies

  • express
  • aws-serverless-express
npm install express aws-serverless-express

Install the package “serverless” as dev dependencies

npm install serverless --save--dev

Step 2 : Simple Express App

Create a server

Create a file local.js this is the file which will start our server and listens to incoming requests in our local environment

local.jsconst express = require('express');
const app = express();
const port = process.env.PORT || 8000;
// Server
app.listen(port, () => {
console.log(`Listening on: http://localhost:${port}`);
});

You can start the server by typing in the command line

node local.js//Output
Listening on: http://localhost:8000

Creating Express App

Create a new folder src this is the folder which will contain all the files related to the logic of our app, this is the place where you would have your api folder and all other folders and static files your app requires.

For the sake of this tutorial, we will create a simple GET request. Create a new file app.js inside the src folder and insert the following code.

src/app.jsconst express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:false}))
//GET
app.get('/', (req, res) => {
res.status(200).send('hello world!');
});
//GET
//Simply sends the current time
app.get('/time', (req, res) => {
let timeNow = Date(Date.now());
res.status(200).send(timeNow.toString());
});
module.exports = app;

Your file structure should look like this

node_moudles
src
|_ app.js
local.js
package.json
package-lock.json

Test our app locally

Replace first two lines in the local.js file with the following line

local.js//Replace these lines
const express = require('express');
const app = express();
//With this line
const app = require('./src/server.js');

Start your server to run the app with the following command

node local.js

To test our GET request use Postman or navigate to the the following URL in your browser

http://localhost:8000/time

You should see something like this based on your time zone

Wed Aug 28 2019 15:34:33 GMT+0530 (India Standard Time)

Cool, we got our app working locally, time to deploy the app to AWS

Step 3 : Entry to AWS

If you are familiar with creating APIs with express all the steps above are a walk in the park for you. From this step, we are going to create and configure the necessary files required to deploy our app to AWS Lambda.

Create file “ lambda.js “

Create a new file lambda.js in the root of the working directory, i.e., the same location where package.json file exists and insert the following code.

lambda.js//This file is AWS Lambda entry pointconst awsServerlessExpress = require('aws-serverless-express');
const app = require('./src/app.js');
const server = awsServerlessExpress.createServer(app)
module.exports.universal = (event, context) => awsServerlessExpress.proxy(server, event, context);

This is the file AWS lambda will call when a request hits it. Don’t think too much what this file does just think of this like the local.js file that you use if you want to start the server locally.

Create file “ serverless.yml ”

This is the serverless configuration file. To know more about this file check out their docs from the official link here.

Create a new file serverless.yml also in the same location where you created lambda.js and package.json exists. Insert the following code inside it.

serverless.ymlservice: expressInAWSDemo #Name of your App
provider:
name: aws
runtime: nodejs10.x # NodeJS version
memorySize: 512
timeout: 15
stage: production
region: us-east-1 # your AWS region
functions:
api:
handler: lambda.universal
events:
- http: ANY {proxy+}
- http: ANY /

For this tutorial, we will use the minimal configurations for the serverless.yml file to deploy a simple app.

These configurations should work well for most API calls. If you need to send and receive files in aws lambda you must make appropriate configurations in the serverless.yml file or make changes in AWS API Gateway settings directly.

Note your region

The important thing you need to know in the configuration is the value of the region. The region is the AWS region where you want to deploy the app, you can find the region name from the URL you see when you log in into your AWS management console.

https://console.aws.amazon.com/console/home?region=us-east-1 ← this one

Step 4 : AWS CLI

Download and install AWS CLI from their official site aws.amazon.com/cli

After installing AWS CLI open your Command prompt or terminal and enter the command

aws configure

It will ask you for four things

  • AWS Access Key ID
  • AWS Secret Access Key
  • Default region name
  • Default output format

Get access keys

To maintain best practices AWS doesn't recommend you to use Access Key ID and Secret Key ID of the root user of the AWS i.e the main account you use to manage your AWS console instead it recommends you to create IAM users and generate Access keys for them. If you create IAM users you need to give them permissions for them to use AWS API Gateway and Lambda function and this is a complete tutorial in itself which I’m not going to cover here.

If you are following this tutorial in your local machine and feel completely safe to use access keys of root user in the system just go and generate the access keys by following steps below

  • Log in to your AWS console
  • Click the drop-down on the top navigation where you see your user name
  • Click My Security Credentials
  • Click the option “Access keys (access key ID and secret access key)”
  • Click “Create new Access key”

Download the file and keep it safe, the file contains your Access key and Secret Key needed to configure the AWS CLI

Enter in the command line

aws configureAWS Access Key ID : ****************ABCD <-- access key
AWS Secret Access Key : ****************EFGH <-- Secret key
Default region name : us-east-1 <-- AWS region
Default output format : JSON <-- Enter JSON here

You have successfully configured your AWS account in your local machine. Now let us enter some scripts in package.json file to start our app to test locally and deploy it to AWS.

Step 5 : Deploy the app to AWS Lambda

Edit package.json file

In you package.json file enter the following inside scripts

"scripts": {
"start": "node local.js",
"deploy": "serverless deploy"
},

The start script lets you to starts the local.js file, this will help you to run and test your app locally.

The deploy script is what we will use to deploy our app to aws.

Deploy

Run the following command, the execution might take some time.

npm run deploy

If you have done everything correctly you should get the following output in the terminal

> express_in_aws@1.0.0 deploy D:\User\express_in_aws
> serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
.....
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service expressInAWSDemo.zip file to S3 (766.4 KB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.................................
Serverless: Stack update finished...
Service Information
service: expressInAWSDemo
stage: production
region: us-east-1
stack: expressInAWSDemo-production
resources: 11
api keys:
None
endpoints:
ANY - https://urusd9dq7h.execute-api.us-east-1.amazonaws.com/production/{proxy+}
ANY - https://urusd9dq7h.execute-api.us-east-1.amazonaws.com/production
functions:
api: expressInAWSDemo-production-api
layers:
None
Serverless: Run the "serverless" command to setup monitoring, troubleshooting and testing.

Check your function

Log into your aws management console and select lambda from services, you should see your deployed function.

Get your API endpoint

Invoke your function using the api endpoints. You can find your api endpoint printed in the terminal once you deploy your app or you can find in you aws lambda management console. Just click the function name and click API Gateway, it should display your endpoint.

aws api gateway endpoints
aws api gateway endpoints

Invoke your function

Use the endpoints to invoke your function, remember we made GET request with /time which displays the current time so call the endpoint with /time

NOTE: Make sure to monitor your aws bills

The serverless will store all your app files in AWS S3 storage, creates an AWS API Gateway and an AWS Lambda function so be sure to check billing charges for the services. To know more about how serverless works check their official site. This is not the only method out there, you can also checkout AWS CodeStar.

Hope you find this tutorial helpful.

Ashiq Sultan

Written by

Full Stack Web developer | Tech enthusiast | Learner

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade