NestJS fundamentals

Intermediate · 9 min

NestJS modules, controllers, providers and dependency injection, plus pipes and guards, and an honest look at when the framework is worth its weight.

Before thisExpress routing and middlewareFastify fundamentals

Tech Vision · 9 min

NestJS fundamentals

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Tech VisionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • NestJS is a TypeScript framework that adds structure on top of Express or Fastify: modules group features, controllers handle routes, providers hold logic, and a dependency injection container wires them together.
  • Classes marked `@Injectable()` are providers. A class declares what it needs in its constructor, and Nest supplies the instances, which makes services easy to replace in tests.
  • Decorators such as `@Controller`, `@Get`, `@Param` and `@Body` attach routing metadata to classes and methods. The request pipeline around them is middleware, guards, interceptors, pipes, then filters for exceptions.
  • Pipes validate or transform inputs (`ParseIntPipe`, custom pipes), guards decide whether a request may proceed (a failed guard returns 403), and thrown `HttpException` subclasses become JSON error responses.
  • Nest pays off on large teams and long-lived codebases that benefit from enforced conventions. For a small service, it is more ceremony than Express or Fastify.

What problem it targets

Express and Fastify leave your project’s shape up to you. In a team of ten, that freedom becomes ten shapes. NestJS answers with a fixed architecture, borrowed from Angular: code is split into modules, each with controllers (HTTP entry points) and providers (logic), connected by dependency injection. It is written in TypeScript and runs on top of Express by default, or Fastify as an option. It trades flexibility for consistency.

Modules, controllers, providers

import { Module, Controller, Get, Post, Param, Body, Injectable, NotFoundException, ParseIntPipe } from '@nestjs/common';

@Injectable()
class CatsService {
  private cats = [{ id: 1, name: 'Tom' }];
  findOne(id: number) {
    const cat = this.cats.find((c) => c.id === id);
    if (!cat) throw new NotFoundException(`Cat ${id} not found`);
    return cat;
  }
  create(name: string) { const cat = { id: this.cats.length + 1, name }; this.cats.push(cat); return cat; }
}

@Controller('cats')
class CatsController {
  constructor(private readonly cats: CatsService) {}   // injected by type
  @Get(':id') one(@Param('id', ParseIntPipe) id: number) { return this.cats.findOne(id); }
}

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

@Module({ imports: [CatsModule] })
class AppModule {}
  • A provider is a class marked @Injectable(). Services, repositories and factories are providers.
  • A controller maps routes to methods. @Controller('cats') plus @Get(':id') is GET /cats/:id. Returning a value sends it as JSON; throwing NotFoundException sends a 404 body.
  • A module declares which controllers and providers belong together and which other modules it imports. AppModule is the root.

The container is where the “magic” happens. CatsController asks for CatsService in its constructor, and Nest reads the constructor’s type through TypeScript decorator metadata, creates one CatsService (singleton by default), and passes it in. You never call new CatsService().

Start it with const app = await NestFactory.create(AppModule); await app.listen(3000);. The decorators here are the classic experimental ones, so the project needs experimentalDecorators and emitDecoratorMetadata enabled in tsconfig.json, as the Nest CLI sets up for you. See decorators in TypeScript for how they work.

Pipes, guards and the request pipeline

A request passes through a fixed sequence: middleware, guards, interceptors, pipes, the handler, then interceptors again on the way out, with exception filters catching errors. Two parts you meet first:

import { PipeTransform, BadRequestException, CanActivate, ExecutionContext, UseGuards, Injectable } from '@nestjs/common';

class NamePipe implements PipeTransform {
  transform(value: any) {
    if (typeof value?.name !== 'string' || !value.name.trim()) throw new BadRequestException('name is required');
    return { name: value.name.trim() };
  }
}

@Injectable()
class ApiKeyGuard implements CanActivate {
  canActivate(ctx: ExecutionContext) {
    return ctx.switchToHttp().getRequest().headers['x-api-key'] === 'secret';
  }
}

// inside CatsController:
// @Post() @UseGuards(ApiKeyGuard) create(@Body(new NamePipe()) body: { name: string }) { ... }

I compiled this with TypeScript 5.9 and ran it on Node 26 against NestJS 12.6, with these results:

  • GET /cats/abc: 400 Validation failed (numeric string is expected) from ParseIntPipe.
  • GET /cats/9: 404 Cat 9 not found.
  • POST /cats without the key: 403 Forbidden resource, from the guard.
  • POST /cats with the key and {"name":" Felix "}: 201 {"id":2,"name":"Felix"}, trimmed by the pipe.
  • With the key and {}: 400 name is required.

In real projects, pipes usually run schema validation: Nest’s ValidationPipe with class-validator, or a Zod-based pipe. Guards usually check JWTs or roles, the same job as the Express auth middleware.

When it is worth it

Nest earns its place when many developers work on a large, long-lived service. Conventions are enforced by the framework, testing with injected fakes is straightforward, and the ecosystem has first-party modules for configuration, queues, GraphQL, microservices and OpenAPI. It costs you a bigger concept surface, decorator metadata, and a TypeScript build step. A service with a handful of routes, or a team that already has strong conventions, is simpler in Express or Fastify. A reasonable path is to start small and move to Nest when the structure starts to hurt.

What the video covers

Tech Vision’s “Every NestJS Concept Explained in 9 Minutes” (July 2024) has a chapter for each concept: application (0:00), modules (1:55), decorators (2:33), controllers (3:33), providers (4:13), middlewares (4:58), guards (5:38), interceptors (6:22), pipes (6:48) and filters (8:10). That is a complete tour of the request pipeline in short chapters, which is why it was chosen over a longer build-along. The description also promotes the creator’s paid course. It dates from NestJS 10; version 12 is current, and the core concepts here are unchanged in the run above. I could not read a transcript, so I can’t say how much of the dependency injection mechanism it explains; the type-metadata account is this page’s. The creator’s 25-minute crash course is under “go deeper”.

Where this fits

Nest builds on the same Express routing and middleware model, with structure on top. It leans on TypeScript decorators and the general idea of dependency injection. Last in this group: real-time with WebSockets.

Check yourself

  1. 01What problem does dependency injection solve in a Nest controller?

    The controller declares `constructor(private cats: CatsService)` and Nest creates and supplies the instance, so the controller does not construct its own dependencies. You can swap the service for a fake in tests, and services shared across controllers are instantiated once per module scope.

  2. 02A request to `GET /cats/abc` hits `@Get(':id') one(@Param('id', ParseIntPipe) id: number)`. What happens?

    `ParseIntPipe` fails to convert `'abc'` and throws a `BadRequestException`, so the client receives a 400 with the message 'Validation failed (numeric string is expected)' and the handler never runs. This was the actual response in a test run.

  3. 03Where in the pipeline does a guard run, and what does it return to stop a request?

    Guards run after middleware and before interceptors and pipes. A guard's `canActivate` returns true to continue or false (or throws) to stop; returning false produces a 403 Forbidden response. Use them for authorization, like checking an API key or role.

  4. 04Why might you not choose NestJS for a small internal service?

    It brings a lot of structure (modules, decorators, DI metadata, a build step for TypeScript decorators) that pays back only as the codebase and team grow. For a few endpoints, plain Express or Fastify is less code and fewer concepts, and you can adopt structure later.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark