tip minersTip Miners

Deploy Express Js Application to AWS Lambda

to deploy your express JS app to a lambda function you need to make us of serverless framwork with serverless-http packageWritten by Miguel

The easiest way to deploy an Express JS app to a lambda function without affecting significantly your code base is to use the Serverless framework to deploy your app and use serverless-http node package to wrap your Express Js application to run on AWS lambda HTTP API gateway.

Steps

  1. Start by installing the Serverless framework globally on your local environment with 
    npm install -g serverless
  2. Being at the root of your Express JS app install serverless-http node package with 
    npm i serverless-http
  1. At the root of your Express JS Application add a serverless.yml file with the following minimum content:
service: name-of-yourapp
frameworkVersion: '2 || 3'
useDotenv: true
provider:
  name: aws
  region: us-east-2
  runtime: nodejs14.x
  lambdaHashingVersion: '20201221'
functions:
  api:
    handler: serverlesshandler.handler
    events:
      - httpApi: '*'
  
  1. Now, from the previous step, you noticed that you require to create a handler function with a specific name, being on the root folder of your project, create a file named serverlesshandler.js and add the following content :
const serverless = require('serverless-http');
const app = require('./src/app');
module.exports.handler = serverless(app);

Here you can note that you require to have your Express App isolated from your http server

  1. You need to have an Access Key and an Access Key ID for your AWS account with enough access to deploy an aws lambda app ( cloudformation objects ) , once you have those add them to your .env file like this :
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
  1. Lastly, on your terminal ( shell, bash ) being at the root of your project, run : 
    serverless deploy

👍🏼 Dos

  • Have your express app exported in a separate module from your HTTP server, this is a generally good practice for express apps, it allows you to decouple your app from your HTTP server for diff
  • Put attention to the region you configure on serverless.yml file , later is you need to have access to aws assets they need to be on the same region to have access

👎🏼 Dont’s

  • Avoid committing your .env file with your access to AWS
  • Do not use serverless template for express js , the repository has outdated config for YML and other things, even more, the command on the online docs does not work for cloning the template

More articles of AWS - Amazon Web Services

Connect a MySQL - AWS RDS from an AWS Lambda-hosted Express JS App

Connect a MySQL AWS RDS from an AWS Lambda-hosted Express JS App