NestJS: how and why to use it

With so many great frameworks available for backend development in JavaScript, you may be wondering why would I look for something else rather than simply going for Express or Next? Come to think about it, there may be a couple of reasons.

Perhaps you have to quickly start off the development process with a good boilerplate and adding not only new controllers but also services manually makes you sick. Maybe you want to build a big scalable app that will be easy to maintain. Or you may just want to work in a more effective and convenient way. Regardless of which one is true in your case, it may turn out that Nest.js is just the right answer to your needs.

What is NestJS?

First things first, let’s talk about origins and statistics. NestJS was developed by Kamil Myśliwiec as a framework facilitating the development of scalable server-side applications. As of January 2020, it boasts over 23k GitHub stars and its weekly npm download rate is almost 180k.

When it comes to technicalities, NestJS is, in fact, an abstraction layer built by default from Express.js (it also supports other libraries, e.g. Fastify so you’re free to complement it with whatever solution you like) and Node.js. The framework uses progressive JavaScript, fully supports TypeScript, and combines three principles:

  • OOP (Object Oriented Programming),
  • FP (Functional Programming),
  • FRP (Functional Reactive Programming).

The main idea behind the creation of NestJS was to resolve tackle one – but how crucial –  issue: that of structuring the app. Thus, it’s worth mentioning that while it shares the Angular architecture (along with dependency injection), it's not about the frontend anymore.

NestJS: fall in love with CLI and architecture

If you’re not sure whether you and NestJS will make a good match, start by checking out Nest CLI. It’s a command-line interface tool that not only automates the app initialization and the most tedious chores but also speeds up the entire web app development process. To instantly create a boilerplate, you simply run:

$ npm i -g @nestjs/cli
$ nest new project-name

Now, you’re only one step away from a ready-to-go app. This step is the answer to the following question: which package manager would I love to use. You can pick either NPM or Yarn. After selecting Yarn, the app with the first module, controller, and example service will be created and dependencies will be installed. One step that remains to be taken is to run the server. The whole structure will look like that:

1 .
2 ├── README.md
3 ├── nest-cli.json
4 ├── package.json
5 ├── src
6 │ ├── app.controller.spec.ts
7 │ ├── app.controller.ts
8 │ ├── app.module.ts
9 │ ├── app.service.ts
10 │ └── main.ts
11 ├── test
12 │ ├── app.e2e-spec.ts
13 │ └── jest-e2e.json
14 ├── tsconfig.build.json
15 ├── tsconfig.json
16 ├── tslint.json
17 └── yarn.lock

It’s a very tidy and convenient solution, especially if you’ve worked with Angular before. But even if you haven’t, don’t worry – it shouldn’t be a big deal to get used to it. The major advantage is that it contains all out of the box features you may need at the very beginning of the project.
Nest CLI helps in adding new services (providers) and controllers. What's more, it places them in a separate folder and connects to the relevant modules. If you want to generate a new service or controller, just run:

nest generate controller cats `# or use abbreviation: nest g c cats`
nest generate service cats `#or use abbreviation: nest g s cats`

The newly created controllers are placed inside the `src`, in separate, individually named folders:

src/cats
├── cats.controller.spec.ts
└── cats.controller.ts

But generating files is not the only thing CLI does. It also supports creating modules, workspaces, and libraries both in standard and monorepo mode. It has plenty of features, and each of them is really worth trying. To get to know all of them, simply dive into the documentation and take a look at some more great examples.

Decorators

You already know that NestJS is heavily based on TypeScript which is why the vast majority of its features are built around the ES2016 decorators.

Decorators are used everywhere in Nest JS. Just to give you an example: for marking modules, controllers, or services, use @Module(), @Controller('my-controller') and @Injectable(). For defining HTTP methods of given endpoint, on the other hand, you should pick: @Get(), @Post(), @Put(), @Delete(), etc.

Of course, you are free to create your own custom decorators as well. It will look as follows:

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

export const Cat = createParamDecorator((data, req) => {
return req.cat;
}); @Get()
async findOne(@Cat() cat: CatEntity) {
console.log({ cat });
}

Database connection

NestJS is database agnostic which means it can work with any database engine. As soon as you choose the relevant one, you just have to connect it in the same way as you would do when using Express or Fastify. If you decide on MongoDB, for example, you can use a dedicated @nestjs/mongoose package.

Another way to integrate both SQL and noSQL databases is to use the @nestjs/typeorm package. It’s not necessary to do it so, at the end of the day, you can use whatever database integration library, including Sequelize or Knex.js.

Benefits of using NestJS

I’ve talked about CLI, custom decorators, and database connection but so far I haven’t provided you with a straightforward answer to the most important question: why should you consider NestJS as the main framework for building your API?

First of all, NestJS gives a developer a head start. All you need to do to begin the development is to set up a new app and it's ready to go. Equally importantly, not only does this framework give a huge boost at the very beginning but it also facilitates further steps by defining the proper app architecture.

Then, NestJS is a really well designed and even better-crafted framework. As it uses modern solutions and technologies, you have every right to expect the applications created with NestJS to be maintainable and long-lasting. And even though the framework is written in JavaScript, it isn’t a cause of any limitations.

Finally, NestJS can use GraphQL, connect with the use of WebSockets, and even be used for building microservices. It can also work with Redis, RabbitMQ, gRPC and many more. At this point I believe that I don’t need to convince you anymore that NestJS has everything you need – just give it a chance and see for yourself how useful it can get!

Further reading

  1. NestJS documentation
  2. NestJS: beautifully crafted Node.js framework we’ve all been waiting for
  3. What is Nest js and should I use it?
  4. Nest js Tutorial Series — Part 1: Introduction & Setup
  5. Introduction to Nest.js for Angular Developers


Want to step up your JavaScript game and work on international projects? Check out our job offers!

Navigate the changing IT landscape

Some highlighted content that we want to draw attention to to link to our other resources. It usually contains a link .