DEV Community

Kaziu
Kaziu

Posted on Edited on

NestJS Core Architecture and How We Used It in a Real Project

※ 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

  1. Module
  2. Controller / Resolver
  3. Service / UseCase
  4. DI (Dependency Injection)
  5. Guard (Authentication and Authorization)
  6. Layered Entity Definitions
  7. Prisma Integration (Repository + Mapper)
  8. How the Auth Context Flows
  9. 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 {}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

A ResolverModule resolves its dependencies by imports-ing UseCaseModules.

@Module({
  providers: [CommentResolver],
  imports: [
    CommentUseCaseModule,
    UserUseCaseModule,
  ],
})
export class CommentResolverModule {}
Enter fullscreen mode Exit fullscreen mode

A UseCaseModule imports RepositoryModules and other ServiceModules.

@Module({
  providers: [CommentUseCase],
  exports: [CommentUseCase],
  imports: [
    PrismaCommentRepositoryModule,
    PrismaRoomRepositoryModule,
    NotificationServiceModule,
  ],
})
export class CommentUseCaseModule {}
Enter fullscreen mode Exit fullscreen mode

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) { ... }
}
Enter fullscreen mode Exit fullscreen mode

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'],
}),
Enter fullscreen mode Exit fullscreen mode

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 });
  }
}
Enter fullscreen mode Exit fullscreen mode

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[];
}
Enter fullscreen mode Exit fullscreen mode

This automatically generates the following GraphQL schema:

input CreateCommentInput {
  content: JSON!
  roomId: ID!
  imageIds: [Int!]
}
Enter fullscreen mode Exit fullscreen mode

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 {}
Enter fullscreen mode Exit fullscreen mode

When you hit a circular dependency, you work around it with forwardRef().

@Module({
  imports: [forwardRef(() => RelatedModule)],
})
export class SomeModule {}
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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 });
}
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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 };
};
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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,
    };
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
});
Enter fullscreen mode Exit fullscreen mode

Key point: Repository methods take an optional db argument, so they're designed to work both inside a transaction and standalone.


8. How the Auth Context Flows

This is how auth information propagates in a multi-tenant SaaS.

1. GraphQL request
   ├─ Header: Authorization: "Bearer <JWT>"
   └─ Header: x-user-type: "Admin" or "Guest"

2. Guard (authentication)
   ├─ Admin → verify JWT → build OperationContext
   └─ Guest → verify session → build OperationContext
   └─ set request.user = OperationContext

3. Resolver
   └─ get it via @Context() context: OperationContext

4. UseCase / Repository
   └─ use the context for permission control and tenant isolation
Enter fullscreen mode Exit fullscreen mode

OperationContext is defined type-safely with a Zod schema.

export const operationContextSchema = z.object({
  tenantId: tenantIdSchema,
  executor: z.union([
    z.object({
      userType: z.literal('ADMIN'),
      userId: userIdSchema,
      role: roleSchema,
    }),
    z.object({
      userType: z.literal('GUEST'),
      userId: userIdSchema,
    }),
  ]),
});

export type OperationContext = z.infer<typeof operationContextSchema>;
Enter fullscreen mode Exit fullscreen mode

It's injected into resolvers with the custom @Context() decorator.

export const Context = createParamDecorator(
  (data: unknown, context: ExecutionContext) => {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req.user as OperationContext;
  },
);
Enter fullscreen mode Exit fullscreen mode

Permission filters handle tenant isolation in DB operations.

export const commentRestrictFilter = (
  context: OperationContext,
): Prisma.CommentWhereInput[] => {
  return [{ Room: { tenantId: context.tenantId } }];
};

// Usage
const comments = await prisma.comment.findMany({
  where: { AND: commentRestrictFilter(context) },
});
Enter fullscreen mode Exit fullscreen mode

9. Summary: Standard NestJS vs. a Real Project

Aspect Standard NestJS Real project
API style REST (@Controller) GraphQL code-first (@Resolver)
Business logic Service UseCase (split by use case)
Data access ORM used directly Repository + Mapper pattern
Auth Single guard Guard that routes by user type
Type safety Standard TypeScript Brand types + Zod validation
Tenant isolation None OperationContext + RestrictFilter
Entity Single definition 3 layers (GraphQL / Domain / Prisma)
Module structure By feature By layer (Resolver / UseCase / Repository)

Wrapping up

NestJS is powerful enough out of the box, but it's also flexible enough to customize the architecture to fit a project's size and requirements.

In this project, we built on NestJS's DI system and added a few things:

  • Layered architecture: separate layers by module and control the dependency direction
  • Code-first GraphQL: generate the schema automatically from TypeScript decorators
  • Brand types: catch mixed-up IDs at compile time
  • RestrictFilter: turn multi-tenant data isolation into a reusable pattern

Once you understand the core NestJS concepts (Module / DI / Guard / Decorator), extending it to fit your project's needs is easy. I hope this helps.

Top comments (0)