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.
To get started with NestJS, follow these steps:
A NestJS application is an open-source, back-end framework for Node.js, so it is required that Node.js be installed.
Run the following command to create a directory for the NestJS project.
mkdir nest-application
Install the Nest CLI to set up the Nest environment by running the following command.
npm i -g @nestjs/cli
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.
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();
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 the NestFactory
class and the App_Module
module.
In the app.module.ts
file:
Lines 5–9: We define three properties in which the imports
property specifies the dependencies for the module, the controllers
property specifies the controllers that handle incoming requests, and the providers
property 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 the getGreeting()
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_class
class with an @Controller()
decorator. The class has a constructor that takes an instance of the Service_class
class as a parameter and a GET
endpoint handler method called the getGreeting()
method of the Service_class
class. When a request is made to the specified endpoint, this method is called and returns the greeting message.
Free Resources