Serverless + Nx + NestJS — Part II

Hareesh
2 min readDec 8, 2023

In the previous article, we discussed about how a NestJS Serverless Project can be created within the NX workspace. In this article, we will learn two different approaches to running the projects locally during the development phase.

The first approach is developer friendly and avoids the usage of serverless, which means running the app as a NestJS application. This is mainly useful when the project is of type a multi-project workspace.

The second approach is for testing application end to end with simulation of the serverless in local.

As a first step we have to create need to have two main entry files namely below,

  • main-nest.ts : It has the configuration that suits running the application as NestJS.
  • main.ts : It has the configuration that suits running the application as serverless application.

Once you have created above two files, update the project.json file to add new build configuration like below, as you could notice that we are pointing it to the main-nest.ts.

"nest": {
"main": "apps/sample-app/src/main-nest.ts",
"optimization": true,
"extractLicenses": true,
"inspect": true,
"fileReplacements": []
}

Similar to above add new configuration within the ‘serve’ configuration as well, so we can run the application nestjs.

{
...
"serve": {
"executor": "@nrwl/js:node",
"options": {
"buildTarget": "sample-app:build"
},
"configurations": {
"prod": {
"buildTarget": "sample-app:build:prod"
},
"nest": {
"buildTarget": "sample-app:build:nest" // nest conifugration
}
}
}
...
}

By default remaining all build configuration will point to the main.ts, which is Serverless configuration. so no need to of any configuration changes for the build.

Finally we are at the end, to serve the application the commands are below

# runs the application as nestjs.
npx nx run sample-app:serve:nest

# as serverless application, nodemon is another node module to look for the changes, so that we can re-run the sls with file change.
npx nx run sample-app:build --watch && nodemon --watch dist --exec serverless offline --config=serverless.yaml

--

--

Hareesh

Everything will be Alright in the End, if not then it's Not an End.