2

I have applied authentication in NestJS middlewares and decoding all the information from user token by the third party API.

Now I have got the information in my middleware, how can I send that information to controllers and services?

Abhishek Kumar
  • 820
  • 12
  • 16

1 Answers1

3

It is normal for middlewares to add information to the request object (eg. adding a user object).

For a clean way to extract information from the request object and inject it into the controller you can make a custom route decorator

For example, extracting the user:

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const User = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
);

And then in your controller

@Get()
async findOne(@User() user: UserEntity) {
  console.log(user);
}

From there you can just ensure that your service methods receive the User as a regular method parameter

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
  • So, if I am using a guard, and it autorizes the requesting user, I can add some metadata on to the request object and then return true from the guard? – thewebjackal Aug 09 '22 at 17:10