Skip to main content
The Sentry Angular SDK provides comprehensive error monitoring and performance tracking for Angular applications (Angular 14-20).

Installation

npm install @sentry/angular

Version Compatibility

  • Angular 14+ is fully supported
  • Angular 10-13: Use SDK version 7.x
  • Angular versions below 10: Not supported

Basic Setup

Initialize Sentry before bootstrapping your application:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { init } from '@sentry/angular';
import { AppComponent } from './app/app.component';

init({
  dsn: 'YOUR_DSN_HERE',
  
  integrations: [
    // No additional setup needed for Angular
  ],
  
  tracesSampleRate: 1.0,
});

bootstrapApplication(AppComponent, appConfig);

ErrorHandler Integration

Register Sentry’s ErrorHandler to capture Angular errors:
// app.config.ts
import { ApplicationConfig, ErrorHandler } from '@angular/core';
import { createErrorHandler } from '@sentry/angular';

export const appConfig: ApplicationConfig = {
  providers: [
    {
      provide: ErrorHandler,
      useValue: createErrorHandler({
        showDialog: true,
        logErrors: true,
      }),
    },
    // ... other providers
  ],
};

Performance Monitoring

TraceService Setup

Enable automatic route change tracking:
// app.config.ts
import { ApplicationConfig, provideAppInitializer, inject } from '@angular/core';
import { TraceService } from '@sentry/angular';

export const appConfig: ApplicationConfig = {
  providers: [
    provideAppInitializer(() => {
      inject(TraceService);
    }),
    // ... other providers
  ],
};

Initialize Browser Tracing

import { init, browserTracingIntegration } from '@sentry/angular';

init({
  dsn: 'YOUR_DSN_HERE',
  
  integrations: [
    browserTracingIntegration(),
  ],
  
  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for performance monitoring.
  tracesSampleRate: 1.0,
  
  // Propagate traces to these targets
  tracePropagationTargets: ['localhost', 'https://yourserver.io/api'],
});

Component Tracking

Track component performance with decorators and directives:
Track component initialization in templates:
// component.ts
import { Component } from '@angular/core';
import { TraceModule } from '@sentry/angular';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [TraceModule],
  template: `
    <app-header trace="header"></app-header>
    <app-content trace="content"></app-content>
    <app-footer trace="footer"></app-footer>
  `,
})
export class DashboardComponent {}
This tracks the duration between OnInit and AfterViewInit lifecycle hooks.

Custom Performance Tracking

Track Bootstrap Process

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { init, startSpan } from '@sentry/angular';
import { AppModule } from './app/app.module';

init({
  dsn: 'YOUR_DSN_HERE',
  tracesSampleRate: 1.0,
});

startSpan(
  {
    name: 'platform-browser-dynamic',
    op: 'ui.angular.bootstrap',
  },
  async () => {
    await platformBrowserDynamic().bootstrapModule(AppModule);
  },
);

Track Service Methods

import { Injectable } from '@angular/core';
import * as Sentry from '@sentry/angular';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  async fetchData() {
    return await Sentry.startSpan(
      {
        name: 'DataService.fetchData',
        op: 'http.client',
      },
      async () => {
        const response = await fetch('/api/data');
        return response.json();
      },
    );
  }
}

Error Handling

Manual Error Capture

import { Component } from '@angular/core';
import * as Sentry from '@sentry/angular';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
})
export class UserProfileComponent {
  async saveProfile() {
    try {
      await this.userService.save(this.profile);
    } catch (error) {
      Sentry.captureException(error, {
        tags: {
          component: 'UserProfile',
          action: 'save',
        },
      });
    }
  }
}

ErrorHandler Options

import { createErrorHandler } from '@sentry/angular';

const errorHandler = createErrorHandler({
  // Show user feedback dialog
  showDialog: true,
  
  // Log errors to console
  logErrors: true,
  
  // Customize dialog options
  dialogOptions: {
    title: 'It looks like we\'re having issues.',
    subtitle: 'Our team has been notified.',
  },
});

HTTP Interceptor

Track HTTP requests:
import { ApplicationConfig, provideHttpClient, withInterceptors } from '@angular/core';
import { httpClientIntegration } from '@sentry/angular';

init({
  dsn: 'YOUR_DSN_HERE',
  integrations: [
    httpClientIntegration(),
  ],
});

Context & User Information

import { Injectable } from '@angular/core';
import * as Sentry from '@sentry/angular';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  setUser(user: User) {
    // Set user context
    Sentry.setUser({
      id: user.id,
      email: user.email,
      username: user.username,
    });
    
    // Add custom context
    Sentry.setContext('permissions', {
      roles: user.roles,
      features: user.enabledFeatures,
    });
    
    // Add tags
    Sentry.setTag('subscription', user.subscriptionTier);
  }
  
  clearUser() {
    Sentry.setUser(null);
  }
}

Router Instrumentation

The SDK automatically instruments Angular Router when TraceService is initialized:
import { Router } from '@angular/router';
import { Component } from '@angular/core';
import * as Sentry from '@sentry/angular';

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>',
})
export class AppComponent {
  constructor(private router: Router) {
    // Router events are automatically tracked
    // Transaction names will match route paths
  }
}

Advanced Configuration

// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { init, browserTracingIntegration, replayIntegration } from '@sentry/angular';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';

init({
  dsn: 'YOUR_DSN_HERE',
  
  environment: 'production',
  release: 'my-app@1.0.0',
  
  integrations: [
    browserTracingIntegration(),
    replayIntegration({
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],
  
  // Performance
  tracesSampleRate: 0.2,
  tracePropagationTargets: ['localhost', /^https:\/\/api\.example\.com/],
  
  // Session Replay
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  
  // Error filtering
  ignoreErrors: [
    'Non-Error exception captured',
    'ResizeObserver loop limit exceeded',
  ],
  
  beforeSend(event, hint) {
    // Filter or modify events
    if (event.exception) {
      console.log('Error captured:', hint.originalException);
    }
    return event;
  },
});

bootstrapApplication(AppComponent, appConfig);
// app.config.ts
import { ApplicationConfig, ErrorHandler, provideAppInitializer, inject } from '@angular/core';
import { provideRouter } from '@angular/router';
import { createErrorHandler, TraceService } from '@sentry/angular';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    
    {
      provide: ErrorHandler,
      useValue: createErrorHandler({
        showDialog: true,
        logErrors: true,
      }),
    },
    
    provideAppInitializer(() => {
      inject(TraceService);
    }),
  ],
};

Best Practices

TraceService

Always inject TraceService to enable automatic route tracking.

ErrorHandler

Register the ErrorHandler provider to catch all Angular errors.

Component Tracking

Use TraceDirective for template-based tracking, decorators for classes.

Lazy Loading

Component tracking works with lazy-loaded modules automatically.

Next Steps

Router Tracking

Advanced router instrumentation

HTTP Interceptor

Track HTTP requests and responses

Performance

Component performance monitoring

Source Maps

Upload source maps for production