When APIs feel slow, most developers start by blaming the database or trying to "optimize the code."
But here’s a better first step: instrument your endpoints and find out exactly where the delays are.
What should you be asking instead?
- Which endpoints are consistently slow?
- Which services take the longest to resolve?
- Are response times spiking under certain conditions?
This kind of visibility is where NestJS Interceptors come in handy — and they’re seriously underrated.
🧠 What are NestJS Interceptors?
Interceptors in NestJS let you hook into the request-response cycle.
You can run logic before or after a request is handled.
They’re perfect for:
- Logging
- Transforming responses
- Caching
- Measuring execution time
And the best part? You can do this without touching your business logic.
🛠 Example: Measuring API Execution Time
Let’s create a custom MetricsInterceptor
to log how long each endpoint takes:
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';
@Injectable()
export class MetricsInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable {
const now = Date.now();
const req = context.switchToHttp().getRequest();
const method = req.method;
const url = req.url;
return next.handle().pipe(
tap(() => {
const timeTaken = Date.now() - now;
console.log(`[${method}] ${url} took ${timeTaken}ms`);
// Optionally push to Sentry, Datadog, Prometheus, etc.
}),
);
}
}
You can apply this:
- Globally
- Per controller
- On specific routes
Why do this?
- You measure what actually matters
- You catch performance outliers (e.g. admin-only or rarely used endpoints)
- You keep observability separate from your main code
- You reduce blind spots
It’s also a great way to complement tools like Sentry or Datadog — especially when you need internal visibility fast.
Some real-world use cases:
- Track slow DB or third-party calls per endpoint
- Set up alerts on endpoints crossing thresholds
- Visualize which modules need refactoring
- Add tags to identify patterns in traffic vs. performance
NestJS Interceptors are a powerful yet lightweight way to gain observability into your backend APIs. No magic. No overhead. Just TypeScript and good architecture.
How do you handle monitoring in your nestjs projects?