Software Studio
Back to Articles

TypeScript Patterns for NestJS APIs

TypeScriptNestJSNode.jsAPI Design
Cover illustration for TypeScript Patterns for NestJS APIs

NestJS is the closest thing Node.js has to a mature, opinionated backend framework. It draws heavily from Angular's architecture, with modules, providers and decorators, but applied to server-side development. After building several production APIs with it, here are the patterns that matter.

Organize by feature with modules

The module system is NestJS's greatest strength. Each feature gets its own module with its controllers, services and data access layer. This enforces separation of concerns at the framework level.

A UserModule contains everything related to users. An AuthModule handles authentication. They communicate through well-defined interfaces: a module only exposes what it explicitly exports.

@Module({
  controllers: [UsersController],
  providers: [UsersService, UsersRepository],
  exports: [UsersService],
})
export class UsersModule {}

Let dependency injection do the wiring

Dependency injection makes testing straightforward. Every service declares its dependencies in the constructor, and NestJS resolves them automatically.

@Injectable()
export class UsersService {
  constructor(private readonly users: UsersRepository) {}

  findById(id: string) {
    return this.users.findById(id);
  }
}

In tests, you swap real dependencies for mocks. This pattern eliminates the need for the monkey-patching or import hacking that plagues other Node.js frameworks.

Validate every input with DTOs

Type-safe validation with class-validator and class-transformer is non-negotiable. Define DTOs (Data Transfer Objects) for every endpoint's input and decorate the properties with validation rules.

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(2)
  name: string;
}

The ValidationPipe applies these rules globally, rejecting malformed requests before they reach your business logic.

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

The whitelist option strips any property that isn't in the DTO, so a client can't slip extra fields into a request.

Handle errors with exception classes

Error handling follows a consistent pattern: custom exception classes that extend HttpException.

  • BadRequestException for validation errors.
  • NotFoundException for missing resources.
  • ForbiddenException for authorization failures.

The global exception filter catches these and returns consistent error responses. Services throw meaningful exceptions and never build HTTP responses themselves, so every error from your API has the same shape.

Pair NestJS with Prisma

For database access, I pair NestJS with Prisma. The PrismaService extends PrismaClient and implements OnModuleInit to handle the connection lifecycle.

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }
}

Each feature module gets a repository service that wraps Prisma queries, keeping database concerns out of the business logic layer. A service asks the repository for a user. It doesn't know or care how the query is written.

Use guards for authorization

Guards handle authorization cleanly. An AuthGuard validates JWT tokens. A RolesGuard checks user permissions. They compose declaratively with decorators on a controller or route.

@UseGuards(AuthGuard, RolesGuard)
@Roles("admin")
@Delete(":id")
remove(@Param("id") id: string) {
  return this.usersService.remove(id);
}

The guard pattern keeps authorization logic centralized and testable. You can read a controller and see at a glance who is allowed to call each route. For the token side of this, see OAuth 2.0 and OpenID Connect: A Practical Guide.

Use interceptors for cross-cutting concerns

Interceptors are underused but powerful.

  • A LoggingInterceptor records request and response times.
  • A TransformInterceptor wraps responses in a consistent envelope.
  • A CacheInterceptor adds response caching.

These cross-cutting concerns stay separate from business logic. No handler needs a line of timing or wrapping code.

Separate commands from queries

The pattern I wish I'd adopted sooner: command/query separation.

  • Commands (create, update, delete) return simple acknowledgments.
  • Queries return data.

This maps cleanly to REST semantics and makes caching trivial: cache all GET responses and invalidate on mutations. It also makes handlers easier to reason about, because each one either changes something or reads something, never both.

The short version

  • One module per feature.
  • Dependencies through constructors.
  • A DTO for every input, validated globally.
  • Exceptions for errors, one filter for responses.
  • Repositories around Prisma.
  • Guards for access, interceptors for everything cross-cutting.
  • Commands and queries kept apart.

NestJS has opinions, and the easiest way to work with it is to follow them. If you're weighing it against another runtime, I compare the two in Go for Backend Services: A Node.js Developer's Perspective.