🦅 NestJS
Beginner
What are Guards in NestJS?
Answer
Guards are classes decorated with @Injectable() that implement the CanActivate interface. They determine whether a request should be handled by the route handler based on conditions like authentication or authorization. The canActivate() method returns true (allow) or false (deny with 403 Forbidden). Apply guards with @UseGuards(AuthGuard) at controller, method, or global level. The most common use is JWT authentication: extract and verify the token from the request header, attach the user to the request object. Guards execute after all middleware but before interceptors and pipes. NestJS also has built-in support for Passport.js via @nestjs/passport.