(NestJS -1) Introduction to NestJS

Bhargava Chary
8 min readMay 20, 2024

--

This series will provide you with a step-by-step guide to setting up a NestJS application, from the basics to a production-ready project. We will explore the core elements of NestJS, how they work together, and walk you through a straightforward example to kick-start your project. This comprehensive guide will help you build a solid foundation and advance towards creating robust, production-grade applications.

In this article, we will give a general outline of constructing a basic NestJS application. We will look into the fundamentals of each element, their collaboration, and guide you through a straightforward example to kick-start your project. To make this series more practical and relatable, we will use an e-commerce application as our example throughout the guide.

Prerequisites

Before beginning, you should have a basic understanding of TypeScript, JavaScript, Express.js, and some Object-Oriented Programming (OOP) concepts like classes, objects, interfaces, and inheritance.

What is NestJS?

NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It uses TypeScript by default and is heavily inspired by Angular, leveraging its modular architecture and dependency injection patterns. It is built with and fully supports TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

Why Use NestJS?

  • TypeScript: Enjoy the benefits of a strongly typed language, which can catch errors early in the development cycle.
  • Modularity: Organize code in modules to enhance reusability and scalability.
  • Dependency Injection: Manage your dependencies effectively and write testable, maintainable code.
  • Out-of-the-Box Support: Get robust support for common functionalities like validation, database integration, Exception handling, logging services and more.

Setting Up Your Development Environment

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (version >= 16)
  • NPM (comes with Node.js)
  • Code editor (VSCode recommended)

Installation NestJS CLI

We need to install the NestJS CLI globally, To create and manage NestJS projects. Use below command to install:

npm install -g @nestjs/cli

Creating a New Project

Open Command Prompt and navigate to your working directory before starting the project creation process.

cd <path to your working directory>
//exmaple $ cd Desktop

You can create the NestJS application in 2 ways mainly:

1. Create Using CLI

NestJS provides a command to create a basic application with some setup files and a src folder:

nest new project-name

Nestjs support different package manager(npm recommended)

2. Clone from Git

$ git clone https://github.com/nestjs/typescript-starter.git project-name
$ cd project-name
$ npm install

Replace “project-name” with the desired name for your project.

Project Structure

A typical NestJS project structure looks like this:

  • src: Holds all the resource files of application.
  • app.controller.ts: Handles incoming requests and returns responses.
  • app.service.ts: Contains business logic.
  • app.module.ts: The root module that ties everything together.
  • main.ts: The entry point of the application.
  • .spec.ts: These are testing file.
  • package.json: It contains metadata about the project, as well as information about the dependencies, scripts, and various other configurations.
  • .json: These are config files.

In NestJS we mostly working with the files like Root Module, User Modules, Controllers and Services.

Nest is built around a language feature called decorators. we mostly use classes and decorators. In order to better understand how it works I recommend to read this article

Main File

The main.ts file contains a async function, which will bootstrap the application.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap()

The NestFactory is used to create a application instance using the create method which return’s a “NestApplication” object.

Module

The root module, often named AppModule by convention, serves as the entry point of your NestJS application. It is responsible for bootstrapping the application, configuring the dependency injection container, and organizing the application's features into cohesive units called modules. A module is a class annotated with a @Module() decorator.

Here’s a how controllers in NestJS looks:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

To create a controller using the CLI, simply execute the $ nest g module [name] command.

Controller

Controllers in NestJS play a crucial role in handling incoming HTTP requests like Get, Post, Put, Delete and sending back responses to clients. They act as intermediaries between incoming requests and the business logic of your application, typically implemented in services. In the following example we’ll use the @Controller() decorator, which is required to define a basic controller. It allows us to easily group a set of related routes, and minimize repetitive code. It takes a name to define a group of related routers.

Here’s a how controllers in NestJS looks:

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('') // it defines http get request
getHello(): string {
return this.appService.getHello();
}
}

