Search code examples
javascriptexpressnestjsfastify

In NestJS is there any way to pass data from Guards to the controller?


So I am currently using NestJS extensively in my organization. And for authentication purposes we are using our own guards. So my question is that can anyone please guide me if there any way to pass data from guard to the controller, other than response.locals of expressjs? This is creating an hard dependency on the framework and I don't want that at this moment.

TIA.


Solution

  • Instead of using the Guard, you can create your custom decorator to get the data:

    export const Authorization = createParamDecorator((_, request: any) => {
      const { authorization: accessToken } = request.headers;
      try {
        const decoded = jwt.verify(accessToken, process.env.JWT_HASH);
        return pick(decoded, 'userId');
      } catch (ex) {
        throw new InvalidToken();
      }
    });
    
    export interface AuthUser {
      userId: string;
    }
    

    And pass to your controller like this:

      @Post()
      createFeedback(
        @Body() body: FeedbackBody,
        @Authorization() user: AuthUser,
      ): Promise<Feedback> {
        body.userId = user.userId;
        return this.feedbackService.feedback(body, user);
      }
    

    This can act as a guard because when your token is invalid, it will throw an exception