Skip to content
NestPath

Swagger / OpenAPI

Documentation that writes itself. The CLI plugin, bearer + cookie auth schemes, @ApiOperation and friends, composed decorators, documenting your response envelope, and locking docs out of production.

Alright, last chapter. You've built the entire backend — middleware, guards, interceptors, pipes, controllers, services, filters, MongoDB, JWT auth. Now let's make it discoverable and testable without Postman collections or "check the Slack channel for the API docs" conversations that nobody reads.


The Problem You Have Right Now

Your API has 9 endpoints. You know them because you built them. Your frontend team (which is also you) knows them because you're the same person. But in 6 months when you come back to this project, or when another developer joins, they'll see a NestJS app and have to:

  1. Read every controller file to find endpoints
  2. Guess request body shapes by reading DTOs
  3. Guess response shapes by reading interceptors and services
  4. Test with curl or Postman, manually constructing headers and bodies
  5. Discover auth requirements by hitting 401s and reverse-engineering

That's not API design. That's an archaeology project.

Swagger gives you a live, interactive, auto-generated documentation page at /api/docs that lists every endpoint, every request/response shape, every header, every status code — and lets you test them directly from the browser with a built-in "Try it out" button. It's the single highest-ROI thing you can add to any backend.

Analogy

An undocumented API is a restaurant with no menu — you have to walk into the kitchen and ask the chef what he can cook, then guess the price. Swagger is the glossy menu with photos: every dish (endpoint) listed, ingredients (request body) spelled out, portion size (response shape) pictured, and a waiter standing by so you can order a sample right there at the table.


Installation

bash
npm install @nestjs/swagger

That's it. One package. NestJS's Swagger module reads your controllers, decorators, and DTOs to generate an OpenAPI 3.0 specification automatically. You're about to see why NestJS's decorator-heavy architecture pays off — every @Get(), @Body(), @Param() you've already written becomes documentation metadata for free.

Analogy

Because every dish in your kitchen was already labelled with its recipe card (the decorators), the menu practically prints itself. Swagger just walks the kitchen reading the cards you already wrote, instead of you retyping the whole menu by hand — the reward for keeping tidy recipe cards all along.


Basic Setup — Get It Running First

main.ts — Add Swagger bootstrap

ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor';
import helmet from 'helmet';
import * as cookieParser from 'cookie-parser';

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

  // Express middleware
  app.use(helmet());
  app.use(cookieParser());
  app.enableCors({
    origin: ['http://localhost:3001'],
    credentials: true,
  });

  // Pipes
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  // Filters
  app.useGlobalFilters(new AllExceptionsFilter());

  // Interceptors
  app.useGlobalInterceptors(
    new LoggingInterceptor(),
    new TransformInterceptor(),
    new TimeoutInterceptor(),
  );

  // ========================
  //     SWAGGER SETUP
  // ========================
  const config = new DocumentBuilder()
    .setTitle('Tasks API')
    .setDescription('NestJS Task Management API with JWT Authentication')
    .setVersion('1.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'Authorization',
        description: 'Enter your access token',
        in: 'header',
      },
      'access-token', // this is a reference name — used in @ApiBearerAuth()
    )
    .addCookieAuth(
      'refreshToken',
      {
        type: 'apiKey',
        in: 'cookie',
        name: 'refreshToken',
        description: 'HttpOnly refresh token (set automatically by login/refresh)',
      },
      'refresh-token',
    )
    .addTag('Auth', 'Registration, login, token refresh, logout')
    .addTag('Tasks', 'CRUD operations for tasks')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document, {
    swaggerOptions: {
      persistAuthorization: true, // keeps token between page refreshes
      tagsSorter: 'alpha',
      operationsSorter: 'method',
    },
    customSiteTitle: 'Tasks API Documentation',
  });

  await app.listen(3000);
}
bootstrap();

Now visit http://localhost:3000/api/docs and you'll see a Swagger UI. But it's barebones — endpoints are listed but request/response shapes are missing, descriptions are empty, and status codes are wrong. Let's fix that.

Breaking down the Swagger config:

DocumentBuilder — Fluent builder for the OpenAPI spec metadata. Title, description, version — these show at the top of the Swagger page.

