Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
@backtrace-labs/react
Advanced tools
Backtrace captures and reports handled and unhandled exceptions in your production software so you can manage application quality through the complete product lifecycle.
The @backtrace-labs/react SDK connects your React application to Backtrace. The basic integration is quick and easy, after which you can explore the rich set of Backtrace features.
$ npm install @backtrace-labs/react
Add the following code to your application before all other scripts to report client-side errors to Backtrace.
// Import the BacktraceClient from @backtrace-labs/react with your favorite package manager.
import { BacktraceClient, BacktraceConfiguration } from '@backtrace-labs/react';
// Configure client options
const options: BacktraceConfiguration = {
// Name of the website/application
name: 'MyWebPage',
// Version of the website
version: '1.2.3',
// Submission url
// <universe> is the subdomain of your Backtrace instance (<universe>.backtrace.io)
// <token> can be found in Project Settings/Submission tokens
url: 'https://submit.backtrace.io/<universe>/<token>/json',
};
// Initialize the client with the options
const client = BacktraceClient.initialize(options);
// By default, Backtrace will send an error for Uncaught Exceptions and Unhandled Promise Rejections
// Manually send an error
client.send(new Error('Something broke!'));
The @backtrace-labs/react
SDK offers an Error Boundary that will handle errors during rendering, send the error and
component stack to Backtrace, and allow you to provide a fallback component.
Props:
type RenderFallback = () => ReactElement;
export interface Props {
children: ReactNode;
fallback?: ReactElement | RenderFallback;
name?: string; // to identify the ErrorBoundary when multiple are used
}
Usage:
import { ErrorBoundary } from '@backtrace-labs/react';
import Fallback from './components/Fallback';
<ErrorBoundary name="your-boundary-name" fallback={Fallback}>
<App />
</ErrorBoundary>;
Client-side error reports are based on minified code. Upload source maps and source code to resolve minified code to your original source identifiers.
(Source Map feature documentation)
Custom attributes are key-value pairs that can be added to your error reports. They are used in report aggregation, sorting and filtering, can provide better contextual data for an error, and much more. They are foundational to many of the advanced Backtrace features detailed in Error Reporting documentation.
There are several places where attributes can be added, modified or deleted.
It is possible to include an attributes object during BacktraceClient initialization. This list of attributes will be included with every error report, referred to as global attributes.
// Create an attributes object that can be modified throughout runtime
const attributes: Record<string, unknown> = {
release: 'PROD',
};
// BacktraceClientOptions
const options: BacktraceConfiguration = {
name: 'MyWebPage',
version: '1.2.3',
url: 'https://submit.backtrace.io/<universe>/<token>/json',
// Attach the attributes object
userAttributes: attributes,
};
// Initialize the client
const client = BacktraceClient.initialize(options);
You can also include attributes that will be resolved when creating a report:
// BacktraceClientOptions
const options: BacktraceConfiguration = {
name: 'MyWebPage',
version: '1.2.3',
url: 'https://submit.backtrace.io/<universe>/<token>/json',
// Attach the attributes object
userAttributes: () => ({
user: getCurrentUser(),
}),
};
// Initialize the client
const client = BacktraceClient.initialize(options);
Global attributes can be set during the runtime once specific data has be loaded (e.g. a user has logged in).
const client = BacktraceClient.initialize(options);
...
client.addAttribute({
"clientID": "de6faf4d-d5b5-486c-9789-318f58a14476"
})
You can also add attributes that will be resolved when creating a report:
const client = BacktraceClient.initialize(options);
...
client.addAttribute(() => ({
"clientID": resolveCurrentClientId()
}))
The attributes list of a BacktraceReport object can be directly modified.
const report: BacktraceReport = new BacktraceReport('My error message', { myReportKey: 'myValue' });
report.attributes['myReportKey'] = 'New value';
Files can be attached to error reports. This can be done when initalizing the BacktraceClient, updating the BacktraceClient, or dynamically for specific reports. When including attachments in BacktraceClient, all files will be uploaded with each report.
// Import attachment types from @backtrace-labs/react
import { BacktraceStringAttachment, BacktraceUint8ArrayAttachment } from "@backtrace-labs/react";
// BacktraceStringAttachment should be used for text object like a log file, for example
const attachment1 = new BacktraceStringAttachment("logfile.txt", "This is the start of my log")
// BacktraceUint8ArrayAttachment should be used for binary files
const attachment2 = new BacktraceUint8ArrayAttachment("connection_buffer", new Uint8Array(2));
// Setup array of files to attach
const attachments = [attachment1];
// BacktraceClientOptions
const options = {
name: "MyWebPage",
version: "1.2.3",
url: "https://submit.backtrace.io/<universe>/<token>/json",
// Attach the files to all reports
attachments,
}
const client = BacktraceClient.initialize(options);
// Later decide to add an attachment to all reports
client.addAttachment(attachment2)
// After catching an exception and generating a report
try {
throw new Error("Caught exception!")
} catch (error) {
const report = const report = new BacktraceReport(error, {}, [new BacktraceStringAttachment("CaughtErrorLog", "some error logging data here")])
client.send(report);
}
Breadcrumbs are snippets of chronological data tracing runtime events. This SDK records a number of events by default, and manual breadcrumbs can also be added.
(Breadcrumbs feature documentation)
Option Name | Type | Description | Default | Required? |
---|---|---|---|---|
enable | Boolean | Determines if the breadcrumbs support is enabled. By default the value is set to true. | true |
|
logLevel | BreadcrumbLogLevel | Specifies which log level severity to include. By default all logs are included. | All Logs |
|
eventType | BreadcrumbType | Specifies which breadcrumb type to include. By default all types are included. | All Types |
|
maximumBreadcrumbs | Number | Specifies maximum number of breadcrumbs stored by the library. By default, only 100 breadcrumbs will be stored. | 100 |
|
intercept | (breadcrumb: RawBreadcrumb) => RawBreadcrumb | undefined; | Inspects breadcrumb and allows to modify it. If the undefined value is being returned from the method, no breadcrumb will be added to the breadcrumb storage. | All Breadcrumbs |
|
import { BacktraceClient, BacktraceConfiguration } from '@backtrace-labs/react';
// BacktraceClientOptions
const options: BacktraceConfiguration = {
// ignoring all but breadcrumbs config for simplicity
breadcrumbs: {
// breadcrumbs configuration
},
};
// Initialize the client
const client = BacktraceClient.initialize(options);
Type | Description |
---|---|
HTTP | Adds a breadcrumb with the url, request type, and reponse status for Fetch or XMLHttpRequests. |
History | Adds breadcrumb on pushstate and popstate. |
Document/Window | Adds a breadcrumb for document.click, document.dblclick, document.drag, document.drop, window.load, window.unload, window.pagehide, window.pageshow, window.online, and window.offline. |
Console | Adds a breadcrumb every time console log is being used by the developer. |
If PII or other information needs to be filtered from a breadcrumb, you can use the intercept function to skip or filter out the sensitive information. Any RawBreadcrumb returned will be used for the breadcrumb. If undefined is returned, no breadcrumb will be added.
In addition to all of the default breadcrumbs that are automatically collected, you can also manually add breadcrumbs of your own.
client.breadcrumbs?.info('This is a manual breadcrumb.', {
customAttr: 'wow!',
});
The Backtrace React SDK has the ability to send usage Metrics to be viewable in the Backtrace UI.
(Stability Metrics feature documentation)
Option Name | Type | Description | Default | Required? |
---|---|---|---|---|
metricsSubmissionUrl | String | Metrics server hostname. By default the value is set to https://events.backtrace.io. | https://events.backtrace.io |
|
enable | Boolean | Determines if the metrics support is enabled. By default the value is set to true. | true |
|
autoSendInterval | Number | Indicates how often crash free metrics are sent to Backtrace. The interval is a value in ms. By default, session events are sent on application startup/finish, and every 30 minutes while the application is running. If the value is set to 0. The auto send mode is disabled. In this situation the application needs to maintain send mode manually. | On application startup/finish |
|
size | Number | Indicates how many events the metrics storage can store before auto submission. | 50 |
|
// metrics will be undefined if not enabled
client.metrics?.send();
There are several ways to send an error to Backtrace. For more details on the definition of client.send()
see
Methods below.
// send as a string
await client.send('This is a string!');
// send as an Error
await client.send(new Error('This is an Error!'));
// as a BacktraceReport (string)
await client.send(new BacktraceReport('This is a report with a string!'));
// as a BacktraceReport (Error)
await client.send(new BacktraceReport(new Error('This is a report with a string!')));
BacktraceClient is the main SDK class. Error monitoring starts when this object is instantiated, and it will compose and send reports for unhandled errors and unhandled promise rejections. It can also be used to manually send reports from exceptions and rejection handlers.
The following options are available for the BacktraceClientOptions passed when initializing the BacktraceClient.
Option Name | Type | Description | Default | Required? |
---|---|---|---|---|
url | String | Submission URL to send errors to |
| |
name | String | Your application name |
| |
version | String | Your application version |
| |
token | String | The submission token for error injestion. This is required only if submitting directly to a Backtrace URL. (uncommon) |
| |
userAttributes | Dictionary | Additional attributes that can be filtered and aggregated against in the Backtrace UI. |
| |
attachments | BacktraceAttachment[] | Additional files to be sent with error reports. See File Attachments |
| |
beforeSend | (data: BacktraceData) => BacktraceData | undefined | Triggers an event every time an exception in the managed environment occurs, which allows you to skip the report (by returning a null value) or to modify data that library collected before sending the report. You can use the BeforeSend event to extend attributes or JSON object data based on data the application has at the time of exception. See BeforeSend |
| |
skipReport | (report: BacktraceReport) => boolean | If you want to ignore specific types of error reports, we recommend that you use the skipReport callback. By using it, based on the data generated in the report, you can decide to filter the report, or send it to Backtrace. |
| |
captureUnhandledErrors | Boolean | Enable unhandled errors | true |
|
captureUnhandledPromiseRejections | Boolean | Enable unhandled promise rejection | true |
|
timeout | Integer | How long to wait in ms before timing out the connection | 15000 |
|
ignoreSslCertificate | Boolean | Ignore SSL Certificate errors | false |
|
rateLimit | Integer | Limits the number of reports the client will send per minute. If set to '0', there is no limit. If set to a value greater than '0' and the value is reached, the client will not send any reports until the next minute. | 0 |
|
metrics | BacktraceMetricsOptions | See Backtrace Stability Metrics |
| |
breadcrumbs | BacktraceBreadcrumbsSettings | See Backtrace Breadcrumbs |
|
Name | Return Type | Description |
---|---|---|
addAttribute(attributes: Record<string, unknown>) | void | Add attributes to the BacktraceClient reports |
addAttachment(attachment: BacktraceAttachment) | void | Add an attachment to the BacktraceClient reports |
initialize(options: BacktraceClientOptions) | BacktraceClient | Initializes a new BacktraceClient (returns the same instance on subsequent calls) |
builder(options: BacktraceClientOptions).build() | BacktraceClient | (Advanced) Sets up a new BacktraceClient for reporting |
send(data: BacktraceReport | Error | string, reportAttributes: Record<string, unknown> = {}, reportAttachments: BacktraceAttachment[] = []) | Promise<void> | Asynchronously sends error data to Backtrace |
dispose | void | Disposes the client |
A Backtrace Report is the format that ultimately gets sent to Backtrace. Its structure can be found in
BacktraceReport.ts
.
FAQs
Backtrace-Javascript React integration
We found that @backtrace-labs/react demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 7 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.