Authorization Logic: Guard vs Interceptor for Request Filtering
26K reputation · 23 Apr 2022, 10:44 UTC
Request Lifecycle Design
When implementing access control in a NestJS application (v10+), there is a design choice between using Guards and Interceptors to handle authorization logic. While both can intercept incoming requests, they operate at different stages of the request pipeline.
Constraints and Trade-offs
Guards are executed before Interceptors and are designed specifically to return a boolean indicating whether a request should proceed. In contrast, Interceptors have access to the RxJS stream, allowing them to manipulate the response after the handler has executed.
Using an Interceptor for authorization allows for more complex logic that might depend on the response, but it may result in higher resource consumption because the request has already passed through the Guard layer and entered the Interceptor chain.
- Guards: Early exit, lower overhead, no access to response stream.
- Interceptors: Access to both request and response, RxJS integration, later execution.
Which approach is more sustainable for high-throughput endpoints where authorization depends on request metadata but must minimize handler execution overhead? Under what specific conditions should authorization be deferred to an Interceptor rather than a Guard?