Official Sentry SDK for Angular
Links
Angular Version Compatibility
This SDK officially supports Angular 15 to 17.
If you're using an older Angular version please check the
compatibility table in the docs.
If you're using an older version of Angular and experience problems with the Angular SDK, we recommend downgrading the
SDK to version 7.x. Please note that we don't provide any support for Angular versions below 10.
General
This package is a wrapper around @sentry/browser
, with added functionality related to Angular. All methods available
in @sentry/browser
can be imported from @sentry/angular
.
To use this SDK, call Sentry.init(options)
before you bootstrap your Angular application.
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { init } from '@sentry/angular';
import { AppModule } from './app/app.module';
init({
dsn: '__DSN__',
});
enableProdMode();
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(success => console.log(`Bootstrap success`))
.catch(err => console.error(err));
ErrorHandler
@sentry/angular
exports a function to instantiate an ErrorHandler provider that will automatically send Javascript
errors captured by the Angular's error handler.
import { NgModule, ErrorHandler } from '@angular/core';
import { createErrorHandler } from '@sentry/angular';
@NgModule({
providers: [
{
provide: ErrorHandler,
useValue: createErrorHandler({
showDialog: true,
}),
},
],
})
export class AppModule {}
Additionally, createErrorHandler
accepts a set of options that allows you to configure its behavior. For more details
see ErrorHandlerOptions
interface in src/errorhandler.ts
.
Tracing
@sentry/angular
exports a Trace Service, Directive and Decorators that leverage the tracing features to add
Angular-related spans to transactions. If tracing is not enabled, this functionality will not work. The SDK's
TraceService
itself tracks route changes and durations, while directive and decorators are tracking components
initializations.
Install
Registering a Trace Service is a 3-step process.
- Register and configure the
BrowserTracing
integration, including custom Angular routing instrumentation:
import { init, browserTracingIntegration } from '@sentry/angular';
init({
dsn: '__DSN__',
integrations: [browserTracingIntegration()],
tracePropagationTargets: ['localhost', 'https://yourserver.io/api'],
tracesSampleRate: 1,
});
- Register
SentryTrace
as a provider in Angular's DI system, with a Router
as its dependency:
import { NgModule } from '@angular/core';
import { Router } from '@angular/router';
import { TraceService } from '@sentry/angular';
@NgModule({
providers: [
{
provide: TraceService,
deps: [Router],
},
],
})
export class AppModule {}
- Either require the
TraceService
from inside AppModule
or use APP_INITIALIZER
to force-instantiate Tracing.
@NgModule({
})
export class AppModule {
constructor(trace: TraceService) {}
}
or
import { APP_INITIALIZER } from '@angular/core';
@NgModule({
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => () => {},
deps: [TraceService],
multi: true,
},
],
})
export class AppModule {}
Use
To track Angular components as part of your transactions, you have 3 options.
TraceDirective: used to track a duration between OnInit
and AfterViewInit
lifecycle hooks in template:
import { TraceModule } from '@sentry/angular';
@NgModule({
imports: [TraceModule],
})
export class AppModule {}
Then, inside your component's template (keep in mind that the directive's name attribute is required):
<app-header trace="header"></app-header>
<articles-list trace="articles-list"></articles-list>
<app-footer trace="footer"></app-footer>
TraceClass: used to track a duration between OnInit
and AfterViewInit
lifecycle hooks in components:
import { Component } from '@angular/core';
import { TraceClass } from '@sentry/angular';
@Component({
selector: 'layout-header',
templateUrl: './header.component.html',
})
@TraceClass()
export class HeaderComponent {
}
TraceMethod: used to track a specific lifecycle hooks as point-in-time spans in components:
import { Component, OnInit } from '@angular/core';
import { TraceMethod } from '@sentry/angular';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
})
export class FooterComponent implements OnInit {
@TraceMethod()
ngOnInit() {}
}
You can also add your own custom spans via startSpan()
. For example, if you'd like to track the duration of Angular
boostraping process, you can do it as follows:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { init, startSpan } from '@sentry/angular';
import { AppModule } from './app/app.module';
startSpan(
{
name: 'platform-browser-dynamic',
op: 'ui.angular.bootstrap',
},
async () => {
await platformBrowserDynamic().bootstrapModule(AppModule);
},
);
8.16.0
Important Changes
- feat(nextjs): Use spans generated by Next.js for App Router (#12729)
Previously, the @sentry/nextjs
SDK automatically recorded spans in the form of transactions for each of your top-level
server components (pages, layouts, ...). This approach had a few drawbacks, the main ones being that traces didn't have
a root span, and more importantly, if you had data stream to the client, its duration was not captured because the
server component spans had finished before the data could finish streaming.
With this release, we will capture the duration of App Router requests in their entirety as a single transaction with
server component spans being descendants of that transaction. This means you will get more data that is also more
accurate. Note that this does not apply to the Edge runtime. For the Edge runtime, the SDK will emit transactions as it
has before.
Generally speaking, this change means that you will see less transactions and more spans in Sentry. You will no
longer receive server component transactions like Page Server Component (/path/to/route)
(unless using the Edge
runtime), and you will instead receive transactions for your App Router SSR requests that look like
GET /path/to/route
.
If you are on Sentry SaaS, this may have an effect on your quota consumption: Less transactions, more spans.
- - feat(nestjs): Add nest cron monitoring support (#12781)
The @sentry/nestjs
SDK now includes a @SentryCron
decorator that can be used to augment the native NestJS @Cron
decorator to send check-ins to Sentry before and after each cron job run:
import { Cron } from '@nestjs/schedule';
import { SentryCron, MonitorConfig } from '@sentry/nestjs';
import type { MonitorConfig } from '@sentry/types';
const monitorConfig: MonitorConfig = {
schedule: {
type: 'crontab',
value: '* * * * *',
},
checkinMargin: 2, // In minutes. Optional.
maxRuntime: 10, // In minutes. Optional.
timezone: 'America/Los_Angeles', // Optional.
};
export class MyCronService {
@Cron('* * * * *')
@SentryCron('my-monitor-slug', monitorConfig)
handleCron() {
// Your cron job logic here
}
}
Other Changes
- feat(node): Allow to pass instrumentation config to
httpIntegration
(#12761) - feat(nuxt): Add server error hook (#12796)
- feat(nuxt): Inject sentry config with Nuxt
addPluginTemplate
(#12760) - fix: Apply stack frame metadata before event processors (#12799)
- fix(feedback): Add missing
h
import in ScreenshotEditor
(#12784) - fix(node): Ensure
autoSessionTracking
is enabled by default (#12790) - ref(feedback): Let CropCorner inherit the existing h prop (#12814)
- ref(otel): Ensure we never swallow args for ContextManager (#12798)