...

/

Getting the Current User with a Custom Decorator

Getting the Current User with a Custom Decorator

Learn how to create a custom decorator in NestJS.

After setting up our guard and assigning the user to the request object in our application, we need to access this user data in our controllers. This section will explore efficiently retrieving user data using a custom decorator.

Implementation

Suppose we need to directly access user data from the request object in the findBooks method of our BooksController. Let’s see how to do that in the following code:

Directly accessing user data in BooksController using @Req() decorator of @nestjs/common
Collection
Get list of books
Sign-up
Sign-in
KeyValueDescription
RESPONSE
Status: ---Size: ---Time: ---

Enter the URL and click Send to get a response

Press “Run” to start the development server.

Note: Before using the get list of books endpoint, it’s essential to log in to the application. Start by registering with the sign-up request and then log in using the sign-in request to obtain your access token. Once you have the token, include it in the authorization headers for the get list of books request, formatted as Bearer <token> ...