Skip to the content

Lesson 207 of 296

Modules, controllers and providers

What you will learn

  • What NestJS is and why teams choose it
  • Decorators: the syntax NestJS is built on
  • Controllers: handling requests
  • Providers and services: business logic
  • Modules: organising the app
  • Starting an application
  • The folder structure of a feature
On this page

What is NestJS?

NestJS is a framework for building server-side applications with TypeScript. It runs on top of an HTTP library: Express by default, or Fastify for more speed. Express (Part 15) gives you freedom but no structure; in a big team, every project ends up organised differently. NestJS gives every project the same architecture, inspired by Angular and by Java's Spring:

  • Modules group features.
  • Controllers handle HTTP requests.
  • Providers (services, repositories) hold the logic.
  • Dependency injection connects them (Lesson 208).
  • A request pipeline of guards, pipes, interceptors and filters handles auth, validation, logging and errors (Lesson 209).

It also has official packages for configuration, databases (TypeORM, Prisma, Mongoose), GraphQL, WebSockets, queues (BullMQ), scheduling, microservices, OpenAPI documentation and more.

Start a project: npm i -g @nestjs/cli then nest new my-api. In NestJS 12, new projects are ES modules and use Vitest for tests by default (CommonJS projects keep Jest). Generate code with nest generate resource orders (nest g res orders), which creates a module, controller, service, DTOs and tests.

Decorators

NestJS uses decorators: functions written with @ above a class, method or parameter, which attach metadata (extra information) that the framework reads later (Lesson 113 introduced them).

@Controller("orders")          this class handles /orders
export class OrdersController {
  @Get(":id")                  this method handles GET /orders/:id
  findOne(@Param("id") id: string) {}     put the "id" route parameter here
}

You do not need to write decorators yourself in most jobs; you need to read and use them.

Controllers

A controller receives requests for a route and returns responses. It should be thin: read input, call a service, return the result. No business logic, no database code.

First, the shape of the request body, in orders.dto.ts (validation is added in Lesson 210):

TypeScript
export type CreateOrderDto = { productId: string; quantity: number };

Then the controller, in orders.controller.ts:

TypeScript
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Query } from "@nestjs/common";
import { OrdersService } from "./orders.service.js";
import type { CreateOrderDto } from "./orders.dto.js";

@Controller("orders")
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Get()
  findAll(@Query("status") status?: string) {
    return this.ordersService.findAll(status);
  }

  @Get(":id")
  findOne(@Param("id") id: string) {
    return this.ordersService.findOne(id);
  }

  @Post()
  create(@Body() body: CreateOrderDto) {
    return this.ordersService.create(body);
  }

  @Delete(":id")
  @HttpCode(204)
  remove(@Param("id") id: string) {
    this.ordersService.remove(id);
  }
}
DecoratorPurpose
@Controller("orders")Route prefix for all methods
@Get(), @Post(), @Put(), @Patch(), @Delete()HTTP method and sub-path
@Param("id")A route parameter
@Query("status")A query string value
@Body()The parsed request body
@Headers("authorization")A request header
@Req(), @Res()The raw request and response (avoid @Res(): it switches off Nest's automatic response handling)
@HttpCode(204)Change the default status (POST defaults to 201, others to 200)

Whatever the method returns (an object, an array, or a Promise of one) is sent as JSON automatically.

Providers and services

A provider is any class that Nest can create and inject. The most common provider is a service, which holds the business logic:

TypeScript
import { Injectable, NotFoundException } from "@nestjs/common";
import { randomUUID } from "node:crypto";
import type { CreateOrderDto } from "./orders.dto.js";

export type Order = { id: string; productId: string; quantity: number; status: "pending" | "paid" };

@Injectable()
export class OrdersService {
  private readonly orders = new Map<string, Order>();

  findAll(status?: string): Order[] {
    const all = [...this.orders.values()];
    return status ? all.filter((o) => o.status === status) : all;
  }

  findOne(id: string): Order {
    const order = this.orders.get(id);
    if (!order) throw new NotFoundException(`Order ${id} not found`);
    return order;
  }

  create(dto: CreateOrderDto): Order {
    const order: Order = { id: randomUUID(), productId: dto.productId, quantity: dto.quantity, status: "pending" };
    this.orders.set(order.id, order);
    return order;
  }

  remove(id: string): void {
    this.findOne(id);
    this.orders.delete(id);
  }
}
  • @Injectable() marks the class as a provider that can receive and be injected.
  • Built-in HTTP exceptions (NotFoundException, BadRequestException, ForbiddenException, ConflictException, UnauthorizedException...) are turned into the right status code and JSON body automatically. NestJS 12 also lets you add a stable errorCode: new BadRequestException("Password is too weak", { errorCode: "WEAK_PASSWORD" }).
  • In real projects the data comes from a database through a repository (Prisma, Lesson 230), not a Map.

Modules

A module groups a controller, its providers and related code into one feature:

TypeScript
import { Module } from "@nestjs/common";
import { OrdersController } from "./orders.controller.js";
import { OrdersService } from "./orders.service.js";

@Module({
  controllers: [OrdersController],
  providers: [OrdersService],
  exports: [OrdersService]
})
export class OrdersModule {}
PropertyMeaning
controllersControllers in this module
providersProviders created by this module
importsOther modules whose exported providers this module needs
exportsProviders this module makes available to modules that import it

Providers are private to their module unless exported. If InvoicesModule needs OrdersService, it must imports: [OrdersModule], and OrdersModule must export OrdersService. This keeps boundaries clear and is a common source of "Nest can't resolve dependencies" errors.

The root module imports the feature modules:

TypeScript
@Module({ imports: [OrdersModule] })
export class AppModule {}

Starting the application

TypeScript
import "reflect-metadata";
import { NestFactory } from "@nestjs/core";

export async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableShutdownHooks();
  await app.listen(process.env.PORT ?? 3000);
  return app;
}

enableShutdownHooks() makes Nest listen for SIGTERM and run shutdown hooks (Lesson 193). In NestJS 12, the Express adapter also drains in-flight requests during shutdown.

Folder structure

Organise by feature, not by type:

src/
  main.ts
  app.module.ts
  orders/
    orders.module.ts
    orders.controller.ts
    orders.service.ts
    orders.dto.ts
    orders.controller.spec.ts
  users/
    users.module.ts
    ...
  common/
    guards/  interceptors/  filters/

How to say it in an interview

"NestJS is a TypeScript framework on top of Express or Fastify that gives back ends a consistent architecture. Controllers are thin and map routes to service calls using decorators like Get, Post, Param and Body; providers such as services hold business logic and are marked Injectable; modules group a feature's controllers and providers, keep providers private unless exported, and import other modules to use their exports. Nest turns returned values into JSON and built-in HTTP exceptions into proper status codes. I organise code by feature, with one module per domain area."

Key words

WordMeaning
NestJSA structured TypeScript framework for Node.js back ends
Decorator@Something that attaches metadata to a class, method or parameter
ControllerHandles requests for a route
ProviderA class Nest can create and inject
ServiceA provider holding business logic
ModuleA group of controllers and providers forming a feature
exports / importsHow modules share providers

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.