Deploy Nestjs application created by Nx to AWS Lambda using the serverless framework to deploy it

Nx can create monorepo application easily. And Serverless Framework can deploy and maintain your Nestjs applic […]

広告ここから
広告ここまで

目次

    Nx can create monorepo application easily. And Serverless Framework can deploy and maintain your Nestjs application easily too.

    But, when we created the Nestjs application by Nx and want to deploy AWS Lambda by using Serverless Framework, we need to update your Nestjs code a little.

    Install npm modules for AWS Lambda and Serverless Framework

    We need to install npm modules for your Nestjs application.

    $ yarn add serverless-lambda-nestjs
    
    // For Serverless Framework
    $ yarn add -D serverless-layers 
    
    // For TypeScript
    $ yarn add -D @types/aws-lambda

    Create Lambda Handler on the main.ts

    In Nx, the Nestjs application entry-point is src/main.ts. We can update the path from workspace.json, but can not set multipile.

    So, we need to add handler function for AWS Lambda into the file.

    Here is the example.

    import { Logger } from '@nestjs/common';
    import { NestFactory } from '@nestjs/core';
    import { ServerlessNestjsApplicationFactory } from 'serverless-lambda-nestjs';
    import { APIGatewayProxyHandler } from 'aws-lambda';
    import { AppModule } from './app/app.module';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      const globalPrefix = 'api';
      app.setGlobalPrefix(globalPrefix);
      app.enableCors({
        origin: '*',
        allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
      });
      const port = process.env.PORT || 3333;
      await app.listen(port, () => {
        Logger.log('Listening at http://localhost:' + port + '/' + globalPrefix);
      });
    }
    
    // Run Nestjs application locally
    if (process.env.NX_CLI_SET) {
      bootstrap();
    }
    
    // Run Nestjs application in AWS Lambda
    export const handler: APIGatewayProxyHandler = async (event, context) => {
      const app = new ServerlessNestjsApplicationFactory<AppModule>(
        AppModule,
        {
            // NestFactory.create's option object
            cors: {
              origin: '*',
              allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
            },
        }
      );
      const result = await app.run(event, context);
      return result;
    };

    NX_CLI_SET is an environment variable added by Nx CLI. So when the value available, Nestjs should run the application, but if not exists, should not run. Because the env is AWS Lambda.

    Create serverless.yaml on the project root

    Next, we need to create a YAML file for the Serverless Framework.

    Nx build our Nestjs application to the //dist directory.
    So I recommend creating the YAML file in the project root.

    service: nx-nestjs-api
    
    custom:
      prune:
        automatic: true
        number: 3
      serverless-layers:
        dependenciesPath: ./package.json
    
    provider:
      name: aws
      runtime: nodejs12.x
      region: us-east-1
      profile: default
      stage: development
    plugins:
      - serverless-layers
    
    package:
      individually: true
      include:
        - dist/apps/api/**
      exclude:
        - '**'
    
    functions:
      index:
        handler: dist/apps/api/main.handler
        events:
        - http:
            cors: true
            path: '/'
            method: any
        - http:
            cors: true
            path: '{proxy+}'
            method: any

    Build and Deploy

    Finally, we can deploy our Nestjs application.

    # Build Nestjs applciation
    $ yarn build
    
    # Deploy to AWS
    $ serverless deploy

    広告ここから
    広告ここまで

    Random posts

    Home
    Search
    Bookmark