There are other decorators which we use in controllers, they are Post, Put,Patch, Get, Delete. It takes a name to easily identify the router.

The controllers are mainly used to handle user requests and check if the user has Authority to access that service. Its main functionality is used to accept the request and return the response. We don’t write any logic in controllers.

We mostly use asynchronous function to handle multiple requests simultaneously, async / await keeps our asynchronous code organized and more readable.

To create a controller using the CLI, simply execute the $ nest g controller [name] command.

Service

A service in NestJS is a class that encapsulates reusable business logic and can be injected into other components, such as controllers or other services, using dependency injection. Services promote code reuse, maintainability, and test ability by separating concerns and keeping controllers lean. This service will be responsible for data storage and retrieval, and is designed to be used by the controllers. In the following example we’ll use the @Injectable() decorator, It marks a class as a provider that can be injected into other components, such as controllers, other services, or modules.

Here’s a how controllers in NestJS looks:

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

The service will act as a layer between database and controller.

To create a service using the CLI, simply execute the $ nest g service [name] command.

CRUD Generate

In applications, we often build various features to meet business requirements. To do this, we need to create CRUD files to implement the business logic. We have discussed how to create each resource file in the above section.

To reduce the repetitive process of creating these files manually, the NestJS CLI provides a command to generate all the basic required resource files at once:

$ nest g resource [name]

This command generates a folder with the given name, It includes several files, such as module.ts, service.ts, controller.ts, as well as testing files (.spec files).

Additionally, it creates an entity folder with an entity.ts file extension and a DTO (Data Transfer Object) folder with some dto.ts file extension.

The Entity files are used to define the data structure of a database table and DTO files are used to define the structure of income and outgoing data.

Testing the application

Now, start the application in the terminal or command prompt using the command below in the root directory path. This command will start the HTTP server on the port you have defined in the src/main.ts file:

$ npm run start

we have another command which will watch the file changes in the application and reload it on save:

$ npm run start:dev

If application is running, the application will run on HTTP server on localhost Ip on the given port number in app/main.ts file.

You can see the log in console like above. Now you can test your application in different ways like postman, web browser, VScode extensions and soon.

Option 1: Using Postman Application

If you already have Postman installed, open it. If not, you can download it from the official Postman website.

  • Click on the + button to open a new tab.
  • Select the Request type as get and enter the request url http://localhost:3000 in request box.
  • Click the Send button. It will send the request to the given url and display the response in the response section. Our application response should be Hello World!

Option 2: Using Extensions in VSCode

You can also use Postman-like extensions in VSCode for API testing, such as Postman or Thunder Client. Here's how you can set it up:

  • Open VSCode.
  • Go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window or by pressing Ctrl+Shift+X.
  • Search for Thunder Client and click Install.
  • Open the extension from the sidebar.
  • Click on New Request from the sidebar. Select the Request type as get and enter the request url http://localhost:3000 in request box.
  • Click the Send button. The response should be Hello World!

Option 3: using web browser

Open the new tab in the browser and navigate to the url http://localhost:3000. The response should be Hello World!

Note: The web browsers can be used for get only requests which do not require any authentication or Authorization to access.

For more in details please refer to official documentation

GitHub Repository:
You can find the complete code for this implementation on GitHub: bhargavachary123

Conclusion

In this article, we covered the basics of setting up a NestJS project using either the NestJS CLI or by cloning a starter repository. We explored the fundamental building blocks of a NestJS application, including modules, controllers, and services.

By following this guide, you should now have a solid foundation for starting your own NestJS projects.

Check out the next article to learn about configuring custom config module.

Contribution

If you like my Article, please, consider donating through Buy Me a Coffee: https://buymeacoffee.com/bhargavachary

If you found this article useful, please consider leaving a clap (👏) and a comment.

Thanks for reading this far! Happy coding with NestJS!

--

--

Bhargava Chary
Bhargava Chary

No responses yet