addBearerAuth() — Adds a "lock" icon to the Swagger UI. Clicking it lets you paste your access token, and Swagger attaches it to every request. The second argument 'access-token' is a security scheme reference name — you'll use it in controller decorators to specify which endpoints require this auth.

addCookieAuth() — Documents the refresh token cookie. Swagger UI can't set HttpOnly cookies directly (browser restriction), but documenting it tells developers the cookie exists and how it works.

addTag() — Groups endpoints in the UI. Without tags, all endpoints are in a single list. Tags organize them by domain (Auth, Tasks).

SwaggerModule.setup('api/docs', ...) — Mounts the Swagger UI at /api/docs. The JSON spec itself is at /api/docs-json (useful for code generators).

persistAuthorization: true — When you paste a token in Swagger UI and refresh the page, it remembers the token. Without this, you re-paste after every refresh. Small thing, huge quality of life.


The Plugin — Auto-Generate DTO Metadata

Here's NestJS Swagger's biggest pain point and its best solution. By default, Swagger can't read your DTO property types because TypeScript types don't exist at runtime. You'd have to manually add @ApiProperty() to every single DTO field:

ts
// WITHOUT plugin — you'd have to do this on every property:
export class CreateTaskDto {
  @ApiProperty({ description: 'Task title', example: 'Buy groceries' })
  @IsString()
  @IsNotEmpty()
  title: string;

  @ApiProperty({ description: 'Task description', example: 'Milk, eggs, bread' })
  @IsString()
  @IsNotEmpty()
  description: string;
}

That's tedious and violates DRY. The Swagger CLI plugin fixes this by reading your TypeScript source at compile time and auto-adding @ApiProperty() metadata based on types, decorators, and JSDoc comments.

Analogy

The plugin is the menu designer who visits the kitchen before opening and photographs every dish for you. Instead of the chef writing a description card for each plate, the designer reads what's already on the pass and fills the menu automatically. You only step in to add the tasting notes ("goes well with...") that a camera can't capture.

nest-cli.json — Enable the plugin

json
{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true,
    "plugins": [
      {
        "name": "@nestjs/swagger",
        "options": {
          "classValidatorShim": true,
          "introspectComments": true,
          "dtoFileNameSuffix": [".dto.ts", ".schema.ts"]
        }
      }
    ]
  }
}

classValidatorShim: true — Reads class-validator decorators and converts them to Swagger metadata. @IsString() → type: string. @IsNotEmpty() → required: true. @IsOptional() → required: false. @MinLength(8) → minLength: 8. Your existing validation decorators become documentation automatically. Zero extra work.

introspectComments: true — Reads JSDoc comments above properties and uses them as descriptions in Swagger. Write a comment once, get validation AND documentation.

dtoFileNameSuffix — Tells the plugin which files to process. Files ending in .dto.ts and .schema.ts get auto-introspected.

After enabling the plugin, restart the server (not just hot-reload — the plugin runs at compile time). npm run start:dev again.


DTOs — Enhanced with Swagger Metadata

With the plugin enabled, your DTOs need minimal additions. The plugin handles types and required/optional automatically. You just add descriptions and examples for clarity.

src/auth/dto/register.dto.ts

ts
import {
  IsEmail, IsString, IsNotEmpty,
  MinLength, MaxLength, Matches,
} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class RegisterDto {
  /** User's email address */
  @ApiProperty({ example: 'john@example.com' })
  @IsEmail({}, { message: 'Please provide a valid email' })
  email: string;

  /** Unique username (letters, numbers, underscores only) */
  @ApiProperty({ example: 'john_doe' })
  @IsString()
  @IsNotEmpty()
  @MinLength(3)
  @MaxLength(20)
  @Matches(/^[a-zA-Z0-9_]+$/, {
    message: 'Username can only contain letters, numbers, and underscores',
  })
  username: string;

  /**
   * Password must contain at least one uppercase letter,
   * one lowercase letter, and one number
   */
  @ApiProperty({ example: 'SecurePass123' })
  @IsString()
  @MinLength(8, { message: 'Password must be at least 8 characters' })
  @MaxLength(64)
  @Matches(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, {
    message:
      'Password must contain at least one uppercase letter, one lowercase letter, and one number',
  })
  password: string;
}

src/auth/dto/login.dto.ts

