Introduction
Backend observability isn’t optional—it’s the difference between a system that gracefully handles traffic spikes and one that collapses under pressure. For NestJS applications, real-time tracing with Lescopr APM transforms raw logs into actionable insights, helping you identify latency bottlenecks, trace errors across microservices, and maintain Service Level Agreements (SLAs). This guide walks you through integrating Lescopr APM into a NestJS project, from initial setup to deployment, ensuring you capture every request’s lifecycle with precision.
By the end of this guide, you’ll have:
- A NestJS application instrumented with Lescopr APM
- Real-time tracing enabled for all HTTP endpoints
- Customized dashboards to monitor performance metrics
- A deployment-ready configuration for production environments
Let’s begin.
Prerequisites: What You’ll Need
Before diving into integration, ensure your environment meets these requirements:
- A NestJS project (v7.x or later)
- Node.js (v16.x or higher)
- npm or yarn for dependency management
- A Lescopr APM account (sign up here for a free trial)
- Basic familiarity with JavaScript/TypeScript and NestJS modules
If you’re starting fresh, initialize a NestJS project using:
nest new my-nestjs-app
cd my-nestjs-app
Step 1: Installing Lescopr APM Agent
The first milestone is installing the Lescopr APM agent. Unlike generic logging libraries, Lescopr’s agent is designed for distributed tracing, meaning it tracks requests across services, databases, and external APIs.
1.1 Add the Lescopr Agent to Your Project
In your NestJS project directory, install the Lescopr agent via npm:
npm install @lescopr/apm
1.2 Initialize the Agent in Your Application
Lescopr requires an initialization step to configure tracing. Create or modify your main.ts file to include the agent setup:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { APM } from '@lescopr/apm';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Initialize Lescopr APM
APM.init({
applicationName: 'MyNestJSApp',
serviceType: 'node',
environment: process.env.NODE_ENV || 'development',
agentUrl: 'https://agent.lescopr.com',
apiKey: 'YOUR_LESCOPR_API_KEY',
});
await app.listen(3000);
}
bootstrap();
Key Configuration Notes:
- Replace
YOUR_LESCOPR_API_KEYwith your actual Lescopr API key (found in your Lescopr dashboard). - The
serviceType: 'node'flag ensures Lescopr tailors tracing behavior to Node.js/NestJS. - For production, set
environment: 'production'and consider adding error tracking viaAPM.enableErrorTracking().
Step 2: Enabling Tracing for HTTP Endpoints
With the agent installed, the next step is to enable tracing for all HTTP routes. Lescopr automatically instruments NestJS’s built-in HTTP layer, but you can customize tracing behavior for specific controllers.
2.1 Automatic Tracing for Controllers
Lescopr’s agent automatically traces all HTTP requests handled by NestJS controllers. For example, a simple UsersController will now generate traces for every GET, POST, etc., request:
// src/users/users.controller.ts
import { Controller, Get } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get()
findAll() {
return { message: 'List of users' };
}
}
2.2 Customizing Trace Attributes
To enrich traces with business-specific metadata, use Lescopr’s APM.setCustomAttribute() method. For instance, tag requests with user roles or request sources:
import { APM } from '@lescopr/apm';
@Controller('users')
export class UsersController {
@Get()
findAll(@Req() request: Request) {
APM.setCustomAttribute('user_role', request.headers['x-user-role'] || 'guest');
return { message: 'List of users' };
}
}
Why This Matters: Custom attributes help you filter traces in Lescopr’s dashboard, isolating issues tied to specific user roles or request types.
Step 3: Configuring Error Tracking and Performance Monitoring
Real-time tracing is useless without visibility into errors and performance anomalies. Lescopr’s agent includes built-in support for both.
3.1 Enabling Error Tracking
Uncaught exceptions and HTTP errors are automatically captured. To ensure no error slips through, enable global error tracking in your main.ts:
APM.init({
// ... existing config
enableErrorTracking: true,
});
Lescopr will now correlate errors with their corresponding traces, showing you the full request flow leading to the failure.
3.2 Setting Up Performance Thresholds
Define alerting thresholds for slow endpoints. For example, flag requests taking longer than 500ms as potential bottlenecks:
APM.setPerformanceThreshold('http.request.duration', 500);
Lescopr will automatically alert you via Slack, email, or your preferred integration when thresholds are breached.
Step 4: Advanced Tracing for Databases and External Calls
Most latency issues stem from database queries or third-party APIs. Lescopr’s agent automatically traces these calls, but you can manually instrument them for finer control.
4.1 Tracing Database Queries
For TypeORM or Sequelize, Lescopr integrates seamlessly. Example with TypeORM:
import { APM } from '@lescopr/apm';
// Wrap database queries in a transaction scope
APM.startTransaction('database.query');
try {
const users = await this.userRepository.find();
APM.endTransaction();
} catch (error) {
APM.endTransaction(error);
throw error;
}
4.2 Tracing External HTTP Calls
For HTTP clients like axios or fetch, use Lescopr’s APM.traceHttpCall():
import { APM } from '@lescopr/apm';
import axios from 'axios';
async function fetchData() {
const span = APM.traceHttpCall('external.api.call', {
url: 'https://api.example.com/data',
method: 'GET',
});
try {
const response = await axios.get('https://api.example.com/data');
span.end();
return response.data;
} catch (error) {
span.end(error);
throw error;
}
}
Why This Matters: Manual tracing ensures end-to-end visibility, even when calls are made asynchronously or in middleware.
Step 5: Deploying and Validating the Setup
With tracing enabled, the final step is deploying your application and verifying the integration.
5.1 Deploying to Production
Ensure your main.ts uses the production environment and secure API key:
APM.init({
applicationName: 'MyNestJSApp',
serviceType: 'node',
environment: 'production',
agentUrl: 'https://agent.lescopr.com',
apiKey: process.env.LESCOPR_API_KEY, // Use env vars in production
});
5.2 Validating Traces in Lescopr Dashboard
After deployment, navigate to your Lescopr dashboard to confirm:
- Traces are appearing for all HTTP endpoints.
- Error rates are accurately reflected.
- Performance thresholds are triggering alerts (if configured).
Example Dashboard View: A sample trace in Lescopr will show:
- Request duration
- Database query times
- External API latency
- Custom attributes (e.g.,
user_role)
Step 6: Optimizing with Lescopr Dashboards
Lescopr’s dashboards turn raw traces into actionable insights. Key features include:
6.1 Custom Dashboards for SLA Monitoring
Create dashboards to track SLA compliance (e.g., 99.9% uptime) with metrics like:
- Error rates per endpoint
- Latency percentiles (P95, P99)
- Throughput (requests per second)
6.2 Correlating Traces with Errors
Lescopr’s error tracking integrates with traces, showing you:
- The exact request that caused an error
- Stack traces with context
- Affected users or sessions
6.3 Alerting on Anomalies
Set up alerts for:
- Sudden spikes in error rates
- Latency exceeding thresholds
- Unusual traffic patterns
Conclusion: From Setup to Observability
Integrating Lescopr APM with NestJS transforms your backend from a black box into a fully observable system. By following this guide, you’ve:
- Installed and configured the Lescopr agent
- Enabled real-time tracing for all HTTP endpoints
- Set up error tracking and performance monitoring
- Validated the setup in production
- Optimized dashboards for SLA compliance
Next Steps: To go further, Lescopr’s documentation covers step-by-step setup, including advanced configurations for Kubernetes, serverless, and multi-service architectures. For a deeper dive into distributed tracing or GDPR-compliant consent management, explore Lescopr’s product analytics and observability features.
Ready to see your NestJS application’s performance in real time? Start your free trial of Lescopr APM.