How to deploy a NestJS application using serverless architecture with AWS Lambda
NestJS Serverless
NestJS is a powerful Node.js framework built with TypeScript, ideal for building scalable server-side applications. But did you know you can deploy NestJS in a serverless architecture?
In this guide, we'll explore how to deploy a NestJS app to AWS Lambda using the Serverless Framework.
Why Serverless?
Serverless architecture offers benefits like:
- Cost efficiency (pay-per-use)
- Auto-scaling
- No server management
- Ideal for event-driven applications
Setting Up Your NestJS App
Install dependencies needed for serverless:
npm install --save aws-lambda @codegenie/serverless-express
npm install --save-dev serverless serverless-offline
Configuring Serverless
Create a serverless.yml
file at the root of your project:
service: nestjs-serverless
provider:
name: aws
runtime: nodejs18.x
region: ap-southeast-1
plugins:
- serverless-offline
functions:
main:
handler: dist/lambda.handler
events:
- http:
method: ANY
path: /
- http:
method: ANY
path: "{proxy+}"
Create a Lambda Handler
Create a file lambda.ts
in the root:
// lambda.ts
import { NestFactory } from "@nestjs/core";
import serverlessExpress from "@codegenie/serverless-express";
import { Callback, Context, Handler } from "aws-lambda";
import { AppModule } from "./app.module";
let server: Handler;
async function bootstrap(): Promise<Handler> {
const app = await NestFactory.create(AppModule);
await app.init();
const expressApp = app.getHttpAdapter().getInstance();
return serverlessExpress({ app: expressApp });
}
export const handler: Handler = async (
event: any,
context: Context,
callback: Callback
) => {
server = server ?? (await bootstrap());
return server(event, context, callback);
};
Next, open up the tsconfig.json file and make sure to enable the esModuleInterop option to make the @codegenie/serverless-express package load properly.
{
"compilerOptions": {
...
"esModuleInterop": true
}
}
Build the NestJS App
Before deploying, build your NestJS project so the compiled files are available in the dist
directory:
npm run build
Local Development
Use serverless-offline
to run locally:
npx serverless offline
Deploy to AWS
Deploy your application with:
npx serverless deploy
After deployment, you'll get a public URL for your API Gateway endpoint.
Conclusion
Deploying a NestJS app with Serverless on AWS Lambda allows you to build scalable, cost-effective backends. With minimal configuration, you can go from development to production in minutes.