Home Projects Portfolio Dashboard Export PDF Log in

Building Secure User-Specific Endpoints in NestJS: A Team Data Example

In the Acelerador-2.0 project, enabling users to efficiently view their associated teams was a key requirement. This involved creating a secure, authenticated endpoint that could differentiate between a user's roles (participant or mentor) and retrieve only the relevant team information.

The Challenge: Secure, Role-Aware Data Retrieval

The core problem was not just fetching team data, but ensuring that each user could only access teams they were legitimately part of. This required:

  1. Authentication: Verifying the user's identity before any data access.
  2. Authorization: Filtering data based on the authenticated user's ID and their specific role within the application (e.g., as a participant or a mentor).
  3. Data Structuring: Presenting the complex team, member, and project data in a clear, consistent format through Data Transfer Objects (DTOs).
  4. API Documentation: Providing an easy way for other developers to understand and test the new endpoint.

Crafting the Solution with NestJS

Our approach leveraged NestJS's modular architecture, TypeORM for database interactions, and JWT for secure authentication. The solution integrated several key components:

1. Data Transfer Objects (DTOs)

We defined specific DTOs, like TeamDetailResponseDto, to shape the outgoing data. This ensures consistency and clarity for API consumers.

// team-detail-response.dto.ts
export class MemberDto {
  readonly id: string;
  readonly name: string;
  readonly role: 'participant' | 'mentor';
}

export class ProjectDto {
  readonly id: string;
  readonly name: string;
  readonly description: string;
}

export class TeamDetailResponseDto {
  readonly id: string;
  readonly name: string;
  readonly description: string;
  readonly members: MemberDto[];
  readonly projects: ProjectDto[];
}

2. Service Layer: Role-Based Filtering

The TeamService contained the core logic for findMyTeams(userId: string, role?: 'participant' | 'mentor'). This method interacts with the TeamRepository (part of the Repository Pattern facilitated by TypeORM) to fetch teams, dynamically adjusting the query based on the userId and an optional role parameter.

// team.service.ts simplified
@Injectable()
export class TeamService {
  constructor(
    @InjectRepository(TeamEntity) // TypeORM Repository
    private readonly teamRepository: Repository<TeamEntity>,
  ) {}

  async findMyTeams(userId: string, role?: 'participant' | 'mentor'): Promise<TeamDetailResponseDto[]> {
    let query = this.teamRepository.createQueryBuilder('team')
      .leftJoinAndSelect('team.members', 'member')
      .leftJoinAndSelect('team.projects', 'project')
      .where('member.userId = :userId', { userId });

    if (role) {
      query = query.andWhere('member.role = :role', { role });
    }

    const teams = await query.getMany();
    // Map TeamEntity to TeamDetailResponseDto
    return teams.map(team => ({ /* ... mapping logic ... */ }));
  }
}

3. Controller: Endpoint Protection and User Context

The TeamController exposed the GET /team/mine endpoint. It's protected using JwtAuthGuard to ensure only authenticated users can access it. The user's ID is extracted from the JWT token and passed to the service layer.

// team.controller.ts simplified
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('team')
export class TeamController {
  constructor(private readonly teamService: TeamService) {}

  @Get('mine')
  async getMyTeams(@Req() req): Promise<TeamDetailResponseDto[]> {
    const userId = req.user.id; // User ID from JWT payload
    return this.teamService.findMyTeams(userId);
  }
}

4. Swagger Integration

Basic Swagger configuration was added to main.ts, including BearerAuth for authentication. This significantly improved the developer experience by providing interactive API documentation, making it easy to test the protected endpoint directly from a web browser.

Actionable Takeaway

When building secure, user-specific API endpoints in NestJS, combine JwtAuthGuard for authentication, robust service logic for role-based data filtering using TypeORM's Repository pattern, and well-defined DTOs for consistent response structures. Don't forget to integrate Swagger for streamlined documentation and testing, enhancing developer productivity.


Generated with Gitvlg.com

Building Secure User-Specific Endpoints in NestJS: A Team Data Example
Daniela Homobono

Daniela Homobono

Author

Share: