What is NestJS?
NestJS is a popular open-source, back-end framework for Node.js and TypeScript-based, server-side applications. It is intended to provide a solid foundation for developing server-side applications by leveraging well-known patterns and the best practices from other frameworks such as Angular, Express.js, and others.
NestJS is a modular and adaptable framework that allows developers to easily organize their code into smaller and reusable modules. It also includes a robust dependency injection framework that simplifies managing application components and dependencies. NestJS also supports several server-side rendering techniques and interfaces with other Node.js modules and tools.
Installing NestJS
To get started with NestJS, follow these steps:
Step 1: Install Node.js
A NestJS application is an open-source, back-end framework for Node.js, so it is required that Node.js be installed.
Step 2: Make a directory
Run the following command to create a directory for the NestJS project.
mkdir nest-application
Step 3: Install NestJS
Install the Nest CLI to set up the Nest environment by running the following command.
npm i -g @nestjs/cli
Step 4: Project creation
Finally, create the project by using the following command.
nest new nest_application
Now we can run the project by simply using the npm run start command.
Code example
Let's look into the following programming example for a better understanding.
import { NestFactory } from '@nestjs/core';
import { App_Module } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(App_Module);
await app.listen(3000);
}
bootstrap();
Code explanation
Let's understand how the code above works by breaking it down.
In the main.ts file:
Lines 4–7: We define an asynchronous function called
Bootstrap()that creates a NestJS application using theNestFactoryclass and theApp_Modulemodule.
In the app.module.ts file:
Lines 5–9: We define three properties in which the
importsproperty specifies the dependencies for the module, thecontrollersproperty specifies the controllers that handle incoming requests, and theprovidersproperty specifies the providers responsible for creating and managing instances of services or repositories used throughout the application.
In the app.service.ts file:
Lines 4–7: We define a class with the name of
Service_class. It only has thegetGreeting()method, which is used to reflect the following message on the screen:Welcome to the Educative Answers!.
In the app.controller.ts file:
Lines 5–12: We define a
Controller_classclass with an@Controller()decorator. The class has a constructor that takes an instance of theService_classclass as a parameter and aGETendpoint handler method called thegetGreeting()method of theService_classclass. When a request is made to the specified endpoint, this method is called and returns the greeting message.
Free Resources