NestJS: how and why to use it

In 2019, JavaScript has proved to be the most commonly used programming language for the seventh time in a row. The popularity of this technology is a fact and it shows in the sheer number of frameworks facilitating JavaScript development. Just to name a few, there are Angular, React, and Vue on the frontend as well as Express and Next on the backend. But today, I’m going to introduce yet another framework: NestJS.

In this article

Key Takeaways

  1. NestJS builds on Express or Fastify and Node.js, adding structure for scalable server-side applications.
  2. It combines object-oriented, functional, and reactive programming patterns, with full TypeScript support.
  3. The Nest CLI automates project setup and generates controllers, services, and modules in minutes.
  4. Decorators mark modules, controllers, and routes, and developers can also write custom ones.
  5. NestJS stays database agnostic and supports GraphQL, WebSockets, and microservices for broader architecture needs.

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!

FAQ

NestJS is an abstraction layer built by default on top of Express.js and Node.js, though it also supports other libraries such as Fastify. It combines Object Oriented Programming, Functional Programming, and Functional Reactive Programming principles. The framework uses progressive JavaScript and fully supports TypeScript.
Yes, NestJS shares Angular's architecture, including its approach to dependency injection. Despite this resemblance, NestJS is designed for server-side development rather than frontend work. Developers familiar with Angular may find the structure and CLI experience easier to adopt.
You generate a new project by installing the CLI globally and running a command to create a new app, which sets up a ready-to-go boilerplate. During this process, you choose between NPM or Yarn as your package manager. The CLI then creates the first module, controller, and example service, installs dependencies, and leaves you with a structured project ready to run.
Yes, Nest CLI can generate new controllers and services through simple generate commands or their shorthand equivalents. Generated files are placed inside the src directory in separate, individually named folders and connected to the relevant modules. Beyond controllers and services, the CLI also supports creating modules, workspaces, and libraries in both standard and monorepo modes.
NestJS is database agnostic, so it can work with any database engine. For MongoDB, developers can use the dedicated @nestjs/mongoose package, while the @nestjs/typeorm package supports integration with both SQL and NoSQL databases. Other integration libraries, such as Sequelize or Knex.js, can also be used instead.
Decorators are used throughout NestJS to mark modules, controllers, and services, and to define HTTP methods for endpoints. Examples include @Module(), @Controller(), and @Injectable() for structural elements, and @Get(), @Post(), @Put(), and @Delete() for HTTP methods. Developers can also create their own custom decorators using functions like createParamDecorator.
NestJS gives developers a head start by providing a ready app structure as soon as the project is set up, reducing manual configuration work. It also enforces a well-defined app architecture that supports maintainability as the project grows. Additionally, NestJS supports GraphQL, WebSockets, microservices, and integrations with tools like Redis, RabbitMQ, and gRPC, extending its usefulness beyond simple REST APIs.

Let's connect and build together