NestJS - GuardsHow can you combine a guard with a custom decorator to restrict access based on user permissions in NestJS?AApply the guard only on the decorator functionBCreate a decorator to set metadata, then read it in the guard via ReflectorCUse the decorator to throw errors directly without a guardDUse the decorator to modify the request object directlyCheck Answer
Step-by-Step SolutionSolution:Step 1: Understand metadata usageCustom decorators set metadata on routes or controllers.Step 2: Guard reads metadataGuards use Reflector to read metadata and decide access.Step 3: Eliminate incorrect optionsThrowing errors in decorators or modifying requests directly is not standard; guards control access.Final Answer:Create a decorator to set metadata, then read it in the guard via Reflector -> Option BQuick Check:Decorator sets metadata, guard reads it = C [OK]Quick Trick: Use Reflector in guards to read decorator metadata [OK]Common Mistakes:Throwing errors in decoratorsModifying requests in decoratorsApplying guards incorrectly
Master "Guards" in NestJS9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallPerf
More NestJS Quizzes Authentication - Local strategy (username/password) - Quiz 8hard Authentication - Why authentication secures NestJS APIs - Quiz 13medium Database with Prisma - CRUD with Prisma - Quiz 6medium Database with Prisma - CRUD with Prisma - Quiz 8hard Database with Prisma - Prisma setup in NestJS - Quiz 9hard Guards - Reflector and custom decorators - Quiz 14medium Interceptors - Exception mapping interceptor - Quiz 11easy Pipes - Custom pipes - Quiz 10hard Pipes - Custom pipes - Quiz 12easy Pipes - Custom pipes - Quiz 11easy