Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 96 ยท TypeScript in Practice

TypeScript with NestJS

Learn how NestJS uses TypeScript - modules, controllers, providers, dependency injection, decorators, DTO validation and testing - with runnable stand-ins that show how it works.

NestJS is a Node.js framework for building server applications, and it is the most TypeScript-centric of the popular ones. Where Express gives you a few functions and leaves the structure to you, Nest gives you an architecture: modules group features, controllers handle requests, providers (services) hold logic, and a dependency injection container wires them together. The vocabulary will feel familiar if you have used Angular, because Nest borrows its design.

Nest apps cannot run inside this site (they need the real @nestjs/* packages and a server), so the Nest code in this lesson is read-only. Instead, you will run a tiny stand-in that implements the same ideas (decorators, injection, validation) in plain TypeScript, so you can see exactly what Nest does for you. For the Express alternative see TypeScript with Frameworks, and for lighter typed servers see Typed Backends: Fastify, Hono and Koa.

Project setup

Nest uses legacy decorators plus decorator metadata, which the compiler must emit. These two options are required in tsconfig.json:

JSON
{
  "compilerOptions": {
    "module": "nodenext",
    "target": "ES2022",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strict": true,
    "outDir": "dist"
  }
}

experimentalDecorators turns on the decorator syntax that Nest was designed around (the older proposal, different from the standard decorators in Decorators). emitDecoratorMetadata makes the compiler record the types of constructor parameters at runtime. That is how Nest knows that a constructor taking CatsService needs a CatsService: it reads the type that TypeScript wrote down. Create a project with npm i -g @nestjs/cli then nest new my-app.

Because the types become runtime values, injected classes must be imported as values, not with import type. Using import type removes the class from the output, and injection fails with a confusing error.

The pieces of a Nest app

Provider: the service

A provider is any class marked @Injectable(). It holds business logic and can be injected into others.

TypeScript
// cats.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';

export interface Cat {
  id: number;
  name: string;
  age: number;
}

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

  findAll(): Cat[] {
    return this.cats;
  }

  findOne(id: number): Cat {
    const cat = this.cats.find((c) => c.id === id);
    if (!cat) {
      throw new NotFoundException(`Cat #${id} not found`);
    }
    return cat;
  }

  create(name: string, age: number): Cat {
    const cat = { id: this.cats.length + 1, name, age };
    this.cats.push(cat);
    return cat;
  }
}

Controller: routes

A controller maps HTTP requests to methods. Parameters are extracted with decorators, and a pipe such as ParseIntPipe converts the raw string to a number.

TypeScript
// cats.controller.ts
import { Body, Controller, Get, Param, ParseIntPipe, Post } from '@nestjs/common';
import { CatsService, type Cat } from './cats.service.js';
import { CreateCatDto } from './create-cat.dto.js';

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

  @Get()
  findAll(): Cat[] {
    return this.catsService.findAll();
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number): Cat {
    return this.catsService.findOne(id);
  }

  @Post()
  create(@Body() dto: CreateCatDto): Cat {
    return this.catsService.create(dto.name, dto.age);
  }
}

The parameter property private readonly catsService: CatsService is the whole injection story from your side: you ask for a type in the constructor, and Nest supplies an instance. Methods return plain values, which Nest serializes to JSON, so there is no res.json(...) call.

Module: the wiring

A module declares which controllers and providers belong together:

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

@Module({
  controllers: [CatsController],
  providers: [CatsService],
  exports: [CatsService], // let other modules inject it
})
export class CatsModule {}
TypeScript
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';

async function bootstrap(): Promise<void> {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
void bootstrap();

AppModule lists CatsModule under imports. A provider is only visible to the module that declares it, unless that module exports it and another module imports the module.

How decorators and injection work

Here is a miniature of the same architecture that you can run. It has @Injectable, @Controller, @Get, @Post, a container that builds objects and their dependencies, and exceptions that become HTTP statuses. The real Nest reads constructor types from metadata; the stand-in has none, so each controller lists its dependencies in a static inject array.

TypeScript A tiny Nest-style framework: decorators, modules and injection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice four things in the output. Routes were found by reading decorator-recorded data, not by a router you configured by hand. The controller never created its service: the container did, once, and reused it (the last line). An exception thrown deep in the service became a clean 404 for the client. And the body of a POST is unknown, so the controller had to check it by hand. Nest solves that last problem with DTOs.

DTOs and validation

A DTO (data transfer object) describes the shape of data coming in. In Nest a DTO is a class rather than an interface, because a class survives compilation, so the framework can see it at runtime. You decorate its fields with rules from the class-validator package:

TypeScript
// create-cat.dto.ts
import { IsInt, IsOptional, IsString, Length, Max, Min } from 'class-validator';

export class CreateCatDto {
  @IsString()
  @Length(1, 20)
  name!: string;

  @IsInt()
  @Min(0)
  @Max(30)
  age!: number;

  @IsOptional()
  @IsString()
  breed?: string;
}

(The ! definite assignment assertions are needed because strict mode demands initialized fields, and the framework fills them in; see Classes.) Then you switch validation on once, globally:

TypeScript
// main.ts
import { ValidationPipe } from '@nestjs/common';

app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true,            // strip properties that have no decorator
    forbidNonWhitelisted: false, // set true to reject them with a 400 instead
    transform: true,            // turn plain JSON into a CreateCatDto instance
  }),
);

Now every @Body() dto: CreateCatDto is checked before your method runs, and a bad request gets a 400 with a list of messages. This is the same job that Zod does in other stacks. The trade-off: with class-validator you write the type once as a class and the rules as decorators, so they can drift apart; with a schema library one schema gives both. Many Nest teams use nestjs-zod for that reason.

The stand-in below shows the idea in a form you can run: one schema supplies both the runtime check and the TypeScript type, and a whitelist drops unknown fields.

TypeScript DTO validation with a whitelist, like ValidationPipe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The isAdmin: true property on the second input never reached createCat. That is exactly what whitelist: true protects you from: mass assignment, where a client sneaks in fields such as isAdmin that your code later trusts.

Dependency injection in depth

Because injection is by type, swapping implementations is easy, and that makes testing simple. Providers can be written in a longer form when the token is not a class, for example a configuration value or an interface:

TypeScript
@Module({
  providers: [
    CatsService,
    { provide: 'API_KEY', useValue: process.env.API_KEY },
    { provide: Logger, useClass: process.env.NODE_ENV === 'test' ? SilentLogger : Logger },
    {
      provide: 'DB',
      useFactory: async (config: ConfigService) => connect(config.get('DB_URL')),
      inject: [ConfigService],
    },
  ],
})
export class AppModule {}
TypeScript
// injecting a non-class token
constructor(@Inject('API_KEY') private readonly apiKey: string) {}

Interfaces do not exist at runtime, so they cannot be injection tokens. Use an abstract class, a string, a Symbol or an InjectionToken-style constant instead. By default providers are singletons inside the app; request-scoped providers exist but cost performance.

Guards, pipes, interceptors and filters

Nest has four extension points that wrap a request, all of them classes you decorate or register:

Feature Runs Typical use
Guard (CanActivate) Before the handler Authentication and roles: return false to answer 403
Pipe (PipeTransform) On each argument Validation and conversion (ParseIntPipe, ValidationPipe)
Interceptor (NestInterceptor) Before and after Logging, caching, mapping the response
Exception filter (ExceptionFilter) When something throws Turn errors into consistent responses
TypeScript
@Injectable()
export class AdminGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<{ user?: { role: string } }>();
    return request.user?.role === 'admin';
  }
}

@Controller('admin')
@UseGuards(AdminGuard)
export class AdminController {
  @Get('stats')
  stats(): { visitors: number } {
    return { visitors: 1234 };
  }
}

Testing

The injection container makes unit tests short. Test.createTestingModule builds a module with only what you list, and you can replace any provider with a fake:

TypeScript
import { Test } from '@nestjs/testing';
import { describe, expect, it } from 'vitest';

describe('CatsController', () => {
  it('returns the cats from the service', async () => {
    const moduleRef = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [{ provide: CatsService, useValue: { findAll: () => [{ id: 1, name: 'Tom', age: 3 }] } }],
    }).compile();

    const controller = moduleRef.get(CatsController);
    expect(controller.findAll()).toEqual([{ id: 1, name: 'Tom', age: 3 }]);
  });
});

For whole-request tests, supertest sends real HTTP requests to app.getHttpServer(). See Testing TypeScript with Jest and Vitest.

Pitfalls to know

  • Forgetting the decorator. A class without @Injectable() cannot receive injections, and you get "Nest can't resolve dependencies of the X (?)".
  • A provider missing from the module produces the same error. Check providers, imports and exports.
  • Circular dependencies between two services need forwardRef; usually a redesign is better.
  • import type for an injected class erases the metadata Nest reads.
  • Interfaces as DTOs do nothing at runtime. Use classes (or a schema library) for anything you validate.
  • Decorators are legacy mode. Nest's decorators are not the standard ones; do not mix them in a file with TC39 decorators.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Nest require emitDecoratorMetadata?

    Interfaces are erased, but class types written as constructor parameters are emitted as metadata, which is how Nest knows what to inject.
  2. 2. Why are DTOs usually classes instead of interfaces in Nest?

    Interfaces disappear when compiled, so the framework cannot read rules from them.
  3. 3. What does whitelist: true on ValidationPipe do?

    Unknown fields are stripped, which prevents mass assignment of unexpected properties.
  4. 4. Which component runs before a handler and can reject a request with 403?

    Guards implement canActivate and decide whether the request may continue.
  5. 5. A controller fails with "Nest can't resolve dependencies". What is the first thing to check?

    Missing decorators or missing provider registration are the most common causes.

Summary

  • Nest organizes an app into modules, controllers and providers, wired by a dependency injection container.
  • It requires experimentalDecorators and emitDecoratorMetadata; constructor parameter types are the injection tokens.
  • Controllers use @Get, @Post, @Param, @Body and pipes like ParseIntPipe; thrown HttpExceptions become HTTP responses.
  • DTOs are classes with class-validator decorators (or a schema library); enable ValidationPipe with whitelist: true.
  • Guards, pipes, interceptors and filters wrap requests; providers can be replaced with fakes for testing.
  • Nest code on this page is read-only; the runnable stand-ins show the underlying mechanics in plain TypeScript.

Next: Typed Backends: Fastify, Hono and Koa