With over 15 years in engineering and 8 years of experience with both Sentry and Azure Application Insights, I’ve refined my approach to monitoring and debugging applications at scale. My focus has always been on building robust, scalable, and observable systems that provide actionable insights into user behavior and performance.
Introduction
Modern web applications require robust monitoring to ensure optimal performance, diagnose errors, and improve user experience. In this guide, we’ll explore how to integrate LogRocket, Azure Application Insights, and Sentry into a React TypeScript application, ensuring they share the same session, correlation ID, and user ID for seamless tracking.
By the end of this article, you will:
✔ Understand why real-time monitoring is crucial.
✔ Learn how to set up LogRocket, Azure Application Insights, and Sentry in React.
✔ Ensure all monitoring tools share a common user session and correlation ID.
✔ Gain insights into why combining these tools is a game-changer for your application.
Why Use LogRocket, Azure Application Insights, and Sentry Together?
Before jumping into implementation, let’s explore why using these three tools together provides a complete monitoring solution.
1. LogRocket – Session Replay and Frontend Performance Monitoring
✅ Replays User Sessions – LogRocket records user interactions, providing a video-like playback to understand user actions leading to issues.
✅ UI & Redux Monitoring – Helps developers debug UI state changes, making it easier to pinpoint frontend issues.
✅ Network and Console Logs – Captures API calls, errors, and warnings for in-depth debugging.
2. Azure Application Insights – Backend and Telemetry Monitoring
✅ Detects Performance Bottlenecks – Tracks API latency, database queries, and server health.
✅ Application-Wide Logging – Logs backend errors, making it useful for diagnosing full-stack issues.
✅ Tracks User Journeys – Provides telemetry data on how users navigate your app.
3. Sentry – Error Tracking and Crash Reporting
✅ Captures JavaScript Errors – Monitors and logs React errors in real time.
✅ Distributed Tracing – Helps track requests from frontend to backend to see where failures occur.
✅ Alerts & Insights – Notifies developers when issues arise.
Why Use All Three Together?
When combined, these tools provide a 360-degree view of application performance:
✔ Frontend Monitoring (LogRocket) + Backend Insights (Azure) + Error Tracking (Sentry) = Comprehensive Application Monitoring
Step-by-Step Guide to Integration
1. Install Required Dependencies
In your React TypeScript project, install the required monitoring libraries:
npm install @sentry/react logrocket @microsoft/applicationinsights-web uuid
2. Set Up Monitoring in monitoring.ts
Create a new file src/monitoring.ts
to initialize LogRocket, Azure Application Insights, and Sentry, ensuring they share the same session ID and correlation ID.
import LogRocket from 'logrocket';
import * as Sentry from '@sentry/react';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { v4 as uuidv4 } from 'uuid';
// Generate session and correlation ID
const sessionId = getSessionId();
const correlationId = uuidv4();
// Initialize LogRocket
LogRocket.init('your-logrocket-app-id'); // Replace with your LogRocket ID
// Initialize Azure Application Insights
const appInsights = new ApplicationInsights({
config: {
instrumentationKey: 'your-azure-app-insights-key', // Replace with your Azure Key
enableAutoRouteTracking: true,
}
});
appInsights.loadAppInsights();
// Initialize Sentry
Sentry.init({
dsn: 'your-sentry-dsn', // Replace with your Sentry DSN
integrations: [Sentry.reactRouterV6BrowserTracingIntegration(), Sentry.replayIntegration()],
tracesSampleRate: 1.0,
tracePropagationTargets: ['localhost', /^https:\/\/yourserver\.io\/api/],
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
release: "your-app-version@" + import.meta.env.VITE_VERSION,
environment: import.meta.env.VITE_ENV,
});
// Assign user data for monitoring
export const setMonitoringUser = (user: { id: string; email?: string }) => {
if (!user) return;
LogRocket.identify(user.id, { email: user.email, sessionId, correlationId });
appInsights.context.user.id = user.id;
appInsights.context.session.id = sessionId;
Sentry.setUser({ id: user.id, email: user.email });
};
// Generate or retrieve session ID
function getSessionId(): string {
let sessionId = localStorage.getItem('sessionId');
if (!sessionId) {
sessionId = uuidv4();
localStorage.setItem('sessionId', sessionId);
}
return sessionId;
}
export { sessionId, correlationId, appInsights };
3. Modify api.ts
to Include Correlation ID in Requests
Modify your Axios API configuration to include the correlationId
and sessionId
in all requests.
import axios, { AxiosInstance, AxiosHeaders, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { correlationId, sessionId } from './monitoring';
const api: AxiosInstance = axios.create();
api.interceptors.request.use(
(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
if (!config.headers) {
config.headers = new AxiosHeaders();
}
config.headers.set('CorrelationId', correlationId);
config.headers.set('SessionId', sessionId);
config.headers.set('Timestamp', new Date().toISOString());
return config;
},
(error) => Promise.reject(error)
);
export { api };
4. Update AuthContext.tsx
to Track Users
Ensure that LogRocket, Azure, and Sentry receive user ID and session details when a user logs in.
import React, { createContext, useState, useEffect, useContext, ReactNode } from "react";
import { getSessionId, setMonitoringUser } from "../monitoring";
const AuthContext = createContext<AuthContextType | undefined>(undefined);
const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [user, setUser] = useState<UserDto | null>(null);
useEffect(() => {
const fetchUser = async () => {
const response = await fetch("/.auth/me");
if (!response.ok) return setUser(null);
const data = await response.json();
const clientPrincipal = data.clientPrincipal;
if (clientPrincipal?.userId) {
const newUser = { id: clientPrincipal.userId, email: clientPrincipal.userDetails };
setUser(newUser);
setMonitoringUser(newUser);
}
};
fetchUser();
}, []);
return <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>;
};
export { AuthProvider };
5. Ensure monitoring.ts
is Imported in index.tsx
Make sure monitoring is initialized in your app's entry file.
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { AuthProvider } from "./context/AuthContext";
import "./monitoring";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<AuthProvider>
<App />
</AuthProvider>
</React.StrictMode>
);
Final Thoughts: Why This Approach is Essential
By integrating LogRocket, Azure Application Insights, and Sentry together, we achieve:
✔ Frontend session replay (LogRocket)
✔ Backend performance monitoring (Azure App Insights)
✔ Error tracking and distributed tracing (Sentry)
This unified monitoring strategy allows teams to quickly detect, analyze, and resolve issues, ensuring optimal performance and user experience. 🚀
Let me know if you have any questions! 🎯
Final Thoughts
Bringing LogRocket, Azure App Insights, and Sentry together ensures seamless observability, consistent error tracking, and rich session insights. With my background in cloud platforms (AWS, Azure), scalable architectures, and engineering leadership, I’ve implemented similar monitoring solutions for SaaS platforms, reducing debugging time by 50% and increasing system reliability.
By following this guide, you can unify monitoring across your React app, making debugging and performance tuning faster and more efficient. 🚀 Let me know if you have questions!