Turn Nest.Js into Serverless with Nitric in a few seconds
![Turn Nest.Js into Serverless with Nitric in a few seconds](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1693062885590%2F9ab5faec-ee2e-4718-88eb-892a6836f843.png&w=3840&q=100)
Hi, my name is Nyoman Sunima. Product Designer and full stack developer. Today I want to share with you a new way to become serverless using your Nest.js application in just a few steps and seconds.
This post will help you create and deploy your serverless backend API easily and without too much effort. Before I jump in, let me tell you about my problems and challenges.
Challenges
When I build a normal Express backend API, I need to know too much about cloud infrastructure. First, think about where I should deploy my project. spec of servers, type of server (vpc, instances, containers, or cloud-native).
Sometimes, when I finish local development, the project never goes live. It's because I need more setup time when deploying the application than the actual time it takes me to code my projects.
That's why so many people love serverless. Alright, I am not saying that serverless is suitable for all cases. But think again when you are building a microservice or simple project. I think you should consider using serverless.
When you are building portfolio projects or dummy projects, you will realize that the actual server never becomes free. For example, AWS EC2 will only allow you to run for about 28 days in a month. Then you need to configure so many things before you can deploy it automatically.
NestJs and Serverless Challenges
Alright, now you know that serverless is powerful and may match your development case. Now the problem is that the setup of the Nest.js application to become serverless requires much effort.
If you are using Express, you might not think too much. Just install some dependencies, and you can make it a serverless project. But if you love to use Nest.Js and want to make it serverless, you need to do more than just install dependencies.
In my case, I have developed a project using Nest.js, which I should then deploy into a serverless project. I need to install serverless, the AWS Lambda adapter, and set the build using Webpack. Then, after that, you will realize that you will get an error when you deploy.
You need to add another plugin and configure it to make it work properly on AWS Lambda. After you realize that it's going to take half a day to set up your Nest.js project into serverless,
I faced this issue and think that developing serverless applications requires many adaptations before I can code. Now I've found the solution. it's called Nitric.
Let me explain more about it.
What's Nitric and why you should use it?
Nitric is an application framework that allows you to build serverless applications without too much effort. They want to provide you with a framework that allows you to work closely with the serverless platform and turn it into code.
Nitric works like Pulumi. They are using Pulumi behind them. But the difference is that they provide you with a general approach to building your application without the need to address specific providers like Amazon or Google.
So when you need to deploy your application to a different provider or use a custom provider, it's possible. So don't worry about compatibility and vendor lock-in.
This feature allows you to deploy your application to different providers at the same time. For example, for stagging deployment to GCP, and production deployment to AWS.
Benefits
Here are some of the benefits and pros when I using Nitric in the development process.
Focus on writing code without worry and think about infrastructure, providers, and scallability. Nitric handles them all.
Easy to set up and easy to run. Beginning from the first step until the application runs, you just need to run a few commands on the terminal
Support multi-providers and even custom providers.
Support auto-deployment using Github Actions
Local Development Environment allows you to run the application on a local machine without needing to connect to your serverless provider
Moving providers without changing a single line of code
Provide almost anything you need to build a backend application, including a database, storage, event-driven messages, and an API.
Nitric also supports HTTP. NOTE: For now, HTTP only supports node.js frameworks like Express, Fastify, Nestjs, and so on.
I will cover them all in detail later, so stay tuned. Now let's move on to how to work with Nest.Js. For more information on nitric please refer to Nitric Official Site
How do I make Nest.JS serverless?
Nitric provides a new feature called HTTP. It allows you to turn your HTTP server into a serverless one. So without further ado, let's get into it
Prerequisites
Before you can use nitric, you need to install some dependencies and stacks on your local machine, including
Nitic Server - Provide a local server for application development.
Pulumi CLI - Nitric using Pulumi to deploy your stacks.
Node.js & npm - Running Nest.js application
Docker Create docker image for project
Local Development: Nest.js using nitric
Start by creating a new nest project by running
npx @nestjs/cli new nitric-nestjs
It will create a new NestJS project called Nitric-NestJS. Follow the instructions, then open it in your code editor.
Install the Nitric SDK
npm i @nitric/sdk
Open the main file, and then you will find the bootstrap function. All you need to do is just remove the port, and then make the application run on the specified port from the argument passed to the bootstrap function.
/** * Initialize the application and starts listening on the specified port. * * @param {number} port - The port number to listen on. * @return {Promise<void>} - A promise that resolves when the application is successfully started. */ async function bootstrap(port: number) { const app = await NestFactory.create(AppModule) app.useGlobalPipes( new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: false, transformOptions: { enableImplicitConversion: true, }, }), ) app.use(compression()) app.use(helmet()) app.enableCors({ origin: '*', }) // listen on a provided port from nitric await app.listen(port) }
Now all you need to do is import the `http` from '@nitric/sdk', then pass the bootstrap function.
import { http } from '@nitric/sdk' // the code before // this will transform your application // into serverless with adapter http(bootstrap)
Alright, now everything is fine. All you need to do is start the nitric server by running
nitric start
then run the Nest.Js application on development mode using
npm run dev
The command above will start the Nitric server on your local machine and also start the development for Nest.Js. Now you can enjoy coding.
!optional if you are not comfortable with the command and want to execute it on a single line of code. All you need to do is install it concurrently by running
npm i -D concurrently
Then all you need to do is change the scripts on your "package.json" into
"scripts": { // your other secrets "dev": "concurrently \"nitric start\" \"nest start --watch\"", }
Now it's done.
Start the application by running `npm run dev`. Now you can see the results
Deploy Application to the cloud provider
To deploy your serverless application to a serverless provider like Google or Amazon Web Services, you need a few commands to set up and deploy.
Create a new stack for deployment by running this command
nitric stack new
This command will ask you about the stack name. let's just call it "staging". Then it will move to choose the provider, for now, let's use GCP. You may ask for some information. Just fill it out with your preferences.
Now, after finishing, it will create a new file called "nitric-staging.yaml". And the inside looks like this.
name: staging provider: nitric/gcp@0.32.0 gcp-project-id: test region: us-east1
To deploy, please ensure you have already installed the prerequisites and logged into your Pulumi account. Then run the following command:
nitric up -s staging -v0
This command will create a Docker image and configure your GCP account to be ready. After the deployment finishes, you will see the URL. If not, you can login to pulumi account and then find the resource URL
Conclusion
What do you think? Have you tried it? It looks easy, right? In my opinion, I would prefer to use Nitric to make my application serverless. Rather than other frameworks like serverless, which need to be configured too much to just deploy a single function,
If you have any questions or anything related to this article, Please let me know in the comment section. Don't forget to like it if it's useful.
Looking for collaboration or projects? Please let me know. I would be glad to hear about your problem.