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?
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