ts
import { IsEmail, IsString, IsNotEmpty } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class LoginDto {
  /** Registered email address */
  @ApiProperty({ example: 'john@example.com' })
  @IsEmail()
  email: string;

  /** Account password */
  @ApiProperty({ example: 'SecurePass123' })
  @IsString()
  @IsNotEmpty()
  password: string;
}

src/tasks/dto/create-task.dto.ts

ts
import { IsString, IsNotEmpty, MaxLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class CreateTaskDto {
  /** Title of the task */
  @ApiProperty({ example: 'Buy groceries' })
  @IsString({ message: 'title must be a string, not whatever you just sent' })
  @IsNotEmpty({ message: 'title should not be empty — what kind of task has no title?' })
  @MaxLength(100)
  title: string;

  /** Detailed description of what needs to be done */
  @ApiProperty({ example: 'Milk, eggs, bread, and coffee' })
  @IsString()
  @IsNotEmpty()
  @MaxLength(500)
  description: string;
}

src/tasks/dto/update-task.dto.ts

ts
import { IsString, IsBoolean, IsOptional, MaxLength } from 'class-validator';
import { ApiPropertyOptional } from '@nestjs/swagger';

export class UpdateTaskDto {
  /** Updated task title */
  @ApiPropertyOptional({ example: 'Buy groceries and snacks' })
  @IsOptional()
  @IsString()
  @MaxLength(100)
  title?: string;

  /** Updated task description */
  @ApiPropertyOptional({ example: 'Updated list: milk, eggs, bread, coffee, chips' })
  @IsOptional()
  @IsString()
  @MaxLength(500)
  description?: string;

  /** Mark task as complete or incomplete */
  @ApiPropertyOptional({ example: true })
  @IsOptional()
  @IsBoolean()
  done?: boolean;
}

Key distinction:

@ApiProperty() — Required field. Shows in Swagger as mandatory.

@ApiPropertyOptional() — Optional field. Swagger shows it as not required. You can also use @ApiProperty({ required: false }) but @ApiPropertyOptional() is cleaner.

example values — These pre-fill the "Try it out" form in Swagger UI. Without examples, the user sees empty fields or auto-generated garbage like "string". Good examples make the API self-documenting and instantly testable.

JSDoc comments (/** ... */) — With introspectComments: true in the plugin config, these become the description field in Swagger. Write once, document everywhere.


Controllers — Full Swagger Decoration

This is where the documentation becomes rich. Every endpoint gets: a summary, description, possible response codes, auth requirements, and parameter descriptions.

src/auth/auth.controller.ts — Fully Documented

ts
import {
  Controller, Post, Body, Res, Req,
  HttpCode, HttpStatus,
} from '@nestjs/common';
import {
  ApiTags, ApiOperation, ApiResponse,
  ApiBearerAuth, ApiBody, ApiCookieAuth,
} from '@nestjs/swagger';
import { Request, Response } from 'express';
import { AuthService } from './auth.service';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import { Public } from '../common/decorators/public.decorator';
import { CurrentUser } from '../common/decorators/current-user.decorator';

@ApiTags('Auth')
@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Public()
  @Post('register')
  @ApiOperation({
    summary: 'Register a new user',
    description:
      'Creates a new user account. Does not return tokens — user must log in after registration.',
  })
  @ApiResponse({
    status: 201,
    description: 'User successfully registered',
    schema: {
      example: {
        success: true,
        data: {
          message: 'Registration successful',
          user: {
            id: '507f1f77bcf86cd799439011',
            email: 'john@example.com',
            username: 'john_doe',
          },
        },
        timestamp: '2026-02-12T10:00:00.000Z',
        path: '/auth/register',
      },
    },
  })
  @ApiResponse({
    status: 400,
    description: 'Validation failed — check request body',
    schema: {
      example: {
        success: false,
        statusCode: 400,
        error: 'Bad Request',
        message: 'Validation failed',
        details: [
          'email must be a valid email',
          'password must be at least 8 characters',
        ],
        timestamp: '2026-02-12T10:00:00.000Z',
        path: '/auth/register',
      },
    },
  })
  @ApiResponse({
    status: 409,
    description: 'Email or username already exists',
  })
  async register(@Body() registerDto: RegisterDto) {
    return this.authService.register(registerDto);
  }

  @Public()
  @Post('login')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Log in with email and password',
    description:
      'Authenticates user and returns an access token in the response body. ' +
      'A refresh token is set as an HttpOnly cookie automatically. ' +
      'The refresh token is NOT included in the response body.',
  })
  @ApiBody({ type: LoginDto })
  @ApiResponse({
    status: 200,
    description: 'Login successful — access token returned, refresh token set as cookie',
    schema: {
      example: {
        success: true,
        data: {
          accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
          user: {
            id: '507f1f77bcf86cd799439011',
            email: 'john@example.com',
            username: 'john_doe',
            roles: ['user'],
          },
        },
        timestamp: '2026-02-12T10:00:00.000Z',
        path: '/auth/login',
      },
    },
    headers: {
      'Set-Cookie': {
        description: 'refreshToken=<token>; HttpOnly; Secure; SameSite=Strict; Path=/auth',
        schema: { type: 'string' },
      },
    },
  })
  @ApiResponse({
    status: 401,
    description: 'Invalid email or password',
  })
  async login(
    @Body() loginDto: LoginDto,
    @Res({ passthrough: true }) response: Response,
  ) {
    const result = await this.authService.login(loginDto);
    this.setRefreshTokenCookie(response, result.refreshToken);
    return {
      accessToken: result.accessToken,
      user: result.user,
    };
  }

  @Public()
  @Post('refresh')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: 'Refresh access token',
    description:
      'Uses the refresh token from the HttpOnly cookie to generate a new access token ' +
      'and rotate the refresh token. The browser sends the cookie automatically — ' +
      'no manual token handling needed on the frontend.',
  })
  @ApiCookieAuth('refresh-token')
  @ApiResponse({
    status: 200,
    description: 'New access token returned, new refresh token set as cookie',
    schema: {
      example: {
        success: true,
        data: { accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' },
        timestamp: '2026-02-12T10:00:00.000Z',
        path: '/auth/refresh',
      },
    },
  })
  @ApiResponse({
    status: 401,
    description: 'Missing, invalid, or expired refresh token',
  })
  @ApiResponse({
    status: 403,
    description: 'Refresh token reuse detected — all sessions invalidated',
  })
  async refresh(
    @Req() request: Request,
    @Res({ passthrough: true }) response: Response,
  ) {
    const refreshToken = request.cookies?.['refreshToken'];
    const result = await this.authService.refresh(refreshToken);
    this.setRefreshTokenCookie(response, result.refreshToken);
    return { accessToken: result.accessToken };
  }

  @Post('logout')
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth('access-token')
  @ApiOperation({
    summary: 'Log out current device',
    description:
      'Invalidates the refresh token for the current session. ' +
      'The access token remains valid until it expires (stateless). ' +
      'Clears the refresh token cookie.',
  })
  @ApiResponse({ status: 200, description: 'Successfully logged out' })
  @ApiResponse({ status: 401, description: 'Not authenticated' })
  async logout(
    @Req() request: Request,
    @Res({ passthrough: true }) response: Response,
    @CurrentUser('sub') userId: string,
  ) {
    const refreshToken = request.cookies?.['refreshToken'];
    const result = await this.authService.logout(refreshToken, userId);
    response.clearCookie('refreshToken', {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      path: '/auth',
    });
    return result;
  }

  @Post('logout-all')
  @HttpCode(HttpStatus.OK)
  @ApiBearerAuth('access-token')
  @ApiOperation({
    summary: 'Log out all devices',
    description:
      'Invalidates ALL refresh tokens for this user. ' +
      'Use when you suspect account compromise.',
  })
  @ApiResponse({ status: 200, description: 'All sessions invalidated' })
  @ApiResponse({ status: 401, description: 'Not authenticated' })
  async logoutAll(
    @Res({ passthrough: true }) response: Response,
    @CurrentUser('sub') userId: string,
  ) {
    const result = await this.authService.logoutAll(userId);
    response.clearCookie('refreshToken', {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      path: '/auth',
    });
    return result;
  }

  private setRefreshTokenCookie(response: Response, token: string) {
    response.cookie('refreshToken', token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      path: '/auth',
      maxAge: 7 * 24 * 60 * 60 * 1000,
    });
  }
}

