Skip to content
Back to skills

Hexagonal Nestjs Patterns

ASecurity

NestJS/TypeScript backend with hexagonal architecture, SOLID, and KISS. Project structure, ports as abstract classes (inbound/outbound split), Zod entity/DTO validation, injection tokens, exception filters, Swagger via zod-openapi. Use when implementing or refactoring a NestJS backend following hexagonal architecture.

  • 3 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 3, 2026
ai-agentstypescriptpythongonodefastapirefactoringapibackenddevopsperformance

Works with

  • api

Security analysis

A100/100

Pro scans all 8 files and shows the line behind each finding

Scanned December 3, 2026

npx -y skills add Kaiohz/ai-driven --skill hexagonal-nestjs-patterns --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Hexagonal Nestjs Patterns?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Hexagonal Nestjs Patterns
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/kaiohz-hexagonal-nestjs-patterns/badge)](https://www.skillsdirectory.com/skills/kaiohz-hexagonal-nestjs-patterns)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: hexagonal-nestjs-patterns
description: NestJS/TypeScript backend with hexagonal architecture, SOLID, and KISS. Project structure, ports as abstract classes (inbound/outbound split), Zod entity/DTO validation, injection tokens, exception filters, Swagger via zod-openapi. Use when implementing or refactoring a NestJS backend following hexagonal architecture.
---

# NestJS Hexagonal Architecture Patterns

Build a NestJS/TypeScript backend following hexagonal architecture, SOLID, and KISS.

## Use this skill when
- Implementing or refactoring a NestJS backend with hexagonal architecture
- Scaffolding the 3-layer project structure (domain / application / infrastructure)
- Defining ports as abstract classes and wiring injection tokens
- Using Zod for entity + DTO validation with NestJS pipes
- Mapping domain exceptions to HTTP exceptions

## Do not use this skill when
- The task is async/concurrency/RxJS → use `async-nestjs-patterns`
- The task is Python/FastAPI → use `hexagonal-python-patterns`
- The task is performance profiling → use `performance-audit`

## 🛡️ Edge cases (mandatory handling)
Every use case, controller, service, and adapter MUST handle edge cases defensively, not just the happy path. During implementation, cover:
- **Null / undefined inputs** — validate at the port boundary via Zod; throw the correct domain exception, never let `null` / `undefined` propagate silently into business logic
- **Empty / boundary values** — empty array, empty string, `0`, negative numbers, `new Date(0)`, single-element collections; handle explicitly
- **Off-by-one boundaries** — pagination first/last page, offset equals total count, zero results
- **Invalid / malformed input** — Zod schema validation covers structure, but add domain-level `.refine()` / `.superRefine()` for business rules (invalid state transition, value out of business range)
- **Concurrency / race conditions** — duplicate creation, optimistic locking conflict, idempotency key replay; handle with proper exception or upsert
- **External adapter failure** — outbound adapter throws or times out; catch at the use case level, map to the correct domain exception via the exception filter, never silently swallow
- **State transitions** — already-exists, not-found, already-deleted, illegal transition; throw the correct mapped HTTP exception

If the feature has domain invariants, enforce them in the Zod entity schema and throw the matching domain exception when violated.

## 🎯 Core workflow
1. **Structure** — load `references/project-structure.md` and reproduce the layout.
2. **Layer rules** — load `references/layer-rules.md` before writing code in a given layer.
3. **Zod usage** — load `references/zod-usage.md` for entity/DTO/config validation.
4. **NestJS conventions** — load `references/nestjs-conventions.md` for DI, modules, guards, exception filters, Swagger.
5. **Logging rules** — load `references/logging.md` and run its 7-point call checklist on EVERY log call you write. A log call not referencing a `domain/logging/` message constant is a defect, not a style choice.
6. **Checklist** — run `references/checklist.md` end-to-end before declaring done.
7. **Anti-patterns** — load `references/anti-patterns.md` to catch violations.

## 🎯 Core principles (summary)
- **Domain**: business core with Zod for entity validation — NO NestJS decorators, TypeORM, or Mongoose imports
- **Application**: orchestrates use cases, depends only on domain; thin controllers delegate to use cases
- **Infrastructure**: one folder per adapter (`postgres/`, `mongodb/`, `email/`), implements domain ports
- **Ports = abstract classes** (interfaces don't exist at runtime in TS)
- **Inbound ports** (use case entry points) vs **outbound ports** (infrastructure contracts)
- **Injection tokens** (symbols) for loose coupling between layers
- **SOLID**: SRP (1 class = 1 responsibility), OCP (extend via new adapters), LSP, ISP (no 20-method ports), DIP (use cases depend on ports, never adapters)
- **KISS**: direct transformations `new Class({ ...other })` or spread; **no** `fromEntity()` / `toEntity()` methods; **no** Response DTOs (return domain entities directly)
- **Centralized logging (STRICT)**: every log call MUST use a message constant from `src/domain/logging/` with lazy `%s`/`%d` args. Template literals and inline strings in log calls are FORBIDDEN. No logging inside `domain/` (entities, ports, pure services) — see `references/logging.md`.
- **Use case discipline (STRICT — blocking)**: see `references/layer-rules.md` (Application layer) before writing any use case:
  - **ONE use case class per file** — `CreateUserUseCase` lives alone in `create-user.use-case.ts`; NEVER append a second `*UseCase` class to an existing use case's file (its result type may share the file).
  - **Thin use cases** — a use case orchestrates (load → domain service/entity → outbound ports → return); business rules (validation guards, access policy, ownership checks, resolution logic) belong in `domain/services/` (plain TS classes, injected via tokens), NEVER in use-case private methods. ≥3 business private helpers or >~150 lines → extract a domain service.
  - **Reuse-first for logic** — before implementing any guard/query/loader, grep `application/use-cases/`, `domain/services/`, `domain/ports/` for an existing capability and inject/reuse it; re-implementing logic the app already has is a defect, not a style choice.
  - **No delegation-only wrappers (generalized)** — a method whose body ONLY wraps another method (single pass-through call — no guard, no error mapping, no added behavior) is useless indirection: call the target directly. Applies everywhere: use cases, domain services, adapters, controllers. When you touch a class, RE-SCAN it for remaining one-liner wrappers and remove them. A wrapper is justified ONLY when it adds behavior.

## 📦 Default stack
- Package manager: **pnpm**
- Runtime: Node.js + NestJS 10+
- Language: TypeScript 5.0+ (strict)
- Validation: Zod (entities, DTOs, config)
- ORM/ODM: TypeORM / Mongoose — only in `infrastructure/`, never in `domain/`
- Tests: Jest + ts-jest (real implementations for internals; mocks only for external adapters)
- Swagger: `@anatine/zod-openapi` for automatic OpenAPI docs

## References
- `references/project-structure.md` — the 3-layer directory tree (domain ports split inbound/outbound)
- `references/layer-rules.md` — domain + Zod, application DTOs, infrastructure adapter conventions
- `references/zod-usage.md` — Zod schemas for entities, DTOs, config; `z.infer`, `.refine()`, `.transform()`
- `references/logging.md` — centralized log message constants + the mandatory 7-point call checklist
- `references/nestjs-conventions.md` — DI, modules, guards, exception filters, Swagger, middleware
- `references/checklist.md` — architecture, SOLID, NestJS, DevOps checklists
- `references/anti-patterns.md` — "Absolutely Avoid" + critical reminders

Files in this skill

  • SKILL.md6.9 KB
  • references/anti-patterns.md2.5 KB
  • references/checklist.md2.9 KB
  • references/layer-rules.md12.9 KB
  • references/logging.md3.7 KB
  • references/nestjs-conventions.md4.3 KB
  • references/project-structure.md3.6 KB
  • references/zod-usage.md4 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.