Go Serverless With Node.js and AWS Lambda

Make your Node.js Express API run serverless and deploy it to AWS

Juan Cruz Martinez
Nov 20, 2020 · 5 min read
Sun peeking through clouds
Sun peeking through clouds
Photo by Billy Huynh on Unsplash.

Serverless architecture is an alternative to high-maintenance, resource-wasting servers. With serverless deployments, you only have to pay for precisely what you use. And they free you from having to handle multiple server setups and their configurations.

So, it’s no surprise that developers today are flocking to go serverless with their applications. With the help of AWS Lambda and the Serverless framework, you can quickly deploy applications that scale.

In this tutorial, we are looking at deploying a simple serverless API with Node.js, AWS Lambda, and the Serverless framework.

A Bit About These Technologies

AWS Lambda is a cloud-based serverless service. Lambda functions are stateless functions that are triggered by events and expire at the end of their execution.

Given the complex nature of AWS Lambda, we use the Serverless framework to simplify the deployment process. In fact, with Serverless, you can deploy your Node application in just a few steps.

Prerequisites

To continue with this tutorial, you need to have the following things set up:

  • An AWS account. If you are only experimenting with AWS, you can join a free tier without having to pay a dime.
  • Create an IAM user in your AWS console. Follow the steps in this article to create the IAM user. Remember to save the access key ID and secret access key before going to the next step.

Install and Set Up Serverless

You can install Serverless easily with npm. Run the following command to install it globally:

npm install -g serverless

Next, configure Serverless with IAM keys using the following command. Use the ID and key saved when creating the IAM user as the key and secret, respectively:

sls config credentials --provider aws --key xxx --secret xxx

Create the Node Application

I created a simple Hello World application for this tutorial, but you can deploy more complex applications following the same logic:

As you can see above, we use the serverless-http npm package to set up the serverless application, so make sure you have the package installed. You can install the library with:

npm install --save express serverless-http

Create the serverless.yml File

We use a file named serverless.yml to pass Serverless configurations. For our simple application, it contains the following properties:

Here, the functions property lists all the functions in our application. We pass a single function named app and use the exported reference to the handler in the app.js file as the function handler.

Then, we need to add the events that would trigger the given function. We pass the HTTP requests as the triggering events. I have set it up in the configuration above to call the app function every time an HTTP request is sent.

The use of /{proxy+} forwards every request, allowing the Express application to handle every request by itself instead of handling the requests at the API gateway level.

Deploy the Application

Now that we have passed our configuration to the serverless.yml, deploying the application requires only a single command:

sls deploy

And its output will look like this:

Deploy output
Deploy output
SLS deploy output example

Congratulations! You have successfully deployed your first serverless application to AWS.

You can visit the deployed application at the links provided under the endpoints. If you visit the root, you will see the message “Hello World.”

Path-Specific Routing

Remember how we proxied all the routes to the Express application? Though there are benefits to this implementation (e.g. limiting cold starts), we miss out on benefiting from some serverless architecture features.

Instead of routing all the paths with one Lambda function, we can introduce path-specific routes that are handled by different Lambda functions. This allows us to get better insight into the application using path-specific metrics.

In that case, update the serverless.yml like this so that a different function handles each path:

Adding Environment Variables

If you want to pass environment variables to the application, you can use the environment property.

For example, if you want to pass a NODE_ENV variable, you can set it up like this:

If you want to pass the environment variables from a .env file, you need to use the serverless-dotenv-plugin.

First, install the plug-in as a development dependency:

npm install serverless-dotenv-plugin --save-dev

You can then create a .env file in the root directory and add the environment variables to it:

STAGE=dev
SECRET=**********

Once you have listed the dotenv-plugin under the application plug-ins, you can import the stored environment variables and use them inside the serverless.yml file:

Use Serverless Offline

Until this point, we had to deploy our application to carry out even the simplest of route tests. You only have to write 2-3 new routes in your application to realize how annoying this is.

What if there was a way to test your application before deploying it to AWS?

With the use of the serverless-offline plug-in, you can do just that. You only have to install a new npm package and add one new line of code to the serverless.yml file to make this work.

First, install the package:

npm install serverless-offline --save-dev

Then, update serverless.yml:

plugins:
- serverless-offline
- serverless-dotenv-plugin

Now, you simply have to run the following command to start the application locally:

sls offline start

It will show you a list of all the routes in your application. Also, most importantly, it starts your application running locally on port 3000.

You can now test the application routes by visiting them on your browser with the URL http://localhost:3000.

Summary

Serverless architecture is still in its early days compared to servers. You can count on it becoming even more powerful and prominent in the coming years. I hope your first experience with Serverless and AWS Lambda tempted you to give this technology a chance next time you are looking for a deployment option.

Thanks for reading!

Better Programming

Advice for programmers.

By Better Programming

A weekly newsletter sent every Friday with the best articles we published that week. Code tutorials, advice, career opportunities, and more! Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Thanks to Zack Shapiro

Juan Cruz Martinez

Written by

I’m an entrepreneur, developer, author, speaker, and doer of things. I write about JavaScript, Python, AI, and programming in general.

Better Programming

Advice for programmers.

Juan Cruz Martinez

Written by

I’m an entrepreneur, developer, author, speaker, and doer of things. I write about JavaScript, Python, AI, and programming in general.

Better Programming

Advice for programmers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store