Interceptor
ELI5 — The Vibe Check
An interceptor catches requests and responses on the way in and out, letting you transform them. It's like a translator at a meeting — they intercept what's said, modify it if needed, and pass it along. In NestJS, interceptors handle logging, caching, and response mapping.
Real Talk
An interceptor is a component that intercepts incoming requests or outgoing responses to add cross-cutting behavior. In NestJS, interceptors can transform responses, add extra logic before/after method execution, extend behavior with caching, and override exceptions. They wrap the execution stream using RxJS observables, enabling both pre- and post-processing.
Show Me The Code
@Injectable()
class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
const start = Date.now();
return next.handle().pipe(
tap(() => console.log(`${Date.now() - start}ms`))
);
}
}
When You'll Hear This
"Add a logging interceptor to measure response times on all endpoints." / "The transform interceptor wraps all responses in a standard { data, meta } format."
Related Terms
Decorator (Backend)
A backend decorator wraps a function or class to add extra behavior without modifying the original.
Guard
A guard in NestJS is a gatekeeper that decides if a request should be allowed through. Auth guards check if you're logged in.
Middleware
Middleware is like a security checkpoint at an airport.
NestJS
NestJS is Node.js with structure. Plain Express can get messy in large projects.