cover-img

Switching to serverless.

Hosting your expressjs app with serverless.

9 May, 2022

14

14

0

Months after deploying my apollo-express server api on bare metal, I'm switching to hosting on AWS, here my motive is get express api end point proxy that runs through AWS Lambda.

To set up serverless on your local machine (if you dont have it already or want to update) open your terminal window and install by

npm install -g serverless

Once installation is complete, initialise global package by typing serverless, type Yes for Do you want to create a new project? select AWS Node.js from the list of options available and type in required project name.

Next, the package will ask you for your AWS credentials that you'll get from dashboard of your AWS Account. It'll require AWS Access key Id and AWS Secret key.

Next, you'll be prompted to set up command line tab completion, go ahead and select as per your preferred command line.

Finally, according to your project name, serverless will create a directory named by you with all the files it needs. We copy those files to the root of our project. Files will be -


To deploy our serverless project, we run the following command from our root directory

sls deploy

It looks up for out serverless.yml file and deploys all the resources we've specified within it, mainly our Lambda function which will be proxy for our api calls. Lets edit that function according to our server.

My server has 55 APIs currently exposed, one of which is fetching user details

user-resolver.js


From our root directory we can define our lambda function to connect it to our apollo-express server as follows

  1. We install one more dependency

npm i aws-serverless-express

  1. Back in our root directory, we export serverless handler by aws-serverless-express

handler.js


  1. We make a few changes in our serverless.yaml file to tell AWS about our new module handler.

Above yaml configuration has a function app-api which is a handler that's setup to respond to any request that gets sent to it and second event acts as a proxy for any method we specify, first on the root \ itself and every other appended api route.

  1. Deploy

We've finished our configuration and we deploy it by running sls deploy via terminal.

After deployment has finished we get two endpoints to query those will look something like.

GET - https://renj2wbwig.execute-api.{your region}.amazonaws.com/dev/

ANY - https://renj2wbwig.execute-api.{your region}.amazonaws.com/dev/{proxy+}


In this short blog we learnt how to take a pre-existing express server (Apollo-Express Server for me) and publish it using AWS Lambda.

14

14

0

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

Ā© Copyright 2024. Showcase Creators Inc. All rights reserved.