Skip to content Skip to sidebar Skip to footer

Howto Get Req.user In Services In Nest Js

In a controller, I add the user object with a guard, inject some service and call that service to get some response. I have removed a lot of code for brevity. @Controller() @UseGua

Solution 1:

Update March 2019

Since version v6, you can now inject the request object into a request-scoped provider:

import { REQUEST } from'@nestjs/core';
import { Request } from'express';

@Injectable({ scope: Scope.REQUEST })
exportclassUsersService {
  constructor(@Inject(REQUEST) privatereadonly request: Request) {}
}

Outdated answer

It's not possible to inject the user (or request) directly into the service. Nest.js does not yet support request-scoped providers. This might change with version 6. Until then, a service does not know anything about a request.

Logged in user

You can create a custom decorator@User. Using a decorator is preferable over injecting the request object because then a lot of nest's advantages get lost (like inceptors and exception filters).

exportconstUser = createParamDecorator((data, req) => {
  return req.user;
});

And then use it like this:

@UseGuards(AuthGuard()) 
@Get(':id)
async findOne(@Param('id') id, @User() user) {
   returnawaitthis.userService.findOne(id, user);
}

Roles

You can create a RolesGuard that makes sure the logged in user has the required roles. For details, see this answer.

Post a Comment for "Howto Get Req.user In Services In Nest Js"