Howto get req.user in services in Nest JS

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 })
export class UsersService {
  constructor(@Inject(REQUEST) private readonly 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 interceptors and exception filters).

export const User = createParamDecorator((data, req) => {
  return req.user;
});

And then use it like this:

@UseGuards(AuthGuard()) 
@Get(':id')
async findOne(@Param('id') id, @User() user) {
   return await this.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.

Leave a Comment