- Published
- Author
- Sudeep
Understanding
Today I learned how
While building a custom
Why It Matters:
•
• You can switch between different transport layers (HTTP, RPC, WebSockets) using methods like
• It's essential for building dynamic and context-aware logic in guards, interceptors, and decorators.
Pro Tip:
Use
#CCT1JMA0Z #NestJS
ExecutionContext in NestJS GuardsToday I learned how
ExecutionContext works in NestJS — it's a powerful tool for accessing low-level request details within Guards, Interceptors, and Custom Decorators.While building a custom
AuthGuard, I used ExecutionContext to extract the request object and retrieve the authenticated user like so:Code
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const user = request.user;
return !!user; // or apply custom authorization logic
}
}Why It Matters:
•
ExecutionContext wraps the current request lifecycle and gives you flexible access to request-specific information.• You can switch between different transport layers (HTTP, RPC, WebSockets) using methods like
switchToHttp(), switchToRpc(), etc.• It's essential for building dynamic and context-aware logic in guards, interceptors, and decorators.
Pro Tip:
Use
context.getClass() and context.getHandler() to access metadata about the controller and handler being executed — especially useful for implementing role-based access control or custom permission systems.#CCT1JMA0Z #NestJS