NestJS API Standards & Common Patterns
Priority: P1 (OPERATIONAL)
Standardized API response patterns and common NestJS conventions.
Workflow: Standardize an API Endpoint
- Create Response DTO — Define a dedicated DTO for every endpoint return type.
- Map entity to DTO — Use
plainToInstance(UserResponseDto, user)in the service or controller. - Apply TransformInterceptor — Bind globally to wrap all responses in
{ statusCode, data, meta }. - Add nested validation — Decorate nested DTO properties with
@ValidateNested()+@Type(). - Document with Swagger — Apply
@ApiResponse({ status, type })with exact types per endpoint.
Response Wrapper Example
Entity-to-DTO Mapping Example
Deep Validation (Critical)
- [Rule] Nested Validation: When a DTO property is an object or array of objects, you MUST use
@ValidateNested()along with@Type(() => TargetDto)fromclass-transformerto ensure deep validation.
Pagination Standards
- DTOs: Use strict
PageOptionsDto(page/take/order) andPageDto<T>(data/meta). - Swagger Logic: Generics require
ApiExtraModelsand schema path resolution. - Reference: See Pagination Wrapper Implementation for the complete
ApiPaginatedResponsedecorator code.
Custom Error Response
- Standard Error Object: Define
ApiErrorResponsewithstatusCode,message,error,timestamp,path. See Error Response Class. - Docs: Apply
@ApiBadRequestResponse({ type: ApiErrorResponse })globally or per controller.
Anti-Patterns
- No raw entity returns: Always map to a Response DTO; raw entities leak internal fields.
- No unvalidated nested DTOs: Use
@ValidateNested()+@Type()for all nested object properties. - No generic 200 docs: Apply
@ApiResponse({ status, type })with exact types per endpoint.