Introduction
Is NestJS same as NodeJS?
Simple Answer, it is a framework built on top of NodeJS, providing a structured
and opinionated
approach to building backend services using JavaScript as the language of choice.
Is NestJS vs ExpressJS and why I think industry is starting to move from Express?
To answer this question, we need to understand that NestJS follows (MVC) Model-View-Controller
patterns while in Express it doesnt follow any specific patterns even though we can follow one as Express is quite unopinionated
. Also through NestJS, we can make highly scalable backend services using the Microservices architecture which might take some overhead in setting it up in ExpressJS. Ultimately, NestJS is preferable for those who want a well-organized, scalable application, while Express is better suited for minimal and highly customizable setups. But fun fact, it uses Express under the hood.
What needs to be known in advance to move forward?
We need to know TypeScript
and OOP
along with FP (Functional Programming)
and FRP (Functional Reactive Programming)
.
Installation
npm i -g @nestjs/cli
The above command will install nestjs
CLI globally to help us start the nextjs project with ease.
Now to create the new nest project we need to run the command:
nest new <your-program-name> # Example: nest new rest-api
After running the command you will be prompted to select the package manager. You can choose your favorite, in my case I chose pnpm
. After selecting your package manager, the initial files that will be created are shown below:
Let's go in Depth
Now, let's open the main.ts file, in there you will see the following code:
File main.ts
:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
Now, this is the entry point of the whole application that we are going to create in NestJS.
File app.module.ts
:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Now this is the root module of our application and it shows that it has already added AppController for our application
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
as well as the app.controller.spec.ts
which contains all the test cases that we might write for our controller.
File app.service.ts
:
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
The flow of the NestJS application starts with main.ts
, which serves as the entry point. It initializes the application using NestFactory.create(AppModule)
, creating an instance of the app. The AppModule
acts as the root module, registering controllers and providers to manage the application’s structure. Within the module, AppController
handles incoming HTTP requests, defining routes and linking them to appropriate methods. When a request is received, such as a GET /
request, the controller calls the corresponding method in AppService
, which contains the business logic. The service processes the request and returns data, such as a simple Hello World!
response, which is then sent back to the client. This modular architecture ensures a clean separation of concerns, making the application scalable and maintainable.
Running the Application
To run the application, we can use the following command:
pnpm run dev
which would run the application at localhost:3000
in your system. Now if do a get request using postman
or thunderClient
to the route localhost:3000
, then you will get "Hello World"
back in response.
How to add our own module to the application?
Now, remember in the beginning we installed the NestCLI, that would be highly helpful in this scenario. To create the module, we need to run the following command:
nest g module <module_name> # Example: nest g module users
After running the command we will see inside the src
directory, we will see a users
folder which will contain, users.module.ts
. But quite an intesting thing will take place in app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
@Module({
imports: [UsersModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
If you observe carefully, in the imports which was empty before now has UsersModule
that we created just now, which is creating the link from the parent in this case app.module.ts
to the child users.module.ts
.
How to create controller for the module we created?
To create the controller for the module you created in this case it would be users
module, we run the following command:
nest g controller <controller_name> # Example: nest g controller users
which in turn will create users.controller.ts
and users.controller.spec.ts
in the users directory.
How to create service for the module we created?
To create the service for the module you created in this case it would be users
module, we run the following command:
nest g service <controller_name> # Example: nest g service users
which in turn will create users.service.ts
in the users directory.
By running the above commands we have a complete module for our users.
Conclusion
In this blog, we've covered the basics of setting up a NestJS project, understanding its file structure, and creating our own custom modules, controllers, and services. We also learned that the modular architecture of NestJS, which divides the application into modules, controllers, and services, makes it easy to scale and manage as the application grows. In the next phase, we will dive deeper into implementing routing logic and the associated business logic to handle requests efficiently.
You can find the code for this project in the GitHub repository to follow along or explore further. (Leave a star if you feel that it provides any value to you.)
Thank you for reading this small article/blog of mine. What are your thoughts do let me know in the place I will post the link, mainly in Peerlist or X. If you want to form, a group regarding the above topics so that we can learn it together, DM me up on Discord (user ID - call7062
) or on X or Peerlist.