I'm using Nest version ^6.7.2
I'm trying to create a createParamDecorator that gets the req.user value from a request.
Inside the createParamDecorator, the req.user has a value, however when I try to get the value in a controller by using the decorator the value is undefined.
const AuthSession = createParamDecorator((data, req) => {
console.log(req.user); // session data
return req.user;
});
Controller()
export default class AuthController {
@Get("/token/ping")
@UseGuards(AuthGuard("jwt"))
tokenPing(@AuthSession() session: Session) {
console.log(session); // undefined
return session;
}
}
Edit: I just tried updating to nestjs v7 and I'm having the same issue
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
const AuthSession = createParamDecorator((data: any, ctx: ExecutionContext) => {
return { message: "asdf" };
});
export default AuthSession;
@Controller()
export default class AuthController {
@Get("/token/ping")
@UseGuards(AuthGuard("jwt"))
tokenPing(@AuthSession() session: Session) {
console.log(session); // undefined
return session;
}
}
you can get the information firs from ExecutionContext:
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const User = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.user;
},
);
check the example in the doc : Custom decorator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With