NestJS 101

NestJS 101

An Introduction to Building Scalable and Maintainable Server-Side Applications

What is NestJS?

NestJS is a progressive Node.js framework for building efficient, reliable, scalable server-side applications. It leverages TypeScript, a strongly typed language that builds on JavaScript, which means you can write cleaner and more maintainable code. NestJS is heavily inspired by Angular architecture.

Origin of NestJS

NestJS was created by Kamil Myśliwiec in 2017. The framework was designed to address the limitations and challenges of building complex server-side applications with existing Node.js frameworks like Express. NestJS aims to provide a structured and modular approach to server-side development, leveraging TypeScript to enhance developer productivity and code quality.

Why NestJS?

  • TypeScript Out of the Box support

  • Modular Architecture: NestJS promotes a modular architecture, making it easy to manage and scale applications.

  • Built-in Features: It comes with powerful built-in features like dependency injection, middleware, guards, etc.

  • Community and Ecosystem: NestJS has a strong community and a growing ecosystem of plugins and tools.

Pros and Cons of NestJS

Pros

  1. TypeScript Support:

    • Enhanced developer experience with strong typing.

    • Easier to maintain and refactor code.

  2. Modular Architecture:

    • Promotes clean and maintainable code structure.

    • Simplifies the management of complex applications.

  3. Dependency Injection:

    • Built-in dependency injection improves code reusability and testability.
  4. Built-in Features:

    • Robust features like middleware, guards, and interceptors are out of the box.
  5. Consistency:

    • Inspired by Angular, provides a consistent and familiar structure for those with Angular experience.
  6. Scalability:

    • Designed for building large-scale applications with ease.

Cons

  1. Learning Curve:

    • Steeper learning curve, especially for developers not familiar with TypeScript or Angular.
  2. Overhead:

    • May introduce unnecessary overhead for small or simple applications.
  3. Complexity:

    • The extensive feature set and modularity can add complexity to simple projects.

NestJS vs. Express

Similarities

  • Node.js Based: Both frameworks are built on Node.js and use its core features.

  • Middleware: Both support middleware for handling requests and responses.

Differences

  1. Architecture:

    • Express: Minimalistic and unopinionated. It provides basic tools for building server-side applications but leaves the architecture and structure up to the developer.

    • NestJS: Opinionated and structured, promoting a modular and organized approach similar to Angular.

  2. TypeScript Support:

    • Express: Does not come with TypeScript support out of the box, but can be used with it.

    • NestJS: TypeScript is a first-class citizen, and the framework is designed with TypeScript in mind.

  3. Features:

    • Express: Lightweight and minimal. Requires additional libraries for advanced features.

    • NestJS: Rich feature set with built-in support for dependency injection, guards, interceptors, and more.

  4. Learning Curve:

    • Express: Easier to get started with due to its simplicity.

    • NestJS: Steeper learning curve

Getting Started with NestJS

Prerequisites

  • Node.js and npm are installed on your machine.

  • Basic understanding of JavaScript/TypeScript.

Step 1: Install NestJS CLI

First, we need to install the NestJS CLI to generate and manage our project.

npm install -g @nestjs/cli

Step 2: Create a New Project

Create a new NestJS project using the CLI.

nest new project-name

This command will prompt you to choose a package manager (npm or yarn) and then set up your project.

Step 3: Project Structure

After creating a new project, you'll see the following folder structure:

project-name/
├── src/
│   ├── app.controller.ts
│   ├── app.controller.spec.ts
│   ├── app.module.ts
│   ├── app.service.ts
│   ├── main.ts
├── test/
├── node_modules/
├── package.json
├── tsconfig.json
└── nest-cli.json

Step 4: Understanding the Basics

  • app.module.ts: The root module of your application. It's where you define your application's structure and dependencies.

  • app.controller.ts: Defines the routes and handles incoming requests.

  • app.service.ts: Contains the business logic of your application.

  • main.ts: The entry point of the application, where the application is bootstrapped.

Step 5: Creating a Simple Module, Controller, and Service

Let's create a new module, controller, and service to understand the basics.

nest generate module cats
nest generate controller cats
nest generate service cats

This will create three new files:

src/
├── cats/
│   ├── cats.module.ts
│   ├── cats.controller.ts
│   ├── cats.service.ts

Step 6: Defining the Cats Service

Open cats.service.ts and add some basic functionality:

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

@Injectable()
export class CatsService {
  private readonly cats = [];

  create(cat) {
    this.cats.push(cat);
  }

  findAll() {
    return this.cats;
  }
}

Step 7: Creating the Cats Controller

Open cats.controller.ts and use the service we just created:

import { Controller, Get, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()
  create(@Body() cat) {
    this.catsService.create(cat);
  }

  @Get()
  findAll() {
    return this.catsService.findAll();
  }
}

Step 8: Updating the Cats Module

Ensure the service and controller are included in the module. Open cats.module.ts:

import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}

Step 9: Importing the Cats Module in the App Module

Finally, import the CatsModule in your app.module.ts:

import { Module } from '@nestjs/common';
import { CatsModule } from './cats/cats.module';

@Module({
  imports: [CatsModule],
})
export class AppModule {}

Step 10: Running the Application

Start your NestJS application:

npm run start

Your NestJS server should now be running. You can test the endpoints using a tool like Postman or cURL.

  • POST /cats: Create a new cat.

  • GET /cats: Retrieve all cats.

curl -X POST http://localhost:3000/cats \
     -H "Content-Type: application/json" \
     -d '{
           "name": "Whiskers",
           "age": 2,
           "breed": "Siamese"
         }'

curl -X GET http://localhost:3000/cats

Conclusion

In this introductory guide, we've covered the basics of setting up a NestJS application, understanding its structure, and creating simple modules, controllers, and services. NestJS provides a robust framework for building scalable and maintainable server-side applications, leveraging the power of TypeScript and the modularity concept

Did you find this article valuable?

Support Nicanor Talks Web by becoming a sponsor. Any amount is appreciated!