Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

345
Views
NestJS - Access user from Guard

I've been following the official NestJS documentation. I have successfully setup JWT passport authentication. I can access the user details from the @Req within controllers but I'm having issues accessing the user details from within the custom guard.

This works fine

@UseGuards(RolesGuard)
@Get('me')
  getProfile(@Request() req) {
    return req.user;
  }

This does not (curently logging for debug)

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      console.log('No Roles');
      return true;
    }
    const request = context.switchToHttp().getRequest();
    
    // Returns Undefined 
    console.log(request.user);
    return true;
  }
}

This is how I'm declaring each entry in the controller

  @Get()
  @UseGuards(RolesGuard)
  @Roles('admin')
  findAll() {
    return this.usersService.findAll();
  }

The pass through of roles metadata is working fine, just looks like the user isn't being appended to the context at the correct step.

Any help would be great, thanks!

EDIT: updated @UseGuards(RolesGuard), copied and pasted wrong version

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The issue is you are not using the rolesGuard :

@UseGuards(JwtAuthGuard) // <= replace JwtAuthGuard with your guard: RolesGuard 
@Get('me')
getProfile(@Request() req) {
return req.user;
 }

the same for the second method.

over 4 years ago · Santiago Trujillo Report

0

Looks like i've fixed it, have to chain them

@Get()
  @Roles('admin')
  @UseGuards(JwtAuthGuard, RolesGuard)
  findAll() {
    return this.usersService.findAll();
  }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!