Getting started with NestJS

Getting started with NestJS

How to get started with NestJS Framework to build efficient, scalable Node.js server-side applications.

If you have ever created server-side apps using NodeJS, you might have used express, fastify or other HTTP framework. Although, these are very easy to get started and perfect for small projects involving small team. But, if you want to create a project which will last longer and has many contributors, you need a good application architecture to align the team. You may create this by yourself or you can use existing framework like Nest to accomplish the goal.

What is Nest

Nest(NestJS) is a framework for building efficient, scalable Node.js server-side applications. Nest provides an out-of-the-box application architecture that allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications. So, let's get started:

Prerequisites

  1. Node.js (version >= 12, except version 13)
  2. npm, which is installed along with Node.js

Install Nest CLI

To create nest applications, we need Nest cli. Run the following command to install it

npm install --global @nestjs/cli

Create a new project

Let's create a new project nest-blogs using nest cli. Run the below command to create the project

nest new --strict nest-blogs

When it asks to select a package manager to use, select any one you want to use. I selected npm and will be using that. It will take some time since it will install the required node modules as well. Here, the optional --strict flag enables the strict mode in TypeScript.

Project Structure

Open the nest-blogs directory in any code editor or IDE. We have the following files in the project

Project structure of a new project created using nest cli Let's take a look at the purpose of each file in brief:

  1. The package.json file has information about the project, a list of npm dependencies required for the project, and some useful scripts.
  2. The tsconfig.json and tsconfig.build.json files specify the root files and the compiler options required to compile the project.
  3. The nest-cli.json file is used by the nest to keep the metadata needed to organize, build and deploy the project.
  4. The .prettierrc file is a configuration file used by Prettier tool to format the code.
  5. The .eslintrc.js file is used by ESLint to identify and report on patterns found in ECMAScript/Javascript code.
  6. The app.controller.ts is a basic controller with a single route. Controllers are used to map the incoming request to specific functions and to return the response back to the client.
  7. The app.controller.spec.ts is a unit test for the controller.
  8. The app.service.ts is a basic service with a single method. Services are the places where we put the business logic of the application.
  9. The app.module.ts is the root module of the application. Modules are used to divide the application into seperate parts depending on the responsibility.
  10. The main.ts is the entry point of the application which uses the core function NestFactory to create a nest application instance.

Running the application

While creating the application, if required node modules are not installed due to some reason or if you have used --skip-install flag, run the below command to install packages now from the nest-blogs directory

npm install

Run the below command to start the applicatin:

npm start

Open http://localhost:3000/ url in the browser. You should see Hello World! on the page. Press Ctrl ^ c in the terminal to stop the app. While developing the app, we want the app to restart automatically as soon as we make any changes. To do that, run the below command in the terminal:

npm run start:dev

If we again go to the same link, we see the same text. Now, do the following:

  1. Open 'app.service.ts` file in editor.
  2. Change getHello method to return Hello Universe instead of Hello World!.

    import { Injectable } from '@nestjs/common';
    
    @Injectable()
    export class AppService {
     getHello(): string {
       return 'Hello Universe';
     }
    }
    
  3. Save the file.
  4. Go to the same link and reload the page.
  5. We see Hello Universe on the page.

This way, we don't need to stop and start the server manually. It will restart as soon as it detects changes in any project-related file(s).

Platform

Nest can work with any Node HTTP framework using adapters. Nest provides out-of-the-box adapters for two HTTP frameworks - express and fastify.

  1. platform-express is the adapter for express and it is used by default in Nest projects. We don't have to do anything additional to use express.
  2. platform-fastify is the adapter for fastify. To work with fastify instead of express, below steps are required -

    1. Install the required package using
      npm install --save @nestjs/platform-fastify
      
    2. Modify main.ts to use FastifyAdapter to create the application

      import { NestFactory } from '@nestjs/core';
      import {
      FastifyAdapter,
      NestFastifyApplication,
      } from '@nestjs/platform-fastify';
      import { AppModule } from './app.module';
      
      async function bootstrap() {
      const app = await NestFactory.create<NestFastifyApplication>(
        AppModule,
        new FastifyAdapter(),
      );
      await app.listen(3000);
      }
      bootstrap();
      
    3. Restart the application and make sure it works.

Summary

In this article, we have setup a basic Nest project. In the upcoming blogs, we will explore more. You can find the project on github. Please provide your feedback in the comments. We will meet in the next blog. Until then, happy learning.