### install Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Installs the TrackJS agent into the current environment with the provided options. The agent's token is required for installation. ```APIDOC ## install ### Description Installs the agent into the current environment with the provided options. If the agent has already been installed, it will throw a `TrackJSError`. `options.token` is required, and the method will throw a `TrackJSError` if omitted. See `uninstall`. ### Method *Implicitly called (part of TrackJS namespace)* ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (TrackJSOptions) - Options to install with. - **token** (string) - Required. Your TrackJS project token. - **...other options** - See TrackJS documentation for a full list of options. ### Request Example ```javascript const TrackJS = require('trackjs-node'); TrackJS.install({ token: 'YOUR_TRACKJS_TOKEN', // other options like environment, grouping, etc. }); ``` ### Response #### Success Response (200) *Returns `undefined`* #### Response Example None ``` -------------------------------- ### TrackJS Node.js: Install Agent Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Installs the agent into the current environment with the provided options. The 'token' option is required. This method will throw an error if the agent is already installed. ```javascript TrackJS.install({ token: "YOUR_TRACKJS_TOKEN" }); ``` -------------------------------- ### Automatic TrackJS Agent Installation Source: https://docs.trackjs.com/browser-agent/installation This method configures the TrackJS agent to install itself automatically upon loading by defining a configuration object on `window._trackJs`. This is useful when the exact loading time of the agent is uncertain and was the default behavior before version 3.0.0. ```javascript window._trackJs = { token: 'YOUR_TOKEN_HERE' }; // Include the agent script later, for example: // ``` -------------------------------- ### Bundle TrackJS Agent as an ES6 Module Source: https://docs.trackjs.com/browser-agent/installation This method shows how to install the TrackJS agent by bundling it as an ES6 module. It requires you to have the 'trackjs' package installed via npm. This approach is suitable for projects using modern JavaScript module systems. ```javascript import trackjs from 'trackjs'; trackjs.install({ token: 'YOUR_TOKEN_HERE' }); ``` -------------------------------- ### Bundle TrackJS Agent as a CommonJS Module Source: https://docs.trackjs.com/browser-agent/installation This code snippet demonstrates installing the TrackJS agent using CommonJS modules. Ensure you have the 'trackjs' package installed via npm. This is common in Node.js environments or older JavaScript build systems. ```javascript var trackjs = require('trackjs'); trackjs.install({ token: 'YOUR_TOKEN_HERE' }); ``` -------------------------------- ### Install TrackJS Agent from CDN Source: https://docs.trackjs.com/browser-agent/installation This is the default and easiest method to integrate the TrackJS agent into your website. It involves including a script tag that loads the agent from the TrackJS CDN. This method is recommended if you do not use a module bundler. ```html ``` -------------------------------- ### TrackJS Agent with Crossorigin Attribute Source: https://docs.trackjs.com/browser-agent/installation This example shows how to add the `crossorigin` attribute to the TrackJS agent script tag when loading from a CDN. This can help mitigate 'Script Error' issues caused by the browser's Same-Origin Policy, although browser support varies. ```html ``` -------------------------------- ### Install trackjs-nextjs Package Source: https://docs.trackjs.com/node-agent/integrations/nextjs Installs the TrackJS NextJS integration package using npm or yarn. This package is essential for setting up error tracking in your NextJS application. ```bash npm install trackjs-nextjs yarn add trackjs-nextjs ``` -------------------------------- ### configure Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Updates the Agent Options after the agent has been installed. This allows for dynamic configuration changes. ```APIDOC ## configure ### Description Update the Agent Options after `install`. ### Method *Implicitly called (part of TrackJS namespace)* ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (TrackJSOptions) - Options to be updated. ### Request Example ```javascript TrackJS.configure({ "maxBatchSize": 50 }); ``` ### Response #### Success Response (200) - **success** (boolean) - `true` if successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### isInstalled Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Checks whether the TrackJS agent has been installed into the current environment. ```APIDOC ## isInstalled ### Description Whether the agent has been installed into the current environment. See `install` and `uninstall`. ### Method *Implicitly called (part of TrackJS namespace)* ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const TrackJS = require('trackjs-node'); if (TrackJS.isInstalled()) { console.log('TrackJS agent is installed.'); } else { console.log('TrackJS agent is not installed.'); } ``` ### Response #### Success Response (200) - **installed** (boolean) - `true` if the agent is installed, `false` otherwise. #### Response Example ```json { "installed": true } ``` ``` -------------------------------- ### Install TrackJS NextJS Package Source: https://docs.trackjs.com/browser-agent/integrations/nextjs15 Installs the TrackJS-NextJS integration package using npm or yarn. This is the first step for integrating TrackJS into your NextJS application. ```bash npm install trackjs-nextjs # or yarn add trackjs-nextjs ``` -------------------------------- ### TrackJS Node.js: Check Installation Status Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Checks whether the TrackJS agent has been installed in the current environment. This is useful for conditional logic related to agent functionality. ```javascript if (TrackJS.isInstalled()) { // Agent is installed } ``` -------------------------------- ### Client-Side Error Handling with TrackJS Agent (Pages Router) Source: https://docs.trackjs.com/browser-agent/integrations/nextjs15 Enables client-side error tracking in NextJS Pages Router by installing the TrackJS agent at the start of the `pages/_app.tsx` component. Requires your TrackJS token and allows for custom settings. ```typescript import TrackJS from 'trackjs'; import type { AppProps } from 'next/app'; function MyApp({ Component, pageProps }: AppProps) { TrackJS.install({ token: 'YOUR_TRACKJS_TOKEN', // ... other settings ... }); return ; } export default MyApp; ``` -------------------------------- ### Client-Side Error Handling with Pages Router using TrackJS Agent Source: https://docs.trackjs.com/node-agent/integrations/nextjs Enables client-side error tracking in NextJS Pages Router by installing the `TrackJS` agent at the start of the `pages/_app.tsx` App component. Requires your TrackJS token and optional custom settings. ```typescript import TrackJS from 'trackjs'; function MyApp({ Component, pageProps }) { TrackJS.install({ token: 'YOUR_TRACKJS_TOKEN', // other custom settings }); return ; } export default MyApp; ``` -------------------------------- ### TrackJS Node.js: Configure Agent Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Updates the agent options after the agent has been installed. This method allows for dynamic adjustment of agent settings. It returns a boolean indicating success. ```javascript TrackJS.configure({ // New options }); ``` -------------------------------- ### Polyfill navigator.userAgent with Client Hints Source: https://docs.trackjs.com/browser-agent/tips-and-tricks/android-platform-info This snippet demonstrates how to polyfill the `navigator.userAgent` string using Google's UACH Retrofill Library to restore lost Android platform information. It requires including the library and calling `overrideUserAgentUsingClientHints` early in your application's execution. ```javascript /** * Polyfills the navigator.userAgent string using Client Hints. * This is necessary because Google is reducing the amount of Android * device, platform, and version information available in the userAgent string. * * Requirements: * - Include the UACH Retrofill Library from Google. * - Serve pages with the `Accept-CH` header to allow Platform version exposure. * * Usage: * Call `overrideUserAgentUsingClientHints` as early as possible in your code. */ // Example usage (assuming UACH Retrofill Library is loaded): // overrideUserAgentUsingClientHints(["uaFullVersion"]); ``` -------------------------------- ### TrackJS Node.js: Add Metadata Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Adds key-value pairs to describe the current context for error reporting. If a key already exists, its value is updated. This method requires the agent to be installed. ```javascript TrackJS.addMetadata({ "key": "value" }); TrackJS.addMetadata("key", "value"); ``` -------------------------------- ### Nginx Configuration for TrackJS Self-Hosted Domain Forwarding (Nginx) Source: https://docs.trackjs.com/data-management/ad-blockers An example Nginx configuration for setting up a self-hosted domain forwarding server for TrackJS. This allows you to manage the proxy yourself instead of using TrackJS's hosted service. It sets up a reverse proxy to handle requests to the TrackJS endpoint. ```nginx server { listen 443 ssl; server_name errors.your_domain.com; ssl_certificate /path/to/your/ssl_certificate.crt; ssl_certificate_key /path/to/your/ssl_private_key.key; location / { proxy_pass https://forwarder.trackjs.com; proxy_set_header Host forwarder.trackjs.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` -------------------------------- ### TrackJS Safety Check for Standalone Script Source: https://docs.trackjs.com/browser-agent/installation This snippet illustrates a safety check to ensure the TrackJS agent has loaded before attempting to use its methods. It's particularly important when loading the agent as a standalone script or from a CDN to prevent `ReferenceError` if the script fails to load. ```javascript if (window.TrackJS) { TrackJS.someMethod(); } ``` -------------------------------- ### TrackJS Content Security Policy Directives Source: https://docs.trackjs.com/browser-agent/installation This section provides the necessary Content Security Policy (CSP) directives required for the TrackJS agent to function correctly. These directives should be included in your server's HTTP headers or meta tags to allow TrackJS scripts and reports. ```http Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.trackjs.com; connect-src https://api.trackjs.com; ``` -------------------------------- ### Configure TrackJS Agent to Use Proxy Source: https://docs.trackjs.com/data-management/ad-blockers Modify your TrackJS agent installation to use the custom proxy server. This involves setting undocumented properties within the TrackJS.install block. After implementing this, test by sending a manual error. ```javascript TrackJS.install({ token: 'YOUR_TOKEN', proxy: 'https://errors.your_domain.com' }); ``` -------------------------------- ### Read Meta Tag Version in TrackJS Install Config Source: https://docs.trackjs.com/browser-agent/tips-and-tricks/page-version This code snippet shows how to read the version information injected into a meta tag from the page's head and configure TrackJS to include it in its reports. This allows for easy correlation of errors with specific code deployments. ```javascript TrackJS.install({ version: document.querySelector('meta[name="trackjs-version"]').getAttribute('content') }); ``` -------------------------------- ### addMetadata Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Adds or updates key-value pairs of metadata to the current context. This metadata is sent with each error, enabling custom filtering in the dashboard. Metadata can also be added during installation. ```APIDOC ## addMetadata ### Description Adds one or more key-value pairs of strings to describe the current context. You can use this to track any arbitrary data that is interesting for you, such as whether it is a paying customer, their transaction id, or anything else. These metadata key-values are sent with each error and give you the capability to filter the Dashboard in your own way. If the metadata key already exists, it will be updated with the new value. See `removeMetadata`. Metadata can also be added during install via `options`. Agent must be installed. See `install`. ### Method *Implicitly called (part of TrackJS namespace)* ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **metadata** (object | string) - A dictionary of key-value pairs or a single metadata key. - **value** (string) - Metadata value for this page session (used when metadata is a string). ### Request Example ```javascript TrackJS.addMetadata({ "customerType": "paying", "transactionId": "12345" }); TrackJS.addMetadata("userStatus", "active"); ``` ### Response #### Success Response (200) *Returns `undefined`* #### Response Example None ``` -------------------------------- ### GET /websites/trackjs/page-views Source: https://docs.trackjs.com/data-api/pageviews-by-day Retrieves the daily page view counts for a website. This endpoint can be filtered by application, date range, and paginated. ```APIDOC ## GET /websites/trackjs/page-views ### Description Retrieves the daily page view counts for a website. This endpoint returns the page view counts per day, sorted by date descending. ### Method GET ### Endpoint /websites/trackjs/page-views ### Parameters #### Query Parameters - **application** (String) - Optional - Filter the results to only the Application key provided. - **endDate** (ISO 8601 String) - Optional - Filter the results to only return errors before this date. Time precision is within 1 second. - **startDate** (ISO 8601 String) - Optional - Filter the results to only return errors after this date. Time precision is within 1 second. - **page** (Number) - Optional - The page of data you want returned. By default, the first page of data is returned. See Paging. - **size** (Number 1-1000) - Optional - The size of the page of data you want returned. See Paging. ### Request Example ```json { "application": "your_application_key", "startDate": "2023-10-26T00:00:00Z", "endDate": "2023-10-27T23:59:59Z" } ``` ### Response #### Success Response (200) - **date** (String) - The date of the page view count. - **pageViews** (Number) - The number of page views for that date. #### Response Example ```json { "data": [ { "date": "2023-10-26", "pageViews": 1500 }, { "date": "2023-10-25", "pageViews": 1450 } ] } ``` ``` -------------------------------- ### GET /websites/trackjs/page-views-by-hour Source: https://docs.trackjs.com/data-api/pageviews-by-hour Retrieves the hourly page view counts for a given website, with options to filter by application, date range, and control pagination. ```APIDOC ## GET /websites/trackjs/page-views-by-hour ### Description TrackJS records the number of times the Agent loads on your site as Page Views. This endpoint returns the page view counts per hour, sorted by date descending. ### Method GET ### Endpoint /websites/trackjs/page-views-by-hour ### Parameters #### Query Parameters - **application** (String) - Optional - Filter the results to only the Application key provided. - **endDate** (ISO 8601 String) - Optional - Filter the results to only return errors before this date and time. Time precision is within 1 second. - **startDate** (ISO 8601 String) - Optional - Filter the results to only return errors after this date and time. Time precision is within 1 second. - **page** (Number) - Optional - The page of data you want returned. By default, the first page of data is returned. See Paging. - **size** (Number 1-1000) - Optional - The size of the page of data you want returned. See Paging. ### Response #### Success Response (200) - **data** (Array) - An array of objects, where each object contains hourly page view data. - **timestamp** (String) - The hour for which the page views are counted. - **pageViews** (Number) - The number of page views during that hour. #### Response Example ```json { "data": [ { "timestamp": "2023-10-27T10:00:00Z", "pageViews": 150 }, { "timestamp": "2023-10-27T09:00:00Z", "pageViews": 120 } ] } ``` ``` -------------------------------- ### Configure Nginx to Proxy to TrackJS Source: https://docs.trackjs.com/data-management/ad-blockers This configuration snippet modifies your Nginx server block to proxy requests to TrackJS. Ensure you restart Nginx after applying these changes. This setup allows TrackJS errors to be sent through your custom domain. ```nginx server { listen 80; listen [::]:80; server_name errors.your_domain.com; location / { proxy_pass https://api.trackjs.com; proxy_set_header Host api.trackjs.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` -------------------------------- ### TrackJS Node.js: Add Log Telemetry Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Records a telemetry console event into the log. Messages logged with severity 'error' will trigger an error capture. This method requires the agent to be installed. ```javascript TrackJS.addLogTelemetry("info", "User logged in", { userId: 123 }); ``` -------------------------------- ### Server-Side Error Handling with Instrumentation Source: https://docs.trackjs.com/node-agent/integrations/nextjs Captures server-side errors in NextJS (both App Router and Pages Router) by installing the TrackJS agent using the `instrumentation.tsx` file in the project root. This ensures errors occurring on the Node.js server are logged. ```typescript import TrackJS from 'trackjs'; export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { await TrackJS.instrumentation.register(); } } ``` -------------------------------- ### Intercept TrackJS Errors Until GDPR Consent Source: https://docs.trackjs.com/browser-agent/tips-and-tricks/gdpr-consent This code snippet demonstrates how to use the TrackJS onError callback to intercept and store errors until user consent for data tracking is received. It assumes the TrackJS agent is installed but defers error submission. By default, TrackJS does not capture identifiable information, making this step optional for anonymous installations. ```javascript window.TrackJS.onError(function(error, options) { // Store the error and options locally // For example, using localStorage or a variable in scope // console.log('Error intercepted, waiting for consent:', error); return false; // Prevent immediate submission }); // When user consent is given: function grantConsentAndSubmitErrors() { // Retrieve stored errors and submit them using TrackJS.submit() or similar // console.log('Consent granted, submitting stored errors...'); // Example: TrackJS.submit(storedErrors); } ``` -------------------------------- ### GET /websites/trackjs Source: https://docs.trackjs.com/data-api/errors-by-day Retrieves the Error count by Day, sorted by date descending. Supports filtering by application, date range, and pagination. ```APIDOC ## GET /websites/trackjs ### Description This endpoint returns the Error count by Day, sorted by date descending. ### Method GET ### Endpoint /websites/trackjs ### Parameters #### Query Parameters - **application** (String) - Optional - Filter the results to only the Application key provided. - **endDate** (ISO 8601 String) - Optional - Filter the results to only return errors before this date. Time precision is within 1 second. - **startDate** (ISO 8601 String) - Optional - Filter the results to only return errors after this date. Time precision is within 1 second. - **page** (Number) - Optional - The page of data you want returned. By default, the first page of data is returned. See Paging. - **size** (Number) - Optional - The size of the page of data you want returned. By default, the first page of data is returned. See Paging. - **sort** (String) - Optional - By default the endpoint returns results sorted by date in descending order. You may adjust the sort field and sort direction. Supported fields are "date", "count" and "usercount". Sort directions are specified by appending "|asc" or "|desc". Default value is "date|desc" if not specified. ### Response #### Success Response (200) (Response structure not detailed in the provided text) #### Response Example (Response example not provided in the text) ``` -------------------------------- ### TrackJS Node.js: Express Request Handler Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Provides a request handling middleware for Express applications. It can optionally include a correlation header for linking client and server errors. This method requires the agent to be installed. ```javascript const expressRequestHandler = TrackJS.getMiddleware("expressRequestHandler", { correlationHeader: false }); app.use(expressRequestHandler); ``` -------------------------------- ### TrackJS Node.js: Express Error Handler Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Provides an error handling middleware for Express applications. It can optionally pass errors to the next handler. This method requires the agent to be installed. ```javascript const expressErrorHandler = TrackJS.getMiddleware("expressErrorHandler", { next: true }); app.use(expressErrorHandler); ``` -------------------------------- ### Server-Side Error Instrumentation with instrumentation.tsx Source: https://docs.trackjs.com/browser-agent/integrations/nextjs15 Captures server-side errors in NextJS (both App Router and Pages Router) by installing the TrackJS agent using the `instrumentation.tsx` file in the project root. This ensures errors in the NodeJS server context are tracked. ```typescript import TrackJS from 'trackjs'; export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { TrackJS.install({ token: 'YOUR_TRACKJS_TOKEN', // ... other settings ... }); } } ``` -------------------------------- ### TrackJS Node.js: Remove Metadata Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Removes one or more keys from the metadata store. Metadata associated with these keys will no longer be sent with reported errors. Requires the agent to be installed. ```javascript TrackJS.removeMetadata({ "key1": true, "key2": true }); TrackJS.removeMetadata("key"); ``` -------------------------------- ### TrackJS Node.js: Track Error Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Captures an error to TrackJS. If the provided parameter is not an Error object, one will be generated. Optional options can override agent settings for this specific error. Requires the agent to be installed. ```javascript try { // Some operation that might throw an error throw new Error("Something went wrong"); } catch (e) { TrackJS.track(e, { // Override options for this error }); } ``` -------------------------------- ### GET /websites/trackjs/errors/byhour Source: https://docs.trackjs.com/data-api/errors-by-hour Retrieves the count of errors per hour for a given website. Supports filtering by application, date range, and pagination, as well as custom sorting. ```APIDOC ## GET /websites/trackjs/errors/byhour ### Description This endpoint returns the Error count by hour, sorted by date descending. ### Method GET ### Endpoint `/websites/trackjs/errors/byhour` ### Parameters #### Query Parameters - **application** (String) - Optional - Filter the results to only the Application key provided. - **endDate** (ISO 8601 String) - Optional - Filter the results to only return errors before this date and time. Time precision is within 1 second. - **startDate** (ISO 8601 String) - Optional - Filter the results to only return errors after this date and time. Time precision is within 1 second. - **page** (Number) - Optional - The page of data you want returned. By default, the first page of data is returned. See Paging. - **size** (Number) - Optional - The size of the page of data you want returned. By default, the first page of data is returned. See Paging. (1-1000) - **sort** (Sort String) - Optional - By default the endpoint returns results sorted by date in descending order. You may adjust the sort field and sort direction. Supported fields are `"date"`, `"count"` and `"usercount"`. Sort directions are specified by appending `"|asc"` or `"|desc"`. Default value is `"date|desc"` if not specified. ### Request Example ```json { "example": "No request body for GET requests" } ``` ### Response #### Success Response (200) (Response structure not detailed in the provided text, but will contain error counts per hour) #### Response Example ```json { "example": "Response details not provided in the source text." } ``` ``` -------------------------------- ### GET /websites/trackjs Source: https://docs.trackjs.com/data-api/errors-by-url Retrieves a list of errors, counted by URL, sorted in descending order of error count. Supports filtering by application, date range, pagination, and custom sorting. ```APIDOC ## GET /websites/trackjs ### Description This endpoint returns the count of Error count by URL, sorted by count descending. It allows filtering by application, date range, and pagination, with flexible sorting options. ### Method GET ### Endpoint /websites/trackjs ### Parameters #### Query Parameters - **application** (String) - Optional - Filter the results to only the Application key provided. - **endDate** (ISO 8601 String) - Optional - Filter the results to only return errors before this date. Time precision is within 1 second. - **startDate** (ISO 8601 String) - Optional - Filter the results to only return errors after this date. Time precision is within 1 second. - **page** (Number) - Optional - The page of data you want returned. By default, the first page of data is returned. See Paging. - **size** (Number) - Optional - The size of the page of data you want returned. See Paging. (1-1000) - **sort** (Sort String) - Optional - By default the endpoint returns results sorted by date in descending order. You may adjust the sort field and sort direction. Supported fields are "count" and "usercount". Sort directions are specified by appending "|asc" or "|desc". Default value is "count|desc" if not specified. ### Response #### Success Response (200) - **url** (String) - The URL where the error occurred. - **count** (Number) - The number of times the error occurred at the specified URL. - **usercount** (Number) - The number of unique users affected by errors at the specified URL. #### Response Example ```json { "data": [ { "url": "/homepage", "count": 150, "usercount": 75 }, { "url": "/about", "count": 120, "usercount": 60 } ], "pagination": { "next_page": "?page=2&size=10", "prev_page": null } } ``` ``` -------------------------------- ### Custom AJAX Error Handler with jQuery for TrackJS Source: https://docs.trackjs.com/browser-agent/tips-and-tricks/include-network-payloads This example demonstrates how to add a custom error handler to a jQuery AJAX system to capture network error payloads and send them to TrackJS. It assumes TrackJS is configured to capture custom events. ```javascript $(function() { $.ajaxSetup({ error: function(jqXHR, textStatus, errorThrown) { TrackJS.track( 'AJAX Error: ' + textStatus + ' - ' + errorThrown, { status: jqXHR.status, payload: jqXHR.responseText } ); } }); }); ``` -------------------------------- ### TrackJS Node.js: Add Custom Error Handler Source: https://docs.trackjs.com/node-agent/sdk-reference/agent-methods Attaches a custom error handler to intercept and potentially modify or prevent error payloads from being captured. Handlers are executed in order, and the first to ignore an error stops further processing. Requires the agent to be installed. ```javascript TrackJS.onError(function(payload) { // Modify payload or return false to ignore return true; }); ``` -------------------------------- ### Post Custom Error Report using Fetch API Source: https://docs.trackjs.com/data-api/capture This example demonstrates how to send a custom error report to the TrackJS Capture API using the JavaScript `fetch` function. It specifies the content type and includes the necessary token. The API returns a 200 or 202 status code regardless of data validity due to high volume. ```javascript fetch('https://api.trackjs.com/capture?token=YOUR_TOKEN', { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: JSON.stringify({ message: 'Custom error message', url: window.location.href, timestamp: Date.now() }) }).then(response => { console.log('Capture API response status:', response.status); }).catch(error => { console.error('Error sending to Capture API:', error); }); ``` -------------------------------- ### Sanitize US Social Security Numbers in Console Logs (JavaScript) Source: https://docs.trackjs.com/data-management/sensitive This example demonstrates how to use a custom onError callback in TrackJS to sanitize United States Social Security Numbers (SSNs) from console logs. This prevents sensitive data from being sent to TrackJS while still allowing console logging for debugging. ```javascript TrackJS.configure({ onError: function(error) { // Sanitize SSNs from the error object before it's sent to TrackJS if (error.message) { error.message = error.message.replace(/\d{3}-\d{2}-\d{4}/g, '[SSN]'); } if (error.stack) { error.stack = error.stack.replace(/\d{3}-\d{2}-\d{4}/g, '[SSN]'); } // You can also inspect and modify error.request, error.browser, etc. return error; } }); ``` -------------------------------- ### TrackJS Agent Methods Source: https://docs.trackjs.com/browser-agent/sdk-reference/agent-methods This section details the various methods available in the TrackJS agent for error tracking and management. ```APIDOC ## addMetadata ### Description Add a key-value pair of data that will describe errors captured in this page view. If the metadata key already exists, it will be updated with the new value. ### Method `TrackJS.addMetadata(key, value)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **key** (string) - Required - The metadata key. - **value** (string) - Required - The metadata value for this page session. ### Request Example ```javascript TrackJS.addMetadata('userRole', 'admin'); ``` ### Response #### Success Response (200) - **undefined** - This function does not return a value. #### Response Example ```javascript // No return value ``` ## attempt ### Description Invoke a function with a `try-catch` wrapper and report any errors to TrackJS. Context to invoke the function and parameters can be passed as additional parameters. ### Method `TrackJS.attempt(callback, context, ...params)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **callback** (function) - Required - The function to invoke. - **context** (Object) - Optional - The context to invoke the function on (e.g., `this`). - **...params** (Any) - Optional - Parameters to pass to the function when invoked. ### Request Example ```javascript TrackJS.attempt(function() { throw new Error('Something went wrong!'); }); ``` ### Response #### Success Response (200) - ***** - The output from the invoked function. #### Response Example ```javascript // Returns the output of the callback function ``` ## configure ### Description Update the Agent Config after install. Not all options can be updated, see the `Changeable` flag in the Config SDK. ### Method `TrackJS.configure(options)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **options** (Object) - Required - Options to be updated. ### Request Example ```javascript TrackJS.configure({ token: 'new-token' }); ``` ### Response #### Success Response (200) - **boolean** - `true` if successful. #### Response Example ```javascript true ``` ## console.log ### Description Record a Telemetry event into the log with _default_ severity. This function is a private clone of the global `console.log` for context that is relevant for debugging but should not be displayed in the browser console. ### Method `TrackJS.console.log(...properties)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **...properties** (Any) - Required - Properties to be logged. ### Request Example ```javascript TrackJS.console.log('User logged in:', userData); ``` ### Response #### Success Response (200) - **undefined** - This function does not return a value. #### Response Example ```javascript // No return value ``` ## console.debug ### Description Record a Telemetry event into the log with _debug_ severity. This function is a private clone of the global `console.debug` for context that is relevant for debugging but should not be displayed in the browser console. ### Method `TrackJS.console.debug(...properties)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **...properties** (Any) - Required - Properties to be logged. ### Request Example ```javascript TrackJS.console.debug('Debug information:', data); ``` ### Response #### Success Response (200) - **undefined** - This function does not return a value. #### Response Example ```javascript // No return value ``` ## console.info ### Description Record a Telemetry event into the log with _info_ severity. This function is a private clone of the global `console.info` for context that is relevant for debugging but should not be displayed in the browser console. ### Method `TrackJS.console.info(...properties)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **...properties** (Any) - Required - Properties to be logged. ### Request Example ```javascript TrackJS.console.info('Information:', message); ``` ### Response #### Success Response (200) - **undefined** - This function does not return a value. #### Response Example ```javascript // No return value ``` ## console.warn ### Description Record a Telemetry event into the log with _warning_ severity. This function is a private clone of the global `console.warn` for context that is relevant for debugging but should not be displayed in the browser console. ### Method `TrackJS.console.warn(...properties)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **...properties** (Any) - Required - Properties to be logged. ### Request Example ```javascript TrackJS.console.warn('Potential issue:', warning); ``` ### Response #### Success Response (200) - **undefined** - This function does not return a value. #### Response Example ```javascript // No return value ``` ## console.error ### Description Record a Telemetry event into the log with _error_ severity. If the `console.error` option is on (default), this will also send an error report. This function is a private clone of the global `console.error`. ### Method `TrackJS.console.error(...properties)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **...properties** (Any) - Required - Properties to be logged. ### Request Example ```javascript TrackJS.console.error('An error occurred:', errorObject); ``` ### Response #### Success Response (200) - **undefined** - This function does not return a value. #### Response Example ```javascript // No return value ``` ## install ### Description Installs the agent into the current document and starts reporting errors with the provided Config options. Before `3.0.0`, initialization was automatic on script load, and Config was passed via `window._trackJs`. ### Method `TrackJS.install(config)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **config** (Config) - Required - Options to install with. ### Request Example ```javascript TrackJS.install({ token: 'YOUR_TRACKJS_TOKEN' }); ``` ### Response #### Success Response (200) - **boolean** - `true` if successful. #### Response Example ```javascript true ``` ## isInstalled ### Description Checks whether the agent has been installed into the current environment. ### Method `TrackJS.isInstalled()` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```javascript if (TrackJS.isInstalled()) { console.log('TrackJS is installed.'); } ``` ### Response #### Success Response (200) - **boolean** - `true` if the agent is installed, `false` otherwise. #### Response Example ```javascript true ``` ## removeMetadata ### Description Removes a key and its associated value from the metadata store for this page session. The key will no longer be included with reported errors. ### Method `TrackJS.removeMetadata(key)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **key** (string) - Required - The metadata key to remove. ### Request Example ```javascript TrackJS.removeMetadata('userRole'); ``` ### Response #### Success Response (200) - **undefined** - This function does not return a value. #### Response Example ```javascript // No return value ``` ``` -------------------------------- ### Usage by Hour API Source: https://docs.trackjs.com/data-api/usage-by-hour This endpoint returns account usage statistics by hour, sorted by date ascending. Usage data is for your entire account and is not broken down by application. ```APIDOC ## GET /websites/trackjs/usage/hourly ### Description This endpoint returns account usage statistics by hour, sorted by date ascending. Usage data is for you entire account and is not broken down by application. ### Method GET ### Endpoint /websites/trackjs/usage/hourly ### Parameters #### Query Parameters - **startDate** (ISO 8601 String) - Optional - Filter the results to only return usage data from after this date and time. - **endDate** (ISO 8601 String) - Optional - Filter the results to only return usage data from before this date and time. ### Response #### Success Response (200) - **usage_data** (Array) - Array of usage statistics objects, each containing hour, date, and usage count. #### Response Example ```json { "usage_data": [ { "hour": 0, "date": "2023-10-27", "usage": 150 }, { "hour": 1, "date": "2023-10-27", "usage": 130 } ] } ``` ``` -------------------------------- ### trackJs.watchAll Returns Object for Chaining Initializations Source: https://docs.trackjs.com/browser-agent/changelog This bugfix modifies `trackJs.watchAll` to return the object itself, enabling method chaining for initializations. This improves the developer experience by allowing multiple initialization steps to be chained together fluently. ```javascript `trackJs.watchAll` returns the object for chaining initializations. ``` -------------------------------- ### Enable Instrumentation in NextJS 14 Source: https://docs.trackjs.com/node-agent/integrations/nextjs Enables the execution of `instrumentation.tsx` in NextJS 14 by creating a `next.config.js` file with the `experimental.instrumentation` flag set to true. This is required as NextJS 14 does not execute this file by default. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { instrumentation: true, }, }; module.exports = nextConfig; ``` -------------------------------- ### Manual Error Tracking with TrackJS (JavaScript) Source: https://docs.trackjs.com/data-management/ad-blockers Demonstrates how to manually send a test error using the TrackJS agent. This is useful for verifying that your TrackJS configuration, including domain forwarding, is working correctly. The error message 'testing proxy' will appear in your TrackJS account if successful. ```javascript TrackJS.track('testing proxy'); ``` -------------------------------- ### Add Checks for TrackJS Preconfiguration Aliases Source: https://docs.trackjs.com/browser-agent/changelog This update adds checks for alternative casing of the `_trackJS` variable (`_trackjs` and `_trackjs`). This improves the robustness of preconfiguration by accommodating different capitalization styles. ```plaintext Added checks for `_trackJS` and `_trackjs` (in addition to `_trackJs`) for preconfig. ``` -------------------------------- ### Support Multiple Applications Under Single Account Source: https://docs.trackjs.com/browser-agent/changelog This feature introduces support for managing multiple applications within a single TrackJS account. This allows users to consolidate tracking for different projects or environments under one umbrella. ```plaintext Added support for multiple applications under a single account. ``` -------------------------------- ### Add trackJs.watchAll() Support for Watching Function Objects Source: https://docs.trackjs.com/browser-agent/changelog This feature introduces `trackJs.watchAll()`, which allows watching multiple functions within an object. This simplifies the process of instrumenting multiple functions for error tracking. ```plaintext Added `trackJs.watchAll()` supports watching objects of functions ``` -------------------------------- ### POST /websites/trackjs Source: https://docs.trackjs.com/data-api/usage Submit page view records to the Usage API for processing. This endpoint helps monitor application traffic and attribute errors to specific issues or traffic volumes. ```APIDOC ## POST /websites/trackjs ### Description Submit page view records to the Usage API for processing. This endpoint helps monitor application traffic and attribute errors to specific issues or traffic volumes. ### Method POST ### Endpoint /websites/trackjs ### Parameters #### Query Parameters - **application** (String) - Optional - Attribute the traffic to the application key. - **correlationId** (String) - Optional - Attribute the traffic to the user-generated correlation Id. - **token** (String) - Required - The token identifies error traffic for your account. Get this from the install page. ### Request Example (No explicit request body is defined, parameters are expected as query parameters) ### Response #### Success Response (200) - The response is a 1x1 transparent gif. ``` -------------------------------- ### Enable instrumentation.tsx Execution (NextJS 14) Source: https://docs.trackjs.com/browser-agent/integrations/nextjs15 Enables the execution of `instrumentation.tsx` in NextJS 14 by creating a `next.config.js` file. This is a required additional step for NextJS 14 to ensure server-side instrumentation is active. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { experimental: { instrumentationHooks: true, }, } module.exports = nextConfig ``` -------------------------------- ### Add Option to Capture Bind-Time Stacktrace Source: https://docs.trackjs.com/browser-agent/changelog This feature introduces an option to capture a stacktrace at the time of binding. This can be useful for understanding the origin of functions and tracking their initialization context. ```plaintext Added option to capture a bind-time stacktrace ``` -------------------------------- ### Add trackJs.attempt() to Execute and Catch Function Errors Source: https://docs.trackjs.com/browser-agent/changelog This feature introduces `trackJs.attempt()`, which executes a single function and catches any errors it throws. This provides a safe way to run potentially error-prone code and have errors automatically reported. ```plaintext Added `trackJs.attempt()` executes a single function and catches errors from it ``` -------------------------------- ### Add trackJs.track() Support for Objects, Strings, and Errors Source: https://docs.trackjs.com/browser-agent/changelog This feature enhances `trackJs.track()` to accept objects, strings, or existing error objects as arguments. This provides more flexibility in how errors can be manually reported. ```plaintext Added `trackJs.track()` now supports objects, strings, or error objects ``` -------------------------------- ### Configure TrackJS Agent for Domain Forwarding (JavaScript) Source: https://docs.trackjs.com/data-management/ad-blockers This snippet shows how to configure the TrackJS agent to use a custom forwarding domain. This is essential when using domain forwarding to bypass ad blockers. Ensure the `forwardingDomain` matches your configured CNAME. ```javascript TrackJS.configure({ token: 'YOUR_TOKEN', forwardingDomain: 'errors.your_domain.com', // other configurations }); ``` -------------------------------- ### Ensure window.onerror Includes All Possible Information Source: https://docs.trackjs.com/browser-agent/changelog This bugfix ensures that `window.onerror` messages now include all available information. This provides a more complete picture of errors occurring in the browser, aiding in debugging. ```plaintext Fixed bug where `window.onerror` messages would not include all possible information. ``` -------------------------------- ### Handle SyntaxError in Chrome with Missing File/Column/Line Source: https://docs.trackjs.com/browser-agent/changelog This bugfix improves error handling in Chrome for `SyntaxError` exceptions where file, column, and line number information might be missing. The system now correctly handles these cases without errors. ```plaintext Fixed bug with handling of SyntaxError in Chrome where file, column, and line are not populated. ``` -------------------------------- ### Deprecate trackAll() Source: https://docs.trackjs.com/browser-agent/changelog The `trackAll()` function has been deprecated. Developers should migrate to the newer `trackJs.watchAll()` function for watching multiple functions. ```plaintext Deprecated `trackAll()` ```