src/tasks/tasks.controller.ts — Fully Documented

ts
import {
  Controller, Get, Post, Patch, Delete,
  Param, Body,
} from '@nestjs/common';
import {
  ApiTags, ApiOperation, ApiResponse, ApiParam,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { TasksService } from './tasks.service';
import { CreateTaskDto } from './dto/create-task.dto';
import { UpdateTaskDto } from './dto/update-task.dto';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { Roles } from '../common/decorators/roles.decorator';

@ApiTags('Tasks')
@ApiBearerAuth('access-token') // applies to ALL routes in this controller
@Controller('tasks')
export class TasksController {
  constructor(private readonly tasksService: TasksService) {}

  @Get()
  @ApiOperation({
    summary: 'Get all tasks for the authenticated user',
    description: 'Returns only tasks owned by the currently authenticated user.',
  })
  @ApiResponse({
    status: 200,
    description: 'List of user tasks',
    schema: {
      example: {
        success: true,
        data: [
          {
            _id: '507f1f77bcf86cd799439011',
            title: 'Buy groceries',
            description: 'Milk, eggs, bread',
            done: false,
            owner: '507f1f77bcf86cd799439012',
            createdAt: '2026-02-12T10:00:00.000Z',
            updatedAt: '2026-02-12T10:00:00.000Z',
          },
        ],
        timestamp: '2026-02-12T10:00:00.000Z',
        path: '/tasks',
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Not authenticated' })
  findAll(@CurrentUser('sub') userId: string) {
    return this.tasksService.findAll(userId);
  }

  @Get(':id')
  @ApiOperation({
    summary: 'Get a specific task by ID',
    description: 'Returns the task only if the authenticated user owns it.',
  })
  @ApiParam({
    name: 'id',
    description: 'MongoDB ObjectId of the task',
    example: '507f1f77bcf86cd799439011',
  })
  @ApiResponse({ status: 200, description: 'Task found and returned' })
  @ApiResponse({ status: 401, description: 'Not authenticated' })
  @ApiResponse({ status: 403, description: 'User does not own this task' })
  @ApiResponse({ status: 404, description: 'Task not found' })
  findOne(
    @Param('id') id: string,
    @CurrentUser('sub') userId: string,
  ) {
    return this.tasksService.findOne(id, userId);
  }

  @Post()
  @ApiOperation({
    summary: 'Create a new task',
    description: 'Creates a task owned by the authenticated user.',
  })
  @ApiResponse({ status: 201, description: 'Task created successfully' })
  @ApiResponse({ status: 400, description: 'Validation failed' })
  @ApiResponse({ status: 401, description: 'Not authenticated' })
  create(
    @Body() createTaskDto: CreateTaskDto,
    @CurrentUser('sub') userId: string,
  ) {
    return this.tasksService.create(createTaskDto, userId);
  }

  @Patch(':id')
  @ApiOperation({
    summary: 'Update an existing task',
    description:
      'Partially updates a task. Only the fields provided will be changed. ' +
      'User must own the task.',
  })
  @ApiParam({
    name: 'id',
    description: 'MongoDB ObjectId of the task to update',
    example: '507f1f77bcf86cd799439011',
  })
  @ApiResponse({ status: 200, description: 'Task updated successfully' })
  @ApiResponse({ status: 400, description: 'Validation failed' })
  @ApiResponse({ status: 401, description: 'Not authenticated' })
  @ApiResponse({ status: 403, description: 'User does not own this task' })
  @ApiResponse({ status: 404, description: 'Task not found' })
  update(
    @Param('id') id: string,
    @Body() updateTaskDto: UpdateTaskDto,
    @CurrentUser('sub') userId: string,
  ) {
    return this.tasksService.update(id, updateTaskDto, userId);
  }

  @Roles('admin')
  @Delete(':id')
  @ApiOperation({
    summary: 'Delete a task (admin only)',
    description:
      'Permanently deletes a task. Requires the "admin" role. ' +
      'Even admins can only delete tasks they own.',
  })
  @ApiParam({
    name: 'id',
    description: 'MongoDB ObjectId of the task to delete',
    example: '507f1f77bcf86cd799439011',
  })
  @ApiResponse({
    status: 200,
    description: 'Task deleted',
    schema: {
      example: {
        success: true,
        data: { deleted: true },
        timestamp: '2026-02-12T10:00:00.000Z',
        path: '/tasks/507f1f77bcf86cd799439011',
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Not authenticated' })
  @ApiResponse({ status: 403, description: 'Insufficient role or not task owner' })
  @ApiResponse({ status: 404, description: 'Task not found' })
  async remove(
    @Param('id') id: string,
    @CurrentUser('sub') userId: string,
  ) {
    await this.tasksService.remove(id, userId);
    return { deleted: true }; // matches the documented 200 body
  }
}

Breaking Down Every Swagger Decorator

Controller-level decorators

@ApiTags('Tasks') — Groups all routes in this controller under the "Tasks" section in Swagger UI. Without tags, endpoints appear in an "default" group. Tags match the addTag() calls in your DocumentBuilder.

@ApiBearerAuth('access-token') — At controller level, applies to ALL routes. Tells Swagger: "every route here requires a Bearer token." The 'access-token' string references the security scheme you defined in DocumentBuilder.addBearerAuth(). In Swagger UI, each endpoint shows a lock icon.

Analogy

The auth decorators are the "members only" and "cards we accept" notices on the menu. A lock icon next to a dish is the maître d' saying you'll need to show membership before this one is served, and the security scheme is the little row of payment-card logos by the door telling you which credentials the place actually honours.

Method-level decorators

@ApiOperation({ summary, description }) — summary is the one-liner shown in the endpoint list (collapsed view). description is the detailed text shown when expanded. Summary = what it does. Description = how it does it, edge cases, special behavior.

@ApiResponse({ status, description, schema? }) — Documents a possible response. You can have multiple per endpoint — one for each status code. schema.example provides a concrete JSON example in the docs. Without examples, Swagger shows generic types which are almost useless for integration work.

@ApiParam({ name, description, example }) — Documents URL parameters. name must match the :id in your route. example pre-fills the "Try it out" field.

@ApiBody({ type: SomeDto }) — Usually auto-detected from @Body() dto: SomeDto, but explicit when needed (useful for polymorphic bodies or when the plugin doesn't pick it up).

@ApiCookieAuth('refresh-token') — Documents that the endpoint uses cookie-based auth. Matches the addCookieAuth() reference name. Swagger UI can't set HttpOnly cookies, but this tells developers the mechanism.


Custom Swagger Decorators — DRY Your Documentation

You're repeating @ApiResponse({ status: 401, description: 'Not authenticated' }) on almost every endpoint. Same for 400 and 403. Create reusable combined decorators:

Analogy

This is the "all prices include tax and service" footnote printed once at the bottom of the menu instead of after every single dish. The information is still there for every item, but you wrote it a single time and stamped it everywhere, rather than cluttering each line with the same small print.

src/common/decorators/api-responses.decorator.ts

ts
import { applyDecorators } from '@nestjs/common';
import { ApiResponse } from '@nestjs/swagger';

export function ApiAuthResponses() {
  return applyDecorators(
    ApiResponse({ status: 401, description: 'Not authenticated — missing or invalid access token' }),
    ApiResponse({ status: 403, description: 'Forbidden — insufficient permissions' }),
  );
}

export function ApiValidationResponse() {
  return applyDecorators(
    ApiResponse({
      status: 400,
      description: 'Validation failed',
      schema: {
        example: {
          success: false,
          statusCode: 400,
          error: 'Bad Request',
          message: 'Validation failed',
          details: ['field must be a string', 'field should not be empty'],
          timestamp: '2026-02-12T10:00:00.000Z',
          path: '/endpoint',
        },
      },
    }),
  );
}

export function ApiNotFoundResponse(entity: string = 'Resource') {
  return applyDecorators(
    ApiResponse({ status: 404, description: `${entity} not found` }),
  );
}

Usage in controllers:

ts
@Get(':id')
@ApiOperation({ summary: 'Get a specific task by ID' })
@ApiAuthResponses()          // ← one decorator replaces two
@ApiNotFoundResponse('Task') // ← parameterized
findOne(@Param('id') id: string, @CurrentUser('sub') userId: string) {
  return this.tasksService.findOne(id, userId);
}

applyDecorators() — NestJS utility that composes multiple decorators into one. This is how you build reusable decorator sets. Works with any decorators — Swagger, validators, guards, anything.


Swagger for Response Wrapping — Document Your Interceptor Output

Your TransformInterceptor wraps every response in { success, data, timestamp, path }. Swagger doesn't know about this by default because the interceptor runs outside the controller's return type. You need to tell Swagger about the wrapper.

Analogy

The menu photo shows the dish, but not the branded box and receipt it gets wrapped in at the counter (your interceptor's envelope). The camera never sees the packaging because wrapping happens after the plate leaves the kitchen. So you hand the menu designer a separate photo of the box, so the customer knows exactly what will arrive at their door.

src/common/swagger/api-wrapped-response.ts

ts
import { applyDecorators, Type } from '@nestjs/common';
import { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger';

export function ApiWrappedResponse(
  status: number,
  description: string,
  dataDto?: Type<any>,
  isArray: boolean = false,
) {
  const dataSchema = dataDto
    ? isArray
      ? { type: 'array', items: { $ref: getSchemaPath(dataDto) } }
      : { $ref: getSchemaPath(dataDto) }
    : { type: 'object', nullable: true };

  const decorators = [
    ApiResponse({
      status,
      description,
      schema: {
        properties: {
          success: { type: 'boolean', example: true },
          data: dataSchema,
          // requestId joins the envelope once you thread it through in Module 06
          requestId: { type: 'string', example: 'a1b2c3d4-...' },
          timestamp: { type: 'string', example: '2026-02-12T10:00:00.000Z' },
          path: { type: 'string', example: '/tasks' },
        },
      },
    }),
  ];

  if (dataDto) {
    decorators.unshift(ApiExtraModels(dataDto));
  }

  return applyDecorators(...decorators);
}

This is the advanced pattern. For your current stage, the inline schema.example approach is perfectly fine. This becomes valuable when your DTOs are complex and you want Swagger to reference them with $ref instead of duplicating schemas.


Disable Swagger in Production

Swagger docs are for development and staging. In production, exposing them gives attackers a detailed map of your API.

Analogy

The full illustrated menu is for the dining room, not for taping to the back door where burglars case the place. In production you take the detailed floor plan down: legitimate diners already know what they ordered, and a stranger studying every entrance and safe location is exactly who you don't want holding the map.

main.ts — Conditional setup

ts
// Swagger — only in non-production
if (process.env.NODE_ENV !== 'production') {
  const config = new DocumentBuilder()
    .setTitle('Tasks API')
    .setDescription('NestJS Task Management API with JWT Authentication')
    .setVersion('1.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'Authorization',
        description: 'Enter your access token',
        in: 'header',
      },
      'access-token',
    )
    .addCookieAuth(
      'refreshToken',
      {
        type: 'apiKey',
        in: 'cookie',
        name: 'refreshToken',
      },
      'refresh-token',
    )
    .addTag('Auth', 'Registration, login, token refresh, logout')
    .addTag('Tasks', 'CRUD operations for tasks')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document, {
    swaggerOptions: {
      persistAuthorization: true,
      tagsSorter: 'alpha',
      operationsSorter: 'method',
    },
    customSiteTitle: 'Tasks API Documentation',
  });
}

In production, /api/docs returns 404. Simple, effective.


Testing the Auth Flow in Swagger UI

Here's the exact workflow for testing your API through Swagger:

text
① Open http://localhost:3000/api/docs

② Expand POST /auth/register
   → Click "Try it out"
   → The example values from @ApiProperty are pre-filled
   → Click "Execute"
   → See 201 response with user data

③ Expand POST /auth/login
   → Click "Try it out"
   → Enter the same email/password you registered with
   → Click "Execute"
   → See 200 response with accessToken
   → COPY the accessToken value

④ Click the "Authorize" button (top right, lock icon)
   → Paste the accessToken in the "access-token (http, Bearer)" field
   → Click "Authorize" → Close
   → All endpoints now send this token automatically

⑤ Expand GET /tasks
   → Click "Try it out" → "Execute"
   → See 200 response with your (empty) tasks list

⑥ Expand POST /tasks
   → Click "Try it out"
   → Example values pre-filled from @ApiProperty
   → Click "Execute"
   → See 201 response with created task

⑦ Try DELETE /tasks/:id without admin role
   → See 403 Forbidden response

⑧ Wait 15 minutes (access token expires)
   → Any request returns 401
   → POST /auth/refresh won't work in Swagger UI
     (HttpOnly cookie can't be set via Swagger)
   → For refresh testing, use curl or your React app

The Swagger limitation: Swagger UI runs in the browser but can't set HttpOnly cookies. The /auth/refresh endpoint works perfectly from your React app (browser sends cookie automatically) but can't be fully tested in Swagger. This is a known limitation. For auth flow testing, use your frontend or curl:

bash
# Login and capture the cookie
curl -X POST http://localhost:3000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"john@example.com","password":"SecurePass123"}' \
  -c cookies.txt  # saves cookies to file

# Refresh using the saved cookie (-b sends saved cookies, -c saves the rotated one)
curl -X POST http://localhost:3000/auth/refresh \
  -b cookies.txt \
  -c cookies.txt

OpenAPI JSON Spec — Beyond Swagger UI

Your Swagger UI is at /api/docs. The raw OpenAPI JSON spec is at /api/docs-json. This JSON file is machine-readable and can be used for:

Frontend type generation — Tools like openapi-typescript or swagger-typescript-api read the spec and generate TypeScript types and API client code. Your frontend never manually types response interfaces:

bash
npx openapi-typescript http://localhost:3000/api/docs-json -o src/api/types.ts

Now your React app has auto-generated types that match your backend exactly. Backend changes a DTO → regenerate → TypeScript catches mismatches at compile time. End-to-end type safety without manual sync.

API gateway configuration — Tools like Kong or AWS API Gateway can import OpenAPI specs to auto-configure routes, rate limits, and auth.

Mock servers — Tools like Prism generate mock API servers from the spec. Frontend devs can develop against the mock before the backend is ready.

Postman/Insomnia import — Both tools can import OpenAPI specs and auto-generate request collections.

The Swagger UI is the visible benefit. The JSON spec is the invisible infrastructure that makes your API a first-class artifact.


Final Project Structure

src
app.module.ts
main.ts
common
decorators
public.decorator.ts
roles.decorator.ts
current-user.decorator.ts
api-responses.decorator.tsreusable Swagger decorators
filters
all-exceptions.filter.ts
guards
auth.guard.ts
roles.guard.ts
interceptors
transform.interceptor.ts
logging.interceptor.ts
timeout.interceptor.ts
middleware
request-logger.middleware.ts
interfaces
api-response.interface.ts
error-response.interface.ts
auth
auth.module.ts
auth.controller.tsSwagger-documented
auth.service.ts
dto
register.dto.ts@ApiProperty examples
login.dto.ts
users
users.module.ts
users.service.ts
schemas
user.schema.ts
tasks
tasks.module.ts
tasks.controller.tsSwagger-documented
tasks.service.ts
schemas
task.schema.ts
dto
create-task.dto.ts@ApiProperty examples
update-task.dto.ts

The Complete Stack — Everything You've Built

SWAGGER / OpenAPI

/api/docs — interactive documentation
/api/docs-json — machine-readable spec
documents everything below

REQUEST PIPELINE

① Middleware (helmet, cors, cookies, logging, rate limiting, request ID)
② Guards (JWT auth, role-based authorization)
③ Interceptors PRE (logging, timeout start)
④ Pipes (DTO validation, type transformation)
⑤ Controller (thin route handler, delegates)
⑥ Service (business logic, DB operations)
⑦ Interceptors POST (response wrapping, timing)
⑧ Exception Filter (consistent error formatting)

FOUNDATIONS

Database: MongoDB via Mongoose
Auth: JWT access + refresh tokens with rotation
Storage: refresh tokens hashed in DB
Transport: HttpOnly cookies for refresh tokens

You started with an empty NestJS app and a "what's a module?" question. You now have a production-grade architecture with every layer of the request lifecycle implemented, understood, and documented. Each lesson built on the last without breaking what came before — that's the NestJS architecture paying dividends.

The foundation is solid. From here, you scale: add more entities, add WebSockets, add caching with Redis, add queue processing with Bull, add microservices communication — NestJS has modules for all of them, and they all plug into this same pipeline the same way. The patterns don't change. Only the complexity of what you put inside them does.