Delving Developer

NestJS & Serverless: Deploying on AWS Lambda

Eddie Cunningham
Eddie Cunningham
4 min readNestJS
Cover Image for NestJS & Serverless: Deploying on AWS Lambda

NestJS and Serverless Architecture: Deploying NestJS on AWS Lambdalink

In the ever-evolving world of web development, constructing scalable and efficient applications is a primary goal. Combining NestJS with serverless architecture offers an ideal solution for creating scalable back-end applications effortlessly. AWS Lambda further elevates this approach with its cost-effective, highly scalable platform for your Node.js applications. This article explores how to deploy a NestJS application on AWS Lambda, emphasizing the benefits, processes, and best practices for this dynamic combination.

Understanding NestJS and Serverless Fundamentals

NestJS is a progressive Node.js framework designed to build efficient, reliable, and scalable server-side applications. It incorporates features such as dependency injection, an out-of-the-box application architecture, and TypeScript support, making it a popular choice among developers.

Serverless architecture, on the other hand, defines a way of building and running applications without the need for managing infrastructure. The server management is completely handled by cloud service providers, freeing developers to focus more on code and less on server and infrastructure maintenance.

AWS Lambda is Amazon's serverless compute service that automatically manages the computing resources needed upon execution of your code.

Why Deploy NestJS on AWS Lambda?

Using AWS Lambda to deploy NestJS applications presents numerous advantages:

  1. Cost Efficiency: AWS Lambda follows a pay-as-you-go model, allowing you to only pay for compute time you consume, which can drastically reduce costs.
  2. Scalability: Lambda scales your application automatically. This means you can execute code in response to each event as it occurs.
  3. Flexibility: Lambda is flexible in its triggering sources including HTTP requests through AWS API Gateway.

Setting Up Your NestJS Project

To get started, ensure you have Node.js and npm installed. Initialize a new NestJS project with the following command:

npx @nestjs/cli new my-nestjs-app

This command sets up a basic project structure that you can extend according to your needs.

Adding Serverless Framework to Your Project

The Serverless Framework is an open-source tool that simplifies deploying applications on AWS Lambda:

  1. Install the Serverless Framework globally:

    npm install -g serverless
    
  2. Create a serverless configuration file named serverless.yml in the root directory of your NestJS project. This file describes your service and functions, and specifies the AWS Lambda environment. Here’s a simple example:

    service: my-nestjs-app
    
    provider:
      name: aws
      runtime: nodejs14.x
    
    functions:
      app:
        handler: dist/main.handler
        events:
          - http:
              path: /
              method: get
    

Configuring NestJS for Lambda Deployment

NestJS needs to be slightly adjusted for AWS Lambda compatibility. One of the most common methods is using a library such as @vendia/serverless-express to convert the NestJS app into a handler function.

  1. Install @vendia/serverless-express:

    npm install @vendia/serverless-express
    
  2. Update the main.ts file in your NestJS application to export a Lambda handler using @vendia/serverless-express:

    import { NestFactory } from '@nestjs/core';
    import { ExpressAdapter } from '@nestjs/platform-express';
    import { AppModule } from './app.module';
    import * as express from 'express';
    import { createServer, proxy } from '@vendia/serverless-express';
    
    const server = express();
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
      await app.init();
    }
    
    bootstrap().then(() => console.log('NestJS is ready.'));
    
    export const handler = (event, context) => {
      return proxy(createServer(server), event, context);
    };
    

Deploying Your Application

Deploy your NestJS application to AWS Lambda using the Serverless Framework with a simple command:

serverless deploy

This command performs the following tasks:

  • Packages your code.
  • Uploads it to AWS.
  • Deploys the necessary Lambda functions.

Best Practices and Optimization Tips

  • Optimize Cold Starts: Reduce the size of your application by excluding unnecessary packages and using Webpack with serverless webpack plugin.
  • Environment Configuration: Leverage AWS environment variables to manage configuration without hardcoding sensitive information.
  • Monitoring and Logging: Use AWS CloudWatch to monitor your Lambda functions and set up alarms to promptly respond to any issues.

Conclusion

Deploying NestJS applications on AWS Lambda can be transformative, allowing developers to create scalable and efficient applications seamlessly. The integration of NestJS with AWS Lambda through the Serverless Framework offers a modern approach to application deployment that is cost-effective and reactive. Utilizing NestJS's capabilities with serverless solutions positions developers to build applications that are agile, maintainable, and prepared for future growth.

By following this guide, developers can effectively leverage NestJS and AWS Lambda to innovate their web solutions, creating robust, scalable back-end applications. For further reference check the AWS Lambda documentation and NestJS documentation.