Sentry is an application monitoring and error tracking platform. It helps developers identify, understand, and fix crashes in real time. It goes beyond basic error logging by providing detailed context around errors, including user information, browser details, and even the complete stack trace. This rich context drastically reduces the time it takes to diagnose and resolve issues, leading to improved application stability and a better user experience. Sentry supports a wide range of languages and frameworks, making it a versatile solution for diverse development environments. It allows for proactive monitoring, allowing developers to anticipate and address potential problems before they impact users.
JavaScript applications, especially those running in browsers or within Node.js environments, can be notoriously difficult to debug. Sentry provides several key advantages for JavaScript developers:
Create a Sentry Account: Sign up for a free Sentry account at https://sentry.io/.
Create a New Project: Once logged in, create a new project. Select the appropriate platform (e.g., “JavaScript” if you are working on a web application). You’ll be given a DSN (Data Source Name). Keep this DSN safe; it’s crucial for connecting your application to Sentry.
Install the Sentry SDK: Choose the appropriate SDK for your JavaScript framework (e.g., @sentry/browser
for web applications, @sentry/node
for Node.js). Install it via npm or yarn:
npm install @sentry/browser --save
# or
yarn add @sentry/browser
Initialize the SDK: In your JavaScript code, initialize the Sentry SDK with your DSN:
import * as Sentry from '@sentry/browser';
.init({
Sentrydsn: "YOUR_DSN_HERE", // Replace with your actual DSN
integrations: [new Integrations.BrowserTracing()], // For tracing
; })
Test it out: Introduce a deliberate error in your code (e.g., accessing a non-existent property). Refresh your application. You should see the error appear in your Sentry project dashboard.
Configure Options (Optional): Explore the numerous configuration options available in the Sentry SDK documentation to customize your error reporting (e.g., environment, release version, sample rate).
Remember to replace "YOUR_DSN_HERE"
with your actual DSN from your Sentry project settings. Consult the official Sentry documentation for the most up-to-date instructions and advanced configuration options.
This section details how to install and configure the Sentry JavaScript SDKs for both browser and Node.js environments.
Sentry offers distinct SDKs for different JavaScript environments. The core SDK, @sentry/core
, provides fundamental functionality, while specialized SDKs like @sentry/browser
and @sentry/node
offer platform-specific integrations and features.
Choose the appropriate SDK based on your application’s environment:
@sentry/browser
: For web applications running in browsers. This SDK automatically integrates with common browser features and provides features like performance monitoring.@sentry/node
: For Node.js applications running on servers. This SDK focuses on server-side error reporting and includes integrations relevant to Node.js environments.@sentry/react
: For React applications. This SDK builds upon @sentry/browser
and integrates with React’s error boundaries and context. (Similar SDKs exist for other frameworks like Angular and Vue.js)@sentry/core
: This is the core SDK which provides fundamental error handling and reporting features. You would use this as a foundation if building your own custom SDK or if you need extreme control over the setup, but for most use cases the platform-specific SDKs are preferred.You can install the SDK using either npm or yarn.
After installing the chosen SDK, you must initialize it with your DSN (Data Source Name) and any desired configuration options. This typically involves a single call to the Sentry.init()
function.
Basic Initialization (Browser):
import * as Sentry from '@sentry/browser';
.init({
Sentrydsn: 'YOUR_DSN_HERE', // Replace with your actual DSN
; })
Initialization with Integrations (Browser - Recommended):
Adding integrations enhances Sentry’s capabilities. The Integrations
object provides pre-built integrations for features like tracing and debugging performance issues.
import * as Sentry from '@sentry/browser';
import { Integrations } from '@sentry/tracing';
.init({
Sentrydsn: 'YOUR_DSN_HERE',
integrations: [new Integrations.BrowserTracing()], // Enables automatic performance tracing
; })
Basic Initialization (Node.js):
import * as Sentry from '@sentry/node';
.init({
Sentrydsn: 'YOUR_DSN_HERE',
; })
Remember to replace 'YOUR_DSN_HERE'
with your actual DSN obtained from your Sentry project settings.
The Sentry.init()
function accepts a configuration object with numerous options to tailor Sentry’s behavior. Key configuration options include:
dsn
(required): Your project’s DSN.environment
: Specifies the environment (e.g., ‘production’, ‘development’, ‘staging’). This helps organize and filter errors.release
: The version of your application. Useful for tracking errors across releases.sampleRate
: Controls the percentage of events sent to Sentry (useful for reducing data volume in development).integrations
: An array of Sentry integrations to enable specific features (e.g., tracing, error boundaries).beforeSend
: A function to modify or prevent events from being sent to Sentry. Useful for custom filtering or event transformation.tracesSampleRate
: The rate at which transactions are sampled for performance monitoring.Refer to the official Sentry documentation for a complete list of configuration options and their details.
npm:
npm install @sentry/browser --save
yarn:
yarn add @sentry/browser
CDN (less recommended for production): While possible to include the Sentry SDK via a CDN link, it’s generally less recommended for production deployments due to potential caching issues and the lack of fine-grained control offered by npm/yarn. Check the Sentry documentation for the current CDN links if you choose this method. This method will usually involve adding a <script>
tag to your HTML.
The core functionality of the Sentry SDK remains consistent between browser and Node.js environments; however, some key differences exist:
@sentry/browser
for browser-based applications and @sentry/node
for Node.js server-side applications.@sentry/tracing
), and automatic breadcrumbs. Node.js integrations might focus on HTTP request handling and server-specific error contexts.Remember to always consult the official Sentry documentation for the most up-to-date and detailed instructions on installation, configuration, and usage for each SDK.
This section covers the fundamental aspects of using the Sentry SDK to report errors and other relevant information.
The Sentry JavaScript SDKs automatically capture many common JavaScript errors. For browser-based applications using @sentry/browser
, this includes uncaught exceptions and errors within Promise
rejections. For Node.js applications, errors that bubble up to the top-level event loop are automatically captured. However, for robust error tracking, explicitly reporting errors (as shown in the next section) is recommended. Automatic capture provides a safety net, but manual reporting offers more control and context.
While the SDK automatically captures many errors, explicitly reporting errors using Sentry.captureException()
and Sentry.captureMessage()
offers greater control and allows you to add crucial context.
Sentry.captureException(error)
: Reports an exception object (e.g., an Error
object thrown by your code).try {
// Code that might throw an error
const result = 1 / 0; // Division by zero
catch (error) {
} .captureException(error);
Sentry }
Sentry.captureMessage(message)
: Reports a simple error message as a string..captureMessage('An unexpected issue occurred.'); Sentry
Sentry.captureEvent(event)
: Provides the most control over the reported event, allowing customization of all event properties. Consult the Sentry documentation for details on the event structure.Enriching error reports with context significantly speeds up debugging. The Sentry SDK allows you to add user information, tags, and breadcrumbs to provide valuable insights into the state of your application before an error occurred.
Sentry.setUser()
to associate an ID or other identifying information with an error..setUser({ id: 'user123', email: 'user@example.com' }); // Avoid sensitive data like PII in production Sentry
Sentry.setTag()
for individual tags or Sentry.setTags()
to set multiple tags at once..setTag('environment', 'production');
Sentry.setTags({'feature': 'login', 'version': '2.0'}); Sentry
Sentry.addBreadcrumb()
..addBreadcrumb({
Sentrycategory: 'ui',
message: 'User clicked login button',
data: { buttonId: 'loginBtn' }
; })
While the SDK attempts to capture uncaught exceptions automatically, explicitly handling them provides a more graceful user experience and potentially allows for cleanup before the application crashes. The window.onerror
(browser) or process.on('uncaughtException')
(Node.js) events can be used.
Browser (using window.onerror
):
window.onerror = function (message, source, lineno, colno, error) {
.captureException(error || new Error(message));
Sentryreturn true; // Prevents the default browser error handling.
; }
Node.js (using process.on('uncaughtException')
):
process.on('uncaughtException', (error) => {
.captureException(error);
Sentry// Consider adding graceful shutdown logic here
process.exit(1); // Exit the process to prevent further issues
; })
Use Sentry’s tracing capabilities to monitor the performance of your application. This involves instrumenting your code to track the duration and status of transactions (individual operations or units of work).
(Note: This requires setting up the @sentry/tracing
integration, as shown in the earlier setup sections).
import React from 'react';
import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';
.init({
Sentrydsn: 'YOUR_DSN_HERE',
integrations: [
new Integrations.BrowserTracing(),
new Sentry.Integrations.React(),
,
]tracesSampleRate: 1.0, // Capture 100% of transactions
;
})
function MyComponent() {
const handleClick = () => {
try {
// Some potentially error-prone code
const result = 1/0;
catch (error) {
} .captureException(error);
Sentry
};
}
return (
<div>
<button onClick={handleClick}>Click me</button>
</div>
;
)
}
export default MyComponent;
Remember to install the necessary packages: npm install @sentry/react @sentry/tracing
. Replace 'YOUR_DSN_HERE'
with your actual DSN. This example demonstrates basic error handling within a React component, along with enabling tracing. More advanced React usage may involve integrating with React’s error boundaries for more comprehensive error handling within your React component structure.
This section delves into more advanced configuration options within the Sentry SDK, allowing for fine-grained control over error reporting and data collection.
Beyond the basic Sentry.captureException()
and Sentry.captureMessage()
methods, Sentry offers several ways to customize error handling:
beforeSend
callback: This function allows you to inspect and modify an event before it’s sent to Sentry. You can use it to filter out specific events, add extra data, or even prevent an event from being sent altogether..init({
Sentrydsn: 'YOUR_DSN_HERE',
beforeSend(event) {
// Check if the event is from a specific source
if (event.exception && event.exception.values[0].type === 'MyCustomError') {
// Add extra context
event.extra = { extraData: 'Additional info' };
else if (event.exception && event.exception.values[0].type === 'IgnoreThisError') {
} return null; // Don't send this event to Sentry
}return event;
,
}; })
integrations
: Control which built-in integrations are active. Disabling integrations can reduce the amount of data collected and improve performance. For instance, you might disable the BrowserTracing
integration in a non-production environment.
sampleRate
: This option allows you to randomly sample a percentage of events to reduce the volume of data sent to Sentry, especially helpful in high-traffic environments or during development. A sampleRate
of 0.1 means only 10% of events are sent.
Breadcrumbs provide a trail of events preceding an error, offering valuable context for debugging. Advanced usage includes:
Sentry.addBreadcrumb()
with detailed information..addBreadcrumb({
Sentrycategory: 'api',
message: 'API call made',
type: 'http',
data: { url: '/api/users', method: 'GET', status: 200 },
level: Sentry.Severity.Log //Set severity level (info, warning, error, etc.)
; })
Sentry.setContext()
, Sentry.setExtra()
, Sentry.setTags()
, and Sentry.setUser()
to associate various types of data with an event, improving the richness of error reports and aiding in the investigation process. Ensure you respect user privacy when setting user-related data.For high-volume applications, sampling and rate limiting are crucial for managing the amount of data sent to Sentry.
sampleRate
(already mentioned): Controls the overall sampling rate of events.Sentry integrates with numerous third-party tools to streamline your workflow. Examples include:
Sentry can track user sessions, providing insights into session duration, crashes per session, and user engagement. This allows you to identify problematic patterns related to user activity and application stability. Enabling session tracking usually involves using specific SDK integrations or configuration options.
Transactions represent units of work within your application. They are crucial for performance monitoring, especially in applications with complex interactions. Properly instrumenting your application with transactions provides a view into the performance bottlenecks. This often involves using the @sentry/tracing
integration to track the duration of specific functions or API calls, giving you a clear picture of where your application spends most of its time. You can define start and end points, which will help you visualize your application flow better.
Remember to always refer to the official Sentry documentation for the most comprehensive and up-to-date information on advanced configuration options and best practices. The specifics of certain integrations and features may vary depending on the SDK version and your chosen platform (browser vs. Node.js).
Sentry provides official and community-supported integrations for various JavaScript frameworks and libraries, streamlining error reporting and context collection.
The @sentry/react
package provides seamless integration with React applications. It leverages React’s error boundaries to catch and report errors within components. Key features include:
Installation:
npm install @sentry/react @sentry/tracing --save
Initialization:
import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';
.init({
Sentrydsn: 'YOUR_DSN_HERE',
integrations: [
new Integrations.BrowserTracing(),
new Sentry.Integrations.React(),
,
]; })
While there isn’t a dedicated @sentry/angular
package, integrating Sentry into Angular applications is straightforward using the @sentry/browser
SDK. You can leverage Angular’s error handling mechanisms and Zone.js to capture errors. Consider using Angular’s error handling capabilities in conjunction with Sentry to handle errors gracefully.
Installation:
npm install @sentry/browser --save
Initialization: (within your Angular application’s initialization process, perhaps in app.module.ts
or a similar entry point)
import { Injectable } from '@angular/core';
import * as Sentry from '@sentry/angular';
import { Integrations } from '@sentry/tracing';
Injectable({
@: 'root'
providedIn
})export class SentryService {
constructor() {
.init({
Sentry: 'YOUR_DSN_HERE',
dsn: [new Integrations.BrowserTracing()],
integrations: 1.0,
tracesSampleRate;
})
} }
Then, ensure that the SentryService
is imported and included in the relevant Angular module.
Similar to Angular, the @sentry/browser
SDK works well with Vue.js. You can manually capture exceptions using Sentry.captureException()
or integrate with Vue’s error handling mechanisms. Consider using Vue’s error handling in conjunction with Sentry’s error handling to provide a robust error-reporting system.
Installation:
npm install @sentry/browser --save
Initialization: (within your Vue application’s main.js
or a similar entry point)
import Vue from 'vue';
import * as Sentry from '@sentry/browser';
import { Integrations } from '@sentry/tracing';
.init({
Sentrydsn: 'YOUR_DSN_HERE',
integrations: [new Integrations.BrowserTracing()],
;
})
.config.errorHandler = (error, instance, info) => {
Vue.captureException(error);
Sentry;
}
new Vue({
// ... your Vue app configuration
; })
The @sentry/node
package specifically targets Node.js applications. It integrates with the Node.js event loop to capture uncaught exceptions and provides support for features specific to server-side environments, like request context.
Installation:
npm install @sentry/node --save
Initialization:
import * as Sentry from '@sentry/node';
.init({
Sentrydsn: 'YOUR_DSN_HERE',
; })
You may need to handle uncaught exceptions explicitly using process.on('uncaughtException')
to ensure they’re properly reported to Sentry.
Sentry maintains a list of supported integrations on their website. This list is frequently updated, so check their official documentation for the most current information. Many popular JavaScript frameworks and libraries may have community-supported integrations or examples readily available.
For frameworks or libraries not officially supported, you can create custom integrations. This generally involves creating a class that implements the required Sentry integration interface, handling specific aspects of error capturing and context enrichment relevant to the target framework or library. Refer to Sentry’s documentation for the details of creating custom integrations. This typically involves extending the base integration class and providing relevant methods to capture context and handle specific framework-related events.
Remember that the specific initialization and configuration details may vary slightly depending on the framework and SDK version. Consult the official Sentry documentation for the most accurate and updated instructions for each integration.
This section guides you through effectively using Sentry’s dashboard and tools to monitor your application’s health and troubleshoot issues.
The Sentry dashboard provides a centralized view of your application’s errors and performance. Key areas include:
Familiarize yourself with the dashboard’s navigation and filtering options to effectively monitor your applications.
The Sentry dashboard provides robust filtering and search capabilities to isolate specific issues:
Effective filtering and searching are crucial for prioritizing and managing issues.
Analyzing error reports involves understanding the details provided in individual events:
Thoroughly examine these details to understand the cause and impact of each error.
Sentry offers several tools to aid in debugging:
Properly using these tools streamlines the debugging process.
Common Sentry integration issues:
dsn
, check your configuration, and review the data being sent to Sentry using the beforeSend
handler if necessary.sampleRate
) to reduce data volume if necessary.If you encounter issues not covered here, consult Sentry’s documentation and community forums for additional assistance. The Sentry support channels offer valuable resources for solving more complex problems.
Sentry’s performance monitoring capabilities extend beyond basic error tracking, allowing you to proactively identify and address performance bottlenecks in your applications.
Enabling performance monitoring typically involves:
Installing the necessary packages: Ensure you have the appropriate Sentry SDK installed (e.g., @sentry/browser
or @sentry/node
). Crucially, you’ll likely need the @sentry/tracing
package for transaction tracing.
Initializing the SDK with tracing integration: When initializing the Sentry SDK, include the Integrations.BrowserTracing()
(for browser applications) or equivalent integration for your environment. This enables automatic transaction tracing.
import * as Sentry from '@sentry/browser';
import { Integrations } from '@sentry/tracing';
.init({
Sentrydsn: 'YOUR_DSN_HERE',
integrations: [new Integrations.BrowserTracing()],
tracesSampleRate: 1.0, // Adjust sampling rate as needed
; })
(Optional) Manual instrumentation: For more granular control, you can manually instrument specific parts of your application to track custom transactions. This allows you to define transactions that are meaningful to your application’s architecture.
Adjust sampling rate: The tracesSampleRate
option controls the percentage of transactions that are sent to Sentry. Lowering this value (e.g., to 0.1 for 10%) reduces the amount of data sent, which is beneficial for high-traffic applications.
Once performance monitoring is enabled, Sentry will collect various metrics, including:
Analyzing these metrics provides insights into the performance characteristics of your application.
By examining the collected performance data, you can pinpoint performance bottlenecks:
Effective bottleneck identification requires careful analysis of the collected metrics and their relationships.
Once you’ve identified performance bottlenecks, you can apply various techniques to optimize your application:
Implementing these optimizations often involves iterative improvements and thorough testing to verify the effectiveness of the changes. Remember to monitor your application’s performance over time using Sentry to track the impact of any optimizations.
Security is paramount when using Sentry. This section outlines important security practices to protect your data and applications.
Sentry automatically anonymizes much of the data it collects, but you must take additional steps to protect sensitive information:
beforeSend
: Use the beforeSend
callback to perform custom data sanitization and prevent transmission of sensitive data.Sentry’s access control mechanisms help you manage who can access your project data:
Properly configuring authentication and authorization is critical to restricting access to sensitive data and maintaining the security of your Sentry account.
Compliance with data privacy regulations (like GDPR, CCPA, etc.) requires careful consideration:
Ensure that your use of Sentry complies with all relevant data privacy regulations and best practices. If you’re unsure about specific requirements, consult legal counsel. Properly configuring your Sentry project and understanding the anonymization and data-handling capabilities is critical for achieving data privacy compliance.
This section provides a high-level overview of the Sentry APIs. For complete and up-to-date details, always refer to the official Sentry documentation. The APIs are subject to change, so checking the latest version is crucial.
The Sentry client SDKs (e.g., @sentry/browser
, @sentry/node
, @sentry/react
) expose a JavaScript API for interacting with the Sentry service. Key functions include:
Sentry.init(options)
: Initializes the Sentry SDK with the provided configuration options (DSN, environment, integrations, etc.). This is the fundamental starting point for using the SDK.
Sentry.captureException(error)
: Captures and sends an exception to Sentry. The error
parameter is typically an instance of the JavaScript Error
object or a similar exception.
Sentry.captureMessage(message)
: Captures and sends a simple error message (string) to Sentry.
Sentry.captureEvent(event)
: Allows capturing a fully structured event object, providing maximum control over the data sent to Sentry. This is typically used for advanced scenarios where you want fine-grained control over the event properties.
Sentry.addBreadcrumb(breadcrumb)
: Adds a breadcrumb to the current session, providing context for events. Breadcrumbs show a sequence of events before an error occurred.
Sentry.setUser(user)
: Sets user context for the current session. User data is typically anonymized in production.
Sentry.setTag(key, value)
: Adds a tag to the current session. Tags are key-value pairs used to categorize and filter events.
Sentry.setExtra(key, value)
: Adds extra context to the current session. This allows adding arbitrary key-value pairs relevant to the current state.
Sentry.setContext(key, value)
: Sets context data for the current session. Similar to setExtra
, but specifically designed for named contexts (e.g., ‘user’, ‘request’).
Sentry.flush()
: Flushes any pending events to Sentry. Useful before application shutdown or similar scenarios to ensure all events are processed.
Sentry.close()
: Closes the Sentry client and stops further event processing. This is generally used during application shutdown.
Sentry.getCurrentHub()
: Gets the current Sentry Hub instance. The Hub manages the active client and its state.
Sentry.withScope(callback)
: Executes a callback function within a specific scope, allowing modifying the scope (e.g., adding breadcrumbs) before an event is captured.
These are some of the most commonly used functions. The full API documentation provides a complete list of methods and their parameters.
The Sentry server API allows programmatic interaction with Sentry’s backend. This API is primarily used for integrating Sentry with other systems, automating tasks, or accessing detailed data programmatically. Examples include:
The Sentry server API typically uses RESTful endpoints and often requires authentication using API tokens. Consult the official Sentry API documentation for specific endpoints, authentication methods, and detailed usage instructions. The API documentation details available endpoints, request formats (usually JSON), response formats, and authentication methods. Remember that the server API may require specific authentication and authorization to access certain endpoints and data.
This API reference provides a brief overview. For precise details, including request parameters, response structures, error codes, and rate limits, refer to the comprehensive and constantly updated official Sentry documentation. The documentation usually includes code examples in various programming languages (including Python and Javascript) to demonstrate API usage.
This appendix provides supplemental information to aid in your use of Sentry.
DSN (Data Source Name): A unique identifier for your Sentry project, used to connect your application to Sentry. It’s essentially a connection string that your application needs to send error reports.
Issue: A grouping of similar error events. Sentry automatically groups similar errors into issues, allowing you to track the frequency and severity of specific problems.
Event: A single instance of an error or other event captured by Sentry. An issue typically contains multiple events representing similar occurrences.
Exception: An error that occurs during the execution of your application’s code.
Stack Trace: A record of the sequence of function calls that led to an exception, showing you the path of execution that resulted in an error.
Breadcrumb: A contextual event captured by Sentry that helps reconstruct the user’s actions leading up to an error. Breadcrumbs provide a “trail” before the error occurred.
Transaction: A unit of work in your application, such as a network request or a user interaction. Used primarily in performance monitoring.
Span: A sub-segment within a transaction, used for more granular performance monitoring.
Release: A specific version of your application deployed to production or other environments. Tracking releases allows you to correlate errors with specific deployments.
Integration: A pre-built module or component that connects Sentry with specific frameworks, libraries, or tools.
Sampling Rate: The percentage of events or transactions that Sentry will sample and send to its servers. Reducing the sampling rate helps manage data volume.
Source Map: A file that maps minified or obfuscated code back to its original source code, aiding in debugging.
What happens if my Sentry subscription expires? The free plan offers a good amount of usage. If you exceed the free plan’s limits, you may need to upgrade your plan to a paid version to continue using all Sentry features. If you don’t upgrade, the service will still collect data but may not have all features available. You should also check to ensure your retention policy will keep data available if you aren’t paying for it.
Can I delete my Sentry account? Yes, you can delete your Sentry account through the account settings. Be aware that this will permanently delete all of your project data.
How do I securely store my DSN? Store your DSN as an environment variable, not hardcoded in your application code.
What is the difference between captureException
and captureMessage
? captureException
is used to send an exception object, providing detailed information about the error. captureMessage
is for simpler, text-based error messages.
How do I enable performance monitoring? Include the @sentry/tracing
integration when initializing the Sentry SDK and configure the tracesSampleRate
option.
Refer to the “Monitoring and Troubleshooting” section of this manual for detailed guidance. If you encounter problems not addressed there, check the Sentry documentation and community forums for solutions.
Official Sentry Documentation: https://docs.sentry.io/ The official documentation is the most up-to-date and complete resource.
Sentry Community Forums: Search for answers to your questions or ask your own.
Sentry Support: Contact Sentry support for assistance with complex issues.
Sentry Blog: Stay informed about new features, updates, and best practices.
This appendix provides a starting point; for comprehensive information, always consult the official Sentry resources.