Skip to content
NestPath

Basic CRUD & Architecture

The mental shift from file-based routing to layered architecture: Modules, Controllers, Services, dependency injection, DTOs, and the complete request lifecycle — built into a working in-memory Tasks CRUD.

Alright, let's get you from Next.js brain to NestJS brain. Since you already know TypeScript, half the battle is won. The other half is unlearning the "everything is a function/file" mindset of Next.js and embracing the opinionated, class-based, decorator-heavy architecture NestJS enforces.


The Mental Shift First

In Next.js, you think in files and conventions — app/api/tasks/route.ts and you're done. NestJS thinks in architectural layers — every piece has a role, a decorator, and a place. It's closer to Angular than React. If that makes you uncomfortable, good — that discomfort means you're actually learning something structured instead of duct-taping API routes together.

Analogy

Next.js is a food truck: one person takes the order, cooks it, and hands it out the window — fast, flexible, and fine until the queue gets long. NestJS is a full restaurant: there's a waiter, a kitchen, a menu, and house rules about who does what. It feels like bureaucracy on day one, and it feels like sanity on day one hundred.


5 Core Concepts

1. Modules (@Module)

The organizing unit. Think of it as a container that groups related functionality. Every NestJS app has at least one — AppModule. A TasksModule would bundle together the controller, service, and anything else related to tasks.

ts
@Module({
  controllers: [TasksController],  // handles routes
  providers: [TasksService],       // business logic, injectable stuff
})
export class TasksModule {}

Next.js equivalent? There isn't one. Next.js doesn't care how you organize. NestJS forces you to. That's the point.

Analogy

A module is one restaurant in a chain: it has its own dining room, its own kitchen, and its own staff roster, all under one roof. TasksModule is "the tasks restaurant" — everything needed to serve tasks lives inside it, and the franchise headquarters (AppModule) just needs to know the restaurant exists.

2. Controllers (@Controller)

Route handlers. They receive requests and return responses. That's it. They should NOT contain business logic. If your controller has more than 5 lines of actual logic, you're doing it wrong.

ts
@Controller('tasks')  // base route: /tasks
export class TasksController {
  @Get()       // GET /tasks
  @Post()      // POST /tasks
  @Patch(':id') // PATCH /tasks/:id
  @Delete(':id') // DELETE /tasks/:id
}

Next.js equivalent? Your route.ts handler functions — but split into a class with decorators instead of export async function GET().

Analogy

The controller is the waiter. It greets the request, writes down exactly what was asked for, and carries it to the kitchen — but it never cooks. A waiter who disappears into the kitchen to fry the steak himself is what a fat controller looks like.

3. Services (@Injectable)

Business logic lives here. Database calls, computations, transformations — all in services. Controllers call services, never the other way around.

ts
@Injectable()
export class TasksService {
  // all your CRUD logic here
}

Why separate from controller? Because the same service can be injected into multiple controllers, other services, or even gateways. Reusability. Testability. If you've been shoving everything into API route handlers in Next.js — yeah, that doesn't scale. You know it.

Analogy

The service is the chef. Every real decision about the food — the recipe, the timing, the substitutions — happens at the stove, not at the table. And because the chef doesn't care which waiter brought the order, the same chef can cook for the dining room, the takeaway counter, and the delivery app.

4. Dependency Injection (DI)

This is the magic glue. Instead of importing and instantiating classes manually, you declare what you need in the constructor, and NestJS hands it to you.

ts
@Controller('tasks')
export class TasksController {
  // NestJS sees this, finds TasksService in the module's providers,
  // creates an instance (singleton by default), and injects it.
  constructor(private tasksService: TasksService) {}
}

You never write new TasksService(). The framework manages the lifecycle. This is why everything is registered in Modules — so the DI container knows what exists.

Next.js equivalent? You don't have one. You just import and call functions. Which works until you need to mock things in tests or swap implementations. Then you cry.

Analogy

Dependency injection is the restaurant's staffing system. The waiter never hires his own chef — he just says "I need someone at the grill tonight" and management assigns one from the roster (the module's providers). That's also why swapping the real chef for a stand-in during a health inspection (a mock in a test) requires changing nothing about how the waiter works.

5. DTOs (Data Transfer Objects)

Shape definitions for incoming/outgoing data. They're plain classes (not interfaces, because interfaces disappear at runtime and NestJS needs runtime metadata for validation pipes later).

ts
export class CreateTaskDto {
  title: string;
  description: string;
}

"But that's just a type?" — For now, yes. But when you add class-validator decorators later, these DTOs become your validation layer too. That's why NestJS uses classes over interfaces for DTOs. Interfaces can't carry decorators.

Interfaces are still used — but for your internal data models/entities, not for request shaping.

Analogy

A DTO is the printed order pad. It defines exactly which boxes a customer's order can have — dish, size, notes — so the kitchen never receives a napkin with scribbles on it. Right now the pad is just a suggested layout; in the next module the waiter starts refusing any order that doesn't fill the boxes correctly.


The Complete Request Lifecycle

This is what happens when a request hits your NestJS server, in exact order:

Incoming HTTP Request
1
MIDDLEWARE

like Express middleware — logging, cors, body parsing. Runs before the route is matched.

2
GUARDS

authentication/authorization — "can this user access this?" Returns true/false — if false, the request is rejected.

3
INTERCEPTORS (pre-controller)

transform the request before it hits the controller. Can also wrap the response stream — runs again after the response.

4
PIPES

transform/validate the incoming data. This is where DTO validation happens with class-validator — ParseIntPipe, ValidationPipe, etc.

5
CONTROLLER METHOD

route handler — delegates to the service

6
SERVICE
business logic, data access
7
CONTROLLER RETURNS
response object/data
8
INTERCEPTORS (post-controller)

transform the response — serialization, wrapping, caching

9
EXCEPTION FILTERS

catch any errors thrown anywhere above and format error responses

HTTP Response sent to client
⚡ Quick lookup — the lifecycle in one line
text
Request -> Middleware -> Guards -> Interceptors(pre) -> Pipes
        -> Controller -> Service -> Interceptors(post)
        -> Exception Filters (if error) -> Response

Key insight: Interceptors run twice — once before the controller, once after. They wrap the entire handler execution. Exception filters are the safety net that catches anything that went wrong at any stage.

Analogy

Follow one customer through the restaurant: the front door and coat check (middleware), the host checking the reservation list (guards), the maître d' walking you in and later walking your plate out (interceptors, both directions), the waiter checking your order form is filled in properly (pipes), the waiter taking it to the chef (controller to service), and — if anything goes wrong anywhere — the manager who steps in with one consistent apology script (exception filters).

For your simple CRUD right now, you'll only touch Controller → Service. Everything else layers on top as you advance.


CRUD Example — Tasks (In-Memory, No Frills)

Here's the complete picture. File structure first:

src
app.module.ts
main.ts
tasks
tasks.module.ts
tasks.controller.ts
tasks.service.ts
dto
create-task.dto.ts
update-task.dto.ts
interfaces
task.interface.ts

task.interface.ts — Your data shape

ts
export interface Task {
  id: number;
  title: string;
  description: string;
  done: boolean;
}

create-task.dto.ts — What the client sends to create

ts
export class CreateTaskDto {
  title: string;
  description: string;
}

update-task.dto.ts — What the client sends to update

ts
export class UpdateTaskDto {
  title?: string;
  description?: string;
  done?: boolean;
}

tasks.service.ts — All logic lives here

ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { Task } from './interfaces/task.interface';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';

@Injectable()
export class TasksService {
  private tasks: Task[] = [];
  private idCounter = 1;

  findAll(): Task[] {
    return this.tasks;
  }

  findOne(id: number): Task {
    const task = this.tasks.find((t) => t.id === id);
    if (!task) {
      throw new NotFoundException(`Task with id ${id} not found`);
    }
    return task;
  }

  create(createTaskDto: CreateTaskDto): Task {
    const newTask: Task = {
      id: this.idCounter++,
      title: createTaskDto.title,
      description: createTaskDto.description,
      done: false,
    };
    this.tasks.push(newTask);
    return newTask;
  }

  update(id: number, updateTaskDto: UpdateTaskDto): Task {
    const task = this.findOne(id);
    Object.assign(task, updateTaskDto);
    return task;
  }

  remove(id: number): void {
    const index = this.tasks.findIndex((t) => t.id === id);
    if (index === -1) {
      throw new NotFoundException(`Task with id ${id} not found`);
    }
    this.tasks.splice(index, 1);
  }
}

tasks.controller.ts — Thin, delegates everything

ts
import {
  Controller, Get, Post, Patch, Delete,
  Param, Body, ParseIntPipe,
} from '@nestjs/common';
import { TasksService } from './tasks.service';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';
import { Task } from './interfaces/task.interface';

@Controller('tasks')
export class TasksController {
  constructor(private readonly tasksService: TasksService) {}

  @Get()
  findAll(): Task[] {
    return this.tasksService.findAll();
  }

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

  @Post()
  create(@Body() createTaskDto: CreateTaskDto): Task {
    return this.tasksService.create(createTaskDto);
  }

  @Patch(':id')
  update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateTaskDto: UpdateTaskDto,
  ): Task {
    return this.tasksService.update(id, updateTaskDto);
  }

  @Delete(':id')
  remove(@Param('id', ParseIntPipe) id: number): void {
    this.tasksService.remove(id);
  }
}

Note on ParseIntPipe: Yeah, I know you said no validation pipes — but this isn't validation. URL params come as strings. ParseIntPipe just converts "1" to 1. Without it, id would be a string and find() would never match. This is a transformation pipe, not a validation pipe. You'd have the same problem in Next.js doing parseInt(params.id).

Status codes: POST is 201, but DELETE returns 200

NestJS sets POST to 201 Created automatically — that's why you don't see a status set anywhere. But a void return (like remove()) still sends 200 OK with an empty body, when a delete is conventionally a 204 No Content. If you want the conventional code, say so explicitly:

ts
import { HttpCode, HttpStatus } from '@nestjs/common';

@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT) // 204
remove(@Param('id', ParseIntPipe) id: number): void {
  this.tasksService.remove(id);
}

Keep it 200 for now if you prefer — just know the default, and that this choice comes back in Module 04 when the response interceptor has to decide what to wrap for an empty body.

tasks.module.ts — Wires it together

ts
import { Module } from '@nestjs/common';
import { TasksController } from './tasks.controller';
import { TasksService } from './tasks.service';

@Module({
  controllers: [TasksController],
  providers: [TasksService],
})
export class TasksModule {}

app.module.ts — Root module imports TasksModule

ts
import { Module } from '@nestjs/common';
import { TasksModule } from './tasks/tasks.module';

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

main.ts — Bootstrap

ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

How a DTO Actually Works in the Flow

Let's trace POST /tasks with body { "title": "Learn NestJS", "description": "CRUD first" }:

Client sends POST /tasks with JSON body
NestJS matches route → TasksController.create()
@Body() decorator extracts request body
Body is mapped to CreateTaskDto instance

right now it's just a plain object cast — no runtime validation yet. When you add class-validator + ValidationPipe later, this is where it validates the body against the DTO decorators and throws 400 if invalid.

Controller receives typed createTaskDto, passes to service
Service uses the DTO data, creates Task, returns it
Controller returns the Task object
NestJS serializes it to JSON, sends 201 response

The brutal truth about DTOs without validation: Right now, your DTOs are decorative. Someone could send { "garbage": true } and it would happily reach your service with title and description as undefined. The DTO class exists but NestJS doesn't enforce it at runtime without ValidationPipe + class-validator. You'll add that next — but first, understand the flow without magic.


Quick Start Commands

bash
npm i -g @nestjs/cli
nest new my-task-app
cd my-task-app
nest generate module tasks
nest generate controller tasks
nest generate service tasks
# for creating all at once
nest g resource tasks
# then create the dto/ and interfaces/ folders manually

The CLI generates boilerplate and auto-updates module imports. Use it.


That's your foundation. You now understand the architecture, the lifecycle, and have a working CRUD. When you're ready, the next logical steps are: ValidationPipe + class-validator on DTOs, then Exception Filters, then Interceptors for response shaping. Sequential, like you wanted.