DEV Community

usufjameel
usufjameel

Posted on

How to Deploy Existing NodeJS Express application as an AWS Lambda Function using Serverless Framework

There are seven easy steps to deploy your existing NodeJS ExpressJS application as an AWS Lambda Function using Serverless Framework.

Step 1

Installing Dependencies

$ npm init -y
$ npm install --save serverless-http
Enter fullscreen mode Exit fullscreen mode

Step 2

Do not start the server instead export it

const serverless = require("serverless-http");
...
...
...
// app.listen(port, () => {
//     console.log(`listening On PORT -> ${port} `);
// });

// Export your Express configuration wrapped into serverless function
module.exports.handler = serverless(app);
Enter fullscreen mode Exit fullscreen mode

Step 3

install and Configure the Serverless Framework

$ npm install -g serverless

Prefix the command with sudo if you’re running this command on Linux.

$ sls config credentials --provider aws --key <aws_access_key_id> --secret <aws_secret_access_key>
Enter fullscreen mode Exit fullscreen mode

Step 4

Add serverless.yml file in your project. Follow the link for more details.

service: example-project

provider:
  name: aws
  runtime: nodejs12.x
  stage: dev
  region: us-east-1

  # you can add statements to the Lambda function's IAM Role here
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "s3:PutObject"
      Resource:
        - "arn:aws:s3:::${file(config.json):S3_BUCKET_NAME}/*"

functions:
  app:
    handler: index.handler
    events:
      - http: ANY /
      - http: "ANY /{proxy+}"

Enter fullscreen mode Exit fullscreen mode

Step 4

Deploy the project
$ sls deploy

Step 5

We have to follow this step for production environment.
Add the NODE_ENV in the secrets.json.

{
  "NODE_ENV": "production"
}
Enter fullscreen mode Exit fullscreen mode

Step 6

Add a reference for the secrets.json in the serverless.yml

service: example-project

custom: # add these two lines
  secrets: ${file(secrets.json)} # reference the secrets.json file

provider:
  name: aws
  runtime: nodejs12.x
  stage: dev
  region: us-east-1

  # you can add statements to the Lambda function's IAM Role here
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "s3:PutObject"
      Resource:
        - "arn:aws:s3:::${file(config.json):S3_BUCKET_NAME}/*"

functions:
  app:
    handler: index.handler
    events:
      - http: ANY /
      - http: "ANY /{proxy+}"
Enter fullscreen mode Exit fullscreen mode

Step 7

That’s it! Delete the node_modules and .serverless folders from the service and run npm install again, but this time with the --production flag.

$ npm install --production
Enter fullscreen mode Exit fullscreen mode

Top comments (0)