Polski

Tutorial · NestJS · Hexagonal Architecture

NestJS 11 in practice – modules, DI, validation, Mongoose, queues and hexagonal architecture

We move the pierogi shop's order API to NestJS 11 – modules and dependency injection, controllers and DTOs with class-validator, pipes, guards, interceptors and exception filters, Zod-validated configuration, Mongoose 9, ports and adapters, scheduled jobs and a BullMQ queue, plus tests with swapped dependencies.

By · · 24 min read

Express gives you freedom, NestJS gives you conventions. As an API grows and several people work on it, freedom turns into ten different ways of doing the same thing. NestJS enforces modules, dependency injection (DI) and a clear request lifecycle, while Express 5 still runs underneath. In this tutorial we move the pierogi shop's order API from the Express tutorial to NestJS 11 and arrange it so that the database and the queue are swappable adapters.

Prerequisites: Node.js 22+ (24 recommended), Docker (for MongoDB and Redis), TypeScript with decorators at the level of "I have seen @Something() above a class". Reading the Express tutorial helps – comparing the two approaches is instructive.

11
NestJS version – Express 5 underneath
2
ports – order repository and kitchen tickets
6
request pipeline stages – middleware, guard, interceptor, pipe, handler, filter
26
files in the ZIP – with docker-compose and tests

Step 1. The project and local infrastructure

You can scaffold the skeleton with npx @nestjs/cli@11 new pierogi-nest, but below is a complete, trimmed-down configuration – without ESLint and Prettier, to keep the focus on NestJS.

npm install
cp .env.example .env
docker compose up -d      # MongoDB 8 + Redis 8
npm run start:dev

Project configuration

package.json
{
  "name": "pierogi-nest",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "build": "nest build",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:prod": "node dist/main",
    "typecheck": "tsc --noEmit",
    "test": "jest"
  },
  "dependencies": {
    "@nestjs/bullmq": "^11.0.5",
    "@nestjs/common": "^11.2.12",
    "@nestjs/config": "^4.0.4",
    "@nestjs/core": "^11.2.12",
    "@nestjs/mongoose": "^11.0.4",
    "@nestjs/platform-express": "^11.2.12",
    "@nestjs/schedule": "^6.1.3",
    "@nestjs/throttler": "^6.8.0",
    "bullmq": "^6.7.10",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.15.1",
    "helmet": "^8.3.0",
    "ioredis": "^6.1.0",
    "mongoose": "^9.13.1",
    "reflect-metadata": "^0.2.2",
    "rxjs": "^7.8.2",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@nestjs/cli": "^11.0.24",
    "@nestjs/schematics": "^11.1.0",
    "@nestjs/testing": "^11.2.12",
    "@types/express": "^5.0.6",
    "@types/jest": "^30.0.0",
    "@types/node": "^24.19.4",
    "jest": "^30.5.2",
    "ts-jest": "^29.4.15",
    "typescript": "~5.9.3"
  },
  "jest": {
    "moduleFileExtensions": ["js", "json", "ts"],
    "testRegex": ".*\\.spec\\.ts$",
    "transform": { "^.+\\.(t|j)s$": "ts-jest" },
    "testEnvironment": "node"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "target": "ES2023",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "strict": true,
    "strictPropertyInitialization": false,
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "incremental": true,
    "types": ["node", "jest"]
  },
  "include": ["src", "test"]
}
tsconfig.build.json
{
  "extends": "./tsconfig.json",
  "include": ["src"]
}
nest-cli.json
{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": { "deleteOutDir": true }
}
.env.example
NODE_ENV=development
PORT=3000
MONGODB_URI=mongodb://localhost:27017/pierogi
REDIS_URL=redis://localhost:6379
CORS_ORIGINS=http://localhost:5173
# openssl rand -hex 32
KITCHEN_API_KEY=replace-with-a-long-random-secret-of-32-chars
docker-compose.yml
# Local infrastructure only – the app itself runs with `npm run start:dev`.
services:
  mongo:
    image: mongo:8
    ports: ["27017:27017"]
    volumes: [mongo-data:/data/db]
  redis:
    image: redis:8-alpine
    ports: ["6379:6379"]
volumes:
  mongo-data:

Two tsconfig.json options are mandatory for Nest: experimentalDecorators (the old, "legacy" decorators) and emitDecoratorMetadata – the compiler records constructor parameter types, and the DI container reads them to know what to inject. TypeScript stays on 5.9: Nest CLI 11 uses the compiler API, which TypeScript 7 no longer exposes.

Step 2. Configuration and the root module

ConfigModule.forRoot() reads .env and environment variables, and the validate option lets you plug in any validator. We use the same Zod schema as in Express – the app will not start with a missing MONGODB_URI or a kitchen key that is too short.

Configuration, AppModule and bootstrap

src/config/env.ts
import { z } from 'zod';

const EnvSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
  MONGODB_URI: z.string().startsWith('mongodb'),
  REDIS_URL: z.string().startsWith('redis').default('redis://localhost:6379'),
  CORS_ORIGINS: z.string().default('http://localhost:5173'),
  // Shared secret for the kitchen tablet – long and random.
  KITCHEN_API_KEY: z.string().min(32),
});

export type Env = z.infer<typeof EnvSchema>;

