※ The code examples in this article are based on a real product, but project names, service names, variable names, and anything else that could identify a specific product have been changed or generalized.
(I didn't write all of this from scratch. I took AI-generated content and fixed it up, so I could use it as a kind of dictionary for the project.)
NestJS is a server-side framework built with TypeScript, known for its module-oriented architecture inspired by Angular. In this article, I'll explain the core concepts of NestJS and show how we used them in a real SaaS product (GraphQL API / multi-tenant setup).
(*Update) ↑ I made that sound impressive, but I didn't actually work on that project much, so honestly most of this article isn't in my head lol
Table of contents
- Module
- Controller / Resolver
- Service / UseCase
- DI (Dependency Injection)
- Guard (Authentication and Authorization)
- Layered Entity Definitions
- Prisma Integration (Repository + Mapper)
- How the Auth Context Flows
- Summary: Standard NestJS vs. a Real Project
1. Module
NestJS basics
A NestJS application is organized in units called Modules. With the @Module() decorator, you define providers (services it provides), imports (modules it depends on), and exports (services it exposes to others), which together configure the DI container.
@Module({ providers: [CatService], imports: [DatabaseModule], exports: [CatService], }) export class CatModule {} In the real project
In this project, modules are split into three layers following a layered architecture.
app.module.ts ├─ ResolverModules (interface/di/) ← presentation layer ├─ UseCaseModules (app/di/) ← application layer └─ RepositoryModules (infra/prisma/di/) ← infrastructure layer The directory structure looks like this:
packages/api/src/ ├── app/ # Application layer │ ├── di/ # UseCase module definitions │ └── useCases/ # UseCase implementations ├── domain/ # Domain layer │ ├── entities/ # Domain entities and type definitions │ ├── restrictFilters/ # Permission filters │ └── common/ # Shared types and utilities ├── interface/ # Interface layer │ ├── di/ # Resolver module definitions │ ├── resolvers/ # GraphQL resolvers │ ├── schema/ # Request/response types │ └── auth/ # Auth guards ├── infra/ # Infrastructure layer │ ├── prisma/ # Repositories and mappers │ └── ... # External service integrations └── entities/ # GraphQL ObjectType definitions A ResolverModule resolves its dependencies by imports-ing UseCaseModules.
@Module({ providers: [CommentResolver], imports: [ CommentUseCaseModule, UserUseCaseModule, ], }) export class CommentResolverModule {} A UseCaseModule imports RepositoryModules and other ServiceModules.
@Module({ providers: [CommentUseCase], exports: [CommentUseCase], imports: [ PrismaCommentRepositoryModule, PrismaRoomRepositoryModule, NotificationServiceModule, ], }) export class CommentUseCaseModule {} Key point: We use NestJS's module system to enforce a clean-architecture-style dependency direction (interface → app → domain ← infra).
2. Controller / Resolver
NestJS basics
For a REST API, you use decorators like @Get() / @Post() on a @Controller().
@Controller('cats') export class CatController { @Get() findAll() { return 'All cats'; } @Post() create(@Body() dto: CreateCatDto) { ... } } For GraphQL, you use @Query() / @Mutation() / @ResolveField() on a @Resolver().
In the real project
This project uses GraphQL with a code-first approach, generating the schema automatically.
// app.module.ts GraphQLModule.forRoot<ApolloDriverConfig>({ driver: ApolloDriver, autoSchemaFile: join(process.cwd(), 'src/schema.gql'), // generated from TypeScript fieldResolverEnhancers: ['guards'], }), A resolver example:
@Resolver(() => GqlComment) export class CommentResolver { constructor(private readonly commentUseCase: CommentUseCase) {} // Query: fetch data @UseGuards(AuthGuard) @Query(() => [GqlComment]) async commentList( @Args('input') input: GetCommentListInput, @Context() context: OperationContext, ) { return this.commentUseCase.getCommentList(input, context); } // Mutation: change data @UseGuards(AuthGuard) @Mutation(() => GqlComment) async createComment( @Args('input') input: CreateCommentInput, @Context() context: OperationContext, ) { return this.commentUseCase.createComment(input, context); } // ResolveField: resolve a nested field @ResolveField('author', () => GqlUser) async getAuthor(@Parent() comment: Comment) { return this.userUseCase.findOne({ id: comment.userId }); } } Main decorators
| Decorator | Purpose |
|---|---|
@Resolver(() => Type) | Declares the class as a resolver |
@Query(() => Type) | Defines a GraphQL query |
@Mutation(() => Type) | Defines a GraphQL mutation |
@ResolveField('name', () => Type) | Resolves a nested field |
@Args('input') | Binds input arguments |
@Parent() | Accesses the parent object |
@Context() | Gets the GraphQL context (auth info, etc.) |
InputType (request type)
GraphQL input types are also defined with decorators.
@InputType() export class CreateCommentInput { @Field(() => GraphQLJSON) content: Prisma.JsonObject; @Field() roomId: string; @Field(() => [Int], { nullable: true }) imageIds?: number[]; } This automatically generates the following GraphQL schema:
input CreateCommentInput { content: JSON! roomId: ID! imageIds: [Int!] } 3. Service / UseCase
NestJS basics
You use a class with the @Injectable() decorator as a service, and gather business logic there.
@Injectable() export class CatService { constructor(private readonly catRepository: CatRepository) {} findAll() { return this.catRepository.findAll(); } } In the real project
In this project, we name these "UseCase" instead of "Service", and split classes by use case.
@Injectable() export class CommentUseCase { constructor( private readonly commentRepository: PrismaCommentRepository, private readonly roomRepository: PrismaRoomRepository, private readonly notificationService: NotificationService, ) {} async createComment(input, context: OperationContext) { // 1. Domain validation const room = CoreAssert.isNotEmpty( await this.roomRepository.findOneById({ id: input.roomId }, context), ); // 2. Create the domain entity const comment = createCommentSeed({ ...input, userId: context.executor.userId, }); // 3. Save to the DB const created = await this.commentRepository.create(comment); // 4. Notifications and external integrations await this.notificationService.send({ ... }); return created; } } Key point: Inside a UseCase, the flow is domain validation → DB save → side effects (notifications, external integrations). Repositories and external services are all injected through the constructor, which makes it very testable.
4. DI (Dependency Injection)
NestJS basics
NestJS's DI automatically resolves providers from TypeScript type information. You register an @Injectable() class in a module's providers, and it's injected automatically based on the constructor's types.
In the real project
Dependencies that cross layers are controlled with imports / exports.
Resolver → constructor(useCase: CommentUseCase) // resolved by type UseCase → constructor(repo: PrismaCommentRepository) // resolved by type On the module side:
// UseCaseModule: expose CommentUseCase to the outside @Module({ providers: [CommentUseCase], exports: [CommentUseCase], // usable from other modules imports: [PrismaCommentRepositoryModule], }) export class CommentUseCaseModule {} // ResolverModule: import the UseCaseModule to use it @Module({ providers: [CommentResolver], imports: [CommentUseCaseModule], // CommentUseCase becomes available }) export class CommentResolverModule {} When you hit a circular dependency, you work around it with forwardRef().
@Module({ imports: [forwardRef(() => RelatedModule)], }) export class SomeModule {} 5. Guard (Authentication and Authorization)
NestJS basics
You create a guard class that implements the CanActivate interface and apply it with the @UseGuards() decorator.
@Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); return validateToken(request.headers.authorization); } } In the real project
Because this project is a multi-user SaaS, we use a pattern that routes to different auth guards depending on the user type (admin / guest).
@Injectable() export class MultiUserAuthGuard implements CanActivate { constructor( private readonly adminAuthGuard: AdminAuthGuard, private readonly guestAuthGuard: GuestAuthGuard, ) {} async canActivate(context: ExecutionContext): Promise<boolean> { const ctx = GqlExecutionContext.create(context); const request = ctx.getContext().req; const userType = request.headers['x-user-type']; if (userType === 'Admin') { // JWT verification (external auth service) return this.adminAuthGuard.canActivate(context); } else if (userType === 'Guest') { // Session token verification return this.guestAuthGuard.canActivate(context); } throw new UnauthorizedException(); } } We also implement fine-grained permission control at the @ResolveField level.
@ResolveField('author', () => GqlUser) @UseGuards(UserTypesGuard) @RequiredUserTypes('ADMIN') // metadata set via a custom decorator async getAuthor(@Parent() comment: Comment) { return this.userUseCase.findOne({ id: comment.userId }); } UserTypesGuard reads that metadata with Reflector and checks permissions.
@Injectable() export class UserTypesGuard implements CanActivate { constructor(private reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { const requiredTypes = this.reflector.get<string[]>( 'requiredUserTypes', context.getHandler(), ); if (!requiredTypes) return true; const gqlContext = GqlExecutionContext.create(context); const user = gqlContext.getContext().req.user; return requiredTypes.includes(user.executor.userType); } } 6. Layered Entity Definitions
NestJS basics
In a typical NestJS application, a single entity class often serves as both the DB definition and the API definition.
In the real project
This project uses three layers of entity definitions.
| Layer | Example file | Purpose |
|---|---|---|
| GraphQL Entity | entities/Comment.entity.ts | Defines the API output type with @ObjectType() |
| Domain Entity | domain/entities/Comment/index.ts | Type-safe business model using brand types |
| Prisma Model | prisma/schema.prisma | DB schema definition |
GraphQL Entity (API layer)
@ObjectType() export class Comment { @Field(() => Int) id: number; @Field(() => GraphQLJSON) content: Prisma.JsonObject; @Field() createdAt: Date; @Field(() => [CommentImage]) commentImages: CommentImage[]; // nested field } Domain Entity (domain layer)
Brand types let you tell different kinds of IDs apart, even though they're all number.
// Brand type definition type Brand<T, U> = T & { __brand: U }; // Distinguish IDs at the type level export type CommentId = Brand<number, 'CommentId'>; export type UserId = Brand<number, 'UserId'>; // Type error: CommentId and UserId are not compatible const commentId: CommentId = 1 as CommentId; const userId: UserId = commentId; // compile error! The domain entity definition:
export type Comment = { id: CommentId; content: Prisma.JsonObject; roomId: RoomId; userId: UserId; tenantId: TenantId; createdAt: Date; updatedAt: Date; }; // Factory function export const createCommentSeed = (payload: CommentSeed): CommentSeed => { return { ...payload }; }; Prisma Model (DB layer)
model Comment { id Int @id @default(autoincrement()) content Json? roomId String Room Room @relation(fields: [roomId], references: [id], onDelete: Cascade) userId Int createdAt DateTime @default(now()) updatedAt DateTime @default(now()) @updatedAt } Key point: Splitting into three layers means API spec changes don't affect domain logic, and DB schema changes don't leak into the API layer.
7. Prisma Integration (Repository + Mapper)
NestJS basics
In NestJS, it's common to use TypeORM or Prisma directly from services.
In the real project
This project uses a Repository + Mapper pattern to convert Prisma types into domain types.
Repository
@Injectable() export class PrismaCommentRepository { async create(input: CommentSeed, db = client): Promise<Comment> { const prismaComment = await db.comment.create({ data: { contentJson: input.content, roomId: input.roomId, }, include: { Room: true }, }); // Convert Prisma type → domain type return PrismaCommentMapper.toDomainComment(prismaComment); } async findList(input, context, db = client): Promise<Comment[]> { const results = await db.comment.findMany({ where: { roomId: input.roomId, Room: { tenantId: context.tenantId }, // tenant isolation }, orderBy: { createdAt: 'asc' }, }); return results.map(PrismaCommentMapper.toDomainComment); } } Mapper
export class PrismaCommentMapper { static toDomainComment(prismaComment): Comment { return { id: prismaComment.id as CommentId, content: prismaComment.contentJson as Prisma.JsonObject, roomId: prismaComment.roomId as RoomId, userId: prismaComment.userId as UserId, tenantId: prismaComment.Room.tenantId as TenantId, createdAt: prismaComment.createdAt, updatedAt: prismaComment.updatedAt, }; } } Transactions
Operations that span multiple tables use prisma.$transaction() to guarantee atomicity.
const result = await prisma.$transaction(async (db) => { const room = await this.roomRepository.create(roomData, context, db); await this.memberRepository.create(memberData, db); return room; }); Source:https://dev.to/kaziusan/nestjs-core-architecture-and-how-we-used-it-in-a-real-project-1fll