AWS Lambda + ExpressJS

AWS Lambda + ExpressJS

Express.js is one of the most popular tools for web application development in Node.js. Its ability to handle HTTP requests and simplify routing and error handling is widely recognized in the developer community.

By using Express.js on AWS Lambda, one can leverage its ease of use to create a scalable and high-performance RESTful API. Additionally, by using Express.js in combination with AWS Lambda, one can take advantage of the flexibility and scalability of the AWS serverless computing platform. AWS Lambda allows code to be executed without the need to set up servers and automatically scales capacity based on demand.

Overall, by using Express.js on AWS Lambda, one can create a modern and scalable application architecture that can effectively handle a large number of HTTP requests and can grow and change as business needs evolve.

aws-serverless-express

The Node.js package "aws-serverless-express" is a tool that allows an Express.js application to run on AWS Lambda. This tool creates a custom Node.js server that allows the application to run on AWS Lambda as a serverless function.

Essentially, aws-serverless-express provides a compatibility layer between the Express.js application model and the serverless function execution model of AWS Lambda. This enables developers to quickly and easily create and deploy Express.js-based web applications on AWS Lambda, leveraging the scalability and flexibility benefits of AWS Lambda.

The aws-serverless-express package also includes a set of utilities that simplify the deployment and management of the Express.js application on AWS Lambda, making it a valuable tool for developers looking to create scalable and high-performance applications on AWS Lambda.


Ok, let's start with the necessary configuration:

At the beginning, Lambda provides us with an index.js file to work with, along with the Handler function which is the starting point of our function, showing us a similar code:

// index.js

exports.handler = async (event, context) => 
  console.log('Event: ', event);
  console.log('Context: ', context);
  
  return {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!')
  };
};
        

Commonly, the main file of an ExpressJS application is "app.js". You should remove any code in your main file where you call the port where your application is running.

Additionally, you should add an environment variable in the Lambda function that indicates which environment the application is running in. And it is very important to export the app object.

You can also continue running your application locally with the configuration we will set up.

// app.js

const express = require("express")
const app = express();
var port;


if(process.env.ENVIRONMENT != "lambda"){

  port = process.env.PORT || 3000;

  app.listen(port, () => {
    console.log(`Sever running on port: ${port}`);
  });
} 

app.get("/", (req, res) => {
  res.send("App running 👍");
});

module.exports = app;;        

Now, we will modify the index.js file as follows:

// index.js

const awsServerlessExpress = require("aws-serverless-express")
const app = require("./app");

const binaryMimeTypes = [
  "application/octet-stream",
  "font/eot",
  "font/opentype",
  "font/otf",
  "image/jpeg",
  "image/png",
  "image/svg+xml",
];

const server = awsServerlessExpress.createServer(app, null, binaryMimeTypes);

exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);        

Commonly, ExpressJS applications have the following file structure (if this is not your case, it is not a problem).

No hay texto alternativo para esta imagen

In order to upload our application, we need to zip all the files of our code, including the node_modules folder and the package.json file

# Unix/Linux/Mac

zip -r myapp.zip .        

Now, you can go to the AWS web console, access your Lambda function, and upload your code from the "Upload a .zip file" option

No hay texto alternativo para esta imagen
No hay texto alternativo para esta imagen

Great! Now you have your Lambda function configured to use ExpressJS. The only thing left to do is to configure the API Gateway.


Configuring the API Gateway REST

AWS API Gateway configured to use proxy with a Lambda allows creating a RESTful interface for the Lambda function, which means the Lambda can be invoked via an HTTP URL. This enables easy integration of the Lambda function with other web services and applications, and allows greater flexibility in how the Lambda function is configured and accessed.

Create an "ANY" method on the root resource and select "Lambda Function" integration type, add the function name, and remember to check the "Use Lambda Proxy Integration" checkbox.

No hay texto alternativo para esta imagen

Now create a new resource, and on the create resource page, check the "Configure as proxy resource" checkbox, and in the "Resource Path" field, add "{proxy+}".

Inside this new resource, add another "ANY" method, and configure it in the same way as the first one created. Your API structure should look like this:

No hay texto alternativo para esta imagen

Now deploy your API by clicking on the "Actions" drop-down menu, then on "Deploy API". If this is your first time, just enter the name of the stage you want to use.

With the URL generated by API Gateway, you can now make requests to your API running on Lambda and configured to use ExpressJS.

No hay texto alternativo para esta imagen
No hay texto alternativo para esta imagen

I hope this article has been helpful and provided you with a good introduction to using ExpressJS in AWS Lambda through API Gateway. Thanks for reading and have a nice day!

To view or add a comment, sign in

More articles by Sergio Lara

  • AWS Lambda Layers - NodeJS & Python

    Sometimes we as Cloud engineers / Devs / Solutions Architect, need to use several packages on our Lambda functions, but…

    1 Comment

Others also viewed

Explore content categories