// Plugged into ConfigModule: the app refuses to start with a broken config.
export function validateEnv(raw: Record<string, unknown>): Env {
  const result = EnvSchema.safeParse(raw);
  if (!result.success) {
    throw new Error(`Invalid environment configuration:\n${z.prettifyError(result.error)}`);
  }
  return result.data;
}
src/app.module.ts
import { BullModule } from '@nestjs/bullmq';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { MongooseModule } from '@nestjs/mongoose';
import { ScheduleModule } from '@nestjs/schedule';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { DomainExceptionFilter } from './common/filters/domain-exception.filter';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { Env, validateEnv } from './config/env';
import { OrdersModule } from './orders/orders.module';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true, cache: true, validate: validateEnv }),
    MongooseModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({ uri: config.get('MONGODB_URI', { infer: true }) }),
    }),
    BullModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({ connection: { url: config.get('REDIS_URL', { infer: true }) } }),
    }),
    ScheduleModule.forRoot(),
    ThrottlerModule.forRoot([{ ttl: 60_000, limit: 120 }]),
    OrdersModule,
  ],
  providers: [
    // Global enhancers registered as providers can use dependency injection.
    { provide: APP_GUARD, useClass: ThrottlerGuard },
    { provide: APP_FILTER, useClass: DomainExceptionFilter },
    { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor },
  ],
})
export class AppModule {}
src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import helmet from 'helmet';
import { AppModule } from './app.module';
import type { Env } from './config/env';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const config = app.get<ConfigService<Env, true>>(ConfigService);

  app.use(helmet());
  app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }).split(','), credentials: true });
  app.setGlobalPrefix('api');
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true, // strip properties without decorators
      forbidNonWhitelisted: true, // ...or rather reject them with 400
      transform: true, // turn payloads into DTO class instances (and apply defaults)
    }),
  );
  app.enableShutdownHooks(); // SIGTERM -> onModuleDestroy / beforeApplicationShutdown

  await app.listen(config.get('PORT', { infer: true }));
}

void bootstrap();

What is going on here:

  • ConfigService<Env, true> with { infer: true } gives typed reads – config.get('PORT', { infer: true }) returns a number, and a typo in a variable name does not compile.
  • forRootAsync + inject: [ConfigService] is the standard way for an infrastructure module (Mongoose, BullMQ) to get its configuration from DI instead of reading process.env in random places.
  • APP_GUARD, APP_FILTER and APP_INTERCEPTOR register global pipeline elements as providers – they can inject dependencies. app.useGlobalFilters(new X()) in main.ts cannot.
  • ValidationPipe with whitelist and forbidNonWhitelisted rejects fields the DTO does not know (e.g. "admin": true), and transform turns JSON into DTO class instances.

Step 3. The domain and ports

Before touching Nest, we describe the pierogi shop in plain TypeScript: types, rules and domain errors. This file imports nothing from @nestjs/* or mongoose.

Order domain and ports

src/orders/domain/order.ts
// Pure domain: no Nest, no Mongoose – just the rules of Halina's kitchen.
export const DISHES = ['ruskie', 'z-miesem', 'z-kapusta', 'z-jagodami'] as const;
export const ORDER_STATUSES = ['new', 'in-kitchen', 'ready', 'delivered', 'cancelled'] as const;
export const MAX_PIEROGI_PER_ORDER = 100;

export type Dish = (typeof DISHES)[number];
export type OrderStatus = (typeof ORDER_STATUSES)[number];

export interface OrderItem {
  dish: Dish;
  quantity: number;
}

export interface Order {
  id: string;
  customerName: string;
  phone: string;
  items: OrderItem[];
  note?: string;
  status: OrderStatus;
  createdAt: Date;
}

export type NewOrder = Omit<Order, 'id' | 'status' | 'createdAt'>;

export class DomainError extends Error {
  constructor(
    readonly code: string,
    message: string,
  ) {
    super(message);
  }
}

export class OrderNotFoundError extends DomainError {
  constructor(id: string) {
    super('ORDER_NOT_FOUND', `Order ${id} not found`);
  }
}

export class TooManyPierogiError extends DomainError {
  constructor(total: number) {
    super('TOO_MANY_PIEROGI', `Max ${MAX_PIEROGI_PER_ORDER} pierogi per order, got ${total}`);
  }
}

export class InvalidTransitionError extends DomainError {
  constructor(from: OrderStatus, to: OrderStatus) {
    super('INVALID_TRANSITION', `Cannot move order from "${from}" to "${to}"`);
  }
}

const TRANSITIONS: Record<OrderStatus, readonly OrderStatus[]> = {
  new: ['in-kitchen', 'cancelled'],
  'in-kitchen': ['ready', 'cancelled'],
  ready: ['delivered'],
  delivered: [],
  cancelled: [],
};

export function assertValidOrder(order: NewOrder): void {
  const total = order.items.reduce((sum, item) => sum + item.quantity, 0);
  if (total > MAX_PIEROGI_PER_ORDER) throw new TooManyPierogiError(total);
}

export function assertTransition(from: OrderStatus, to: OrderStatus): void {
  if (!TRANSITIONS[from].includes(to)) throw new InvalidTransitionError(from, to);
}
src/orders/domain/ports.ts
import type { NewOrder, Order, OrderStatus } from './order';

// Ports as abstract classes: they exist at runtime, so Nest can use them as DI tokens.
export abstract class OrdersRepository {
  abstract create(order: NewOrder): Promise<Order>;
  abstract findById(id: string): Promise<Order | null>;
  abstract list(filter: { status?: OrderStatus; limit: number }): Promise<Order[]>;
  abstract updateStatus(id: string, status: OrderStatus): Promise<Order | null>;
  abstract deleteCancelledBefore(date: Date): Promise<number>;
}

export abstract class KitchenTickets {
  abstract send(order: Order): Promise<void>;
}

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 4. The application service
  • Step 5. Controller, DTOs and pipes
  • Step 6. Guards, interceptors and exception filters
  • Step 7. Mongoose: schema, adapter and module
  • Step 8. Background work: a queue and a schedule
  • Step 9. Tests with swapped adapters
  • Common mistakes
  • When NestJS, and when not
  • Check yourself
  • What's next

Create a free account · Sign in