### Install and Setup Dependencies Source: https://github.com/hyperdxio/hyperdx-js/blob/main/smoke-tests/hello-node-express-ts/README.md Run this command to install project dependencies and set up the environment. ```bash npm run setup ``` -------------------------------- ### Install Node.js Logger with npm Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-logger/README.md Install the Node.js logger package using npm. ```sh npm install @hyperdx/node-logger ``` -------------------------------- ### Install HyperDX Browser SDK Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Install the HyperDX Browser SDK using npm. This is the first step to integrating HyperDX into your project. ```bash npm install @hyperdx/browser ``` -------------------------------- ### Install Sentry Node Instrumentation Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/instrumentation-sentry-node/README.md Install the Sentry Node instrumentation package using npm. ```bash npm install --save @hyperdx/instrumentation-sentry-node ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Installs project dependencies using Yarn Classic from the repository root. ```bash yarn install ``` -------------------------------- ### Install Node.js Logger with Yarn Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-logger/README.md Install the Node.js logger package using yarn. ```sh yarn add @hyperdx/node-logger ``` -------------------------------- ### Run Main Application with HTTP/Protobuf Source: https://github.com/hyperdxio/hyperdx-js/blob/main/smoke-tests/hello-node-express-ts/README.md Start the application with HyperDX API key and service name configured for HTTP/Protobuf export. ```bash HYPERDX_API_KEY={apikey} OTEL_SERVICE_NAME="hello-node-express-ts" npm start ``` -------------------------------- ### Run Main Application with gRPC Source: https://github.com/hyperdxio/hyperdx-js/blob/main/smoke-tests/hello-node-express-ts/README.md Start the application with HyperDX API key and service name configured for gRPC export. ```bash HYPERDX_API_KEY={apikey} OTEL_SERVICE_NAME="hello-node-express-ts" OTEL_EXPORTER_OTLP_PROTOCOL=grpc npm start ``` -------------------------------- ### Install HyperDX OpenTelemetry Package Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Install the HyperDX OpenTelemetry Node.js package using npm or yarn. ```sh npm install @hyperdx/node-opentelemetry ``` ```sh yarn add @hyperdx/node-opentelemetry ``` -------------------------------- ### Run Application with Manual Instrumentation Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Execute your application using `ts-node` and the custom instrumentation file. This method allows for more granular control over SDK setup. ```sh npx ts-node -r './instrument.ts' index.ts ``` -------------------------------- ### Basic JavaScript Logging Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/performance-tests/devServer/index.html A simple example of logging to the console in JavaScript. ```javascript console.log('hello'); ``` -------------------------------- ### Triggering JavaScript Functions via Links Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/performance-tests/devServer/index.html Examples of creating links that execute JavaScript functions when clicked. ```html [Change name](javascript:clicky()) [Change name after fetch](javascript:clicky()) ``` -------------------------------- ### Setup Winston Transport Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-logger/README.md Configure and create a HyperDX Winston Transport to append to your existing Winston logger transports. Ensure your API key and service name are provided. ```javascript import winston from 'winston'; import { HyperDXWinston } from '@hyperdx/node-logger'; const hyperdxTransport = new HyperDXWinston({ apiKey: ***HYPERDX_API_KEY***, maxLevel: 'info', service: 'my-app', }); const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.Console(), hyperdxTransport, // append this to the existing transports ], }); export default logger; ``` -------------------------------- ### Setup Pino Transport Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-logger/README.md Configure and create a HyperDX Pino Transport by specifying the target and options within the pino transport configuration. The API key and service name are required options. ```javascript import pino from 'pino'; const logger = pino( pino.transport({ targets: [ { target: '@hyperdx/node-logger/build/src/pino', options: { apiKey: ***HYPERDX_API_KEY***, service: 'my-app', }, level: 'info', }, // other transports ], }), ); export default logger; ``` -------------------------------- ### Run Tests in Watch Mode Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Starts Jest in watch mode for continuous testing during development. Commands may differ slightly per package. ```bash cd packages/node-opentelemetry && yarn dev:unit # jest --watchAll cd packages/instrumentation-exception && yarn test:watch # jest --watch ``` -------------------------------- ### Regenerate Self-Signed Certificates Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/utils/certs/README.md Use this command to regenerate self-signed certificate files for local testing purposes. Ensure OpenSSL is installed and accessible in your environment. ```bash openssl req -nodes -new -x509 -keyout server.key -out server.cert ``` -------------------------------- ### NestJS Custom Logger Setup Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-logger/README.md Import and configure the HyperDXNestLoggerModule using forRoot() in your AppModule to enable HyperDX logging within a NestJS application. This sets up the logger for injection across the project. ```javascript import { Module } from '@nestjs/common'; import { HyperDXNestLoggerModule } from '@hyperdx/node-logger'; @Module({ imports: [ HyperDXNestLoggerModule.forRoot({ apiKey: ***HYPERDX_API_KEY***, maxLevel: 'info', service: 'my-app', }), ], }) export class AppModule {} ``` -------------------------------- ### Retrieve Current Session ID Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Call the `getSessionId` function from the HyperDX SDK to get the current session identifier. ```javascript const sessionId = HyperDX.getSessionId(); ``` -------------------------------- ### Build and Run JavaScript Files Source: https://github.com/hyperdxio/hyperdx-js/blob/main/smoke-tests/hello-node-express-ts/README.md Build the TypeScript project to JavaScript and then run the built application. ```bash npm install npm run build npm run start-js ``` -------------------------------- ### Initialize HyperDX SDK Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Initialize the HyperDX SDK with your API key and service name. Configure options like trace propagation, console capture, and network capture. ```javascript import HyperDX from '@hyperdx/browser'; HyperDX.init({ apiKey: '', service: 'my-frontend-app', tracePropagationTargets: [/api.myapp.domain/i], // Set to link traces from frontend to backend requests consoleCapture: true, // Capture console logs (default false) advancedNetworkCapture: true, // Capture full HTTP request/response headers and bodies (default false) otelResourceAttributes: { 'service.version': '1.0.0', 'deployment.environment': 'production', }, }); ``` -------------------------------- ### Run Application with Custom Entry Point (ts-node) Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Use `ts-node` with the `@hyperdx/node-opentelemetry` tracing module to run your application. This is an alternative to the CLI. ```sh npx ts-node -r '@hyperdx/node-opentelemetry/build/src/tracing' index.ts ``` -------------------------------- ### Build All Packages with Nx Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Builds all packages in the monorepo, respecting dependency order managed by Nx. ```bash yarn ci:build # npx nx run-many --target=build ``` -------------------------------- ### Add Custom 3rd-Party Instrumentation Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md When manually initializing the SDK, use the additionalInstrumentations key to include custom third-party instrumentation packages like RemixInstrumentation. ```js // In your instrument.js/ts file... const { initSDK } = require('@hyperdx/node-opentelemetry'); const { RemixInstrumentation } = require('opentelemetry-instrumentation-remix'); initSDK({ consoleCapture: true, // optional, default: true additionalInstrumentations: [new RemixInstrumentation()], // your custom instrumentations here }); ``` -------------------------------- ### Initialize HyperDX Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Initializes the HyperDX SDK with essential configuration options. This is a required step before using other SDK functionalities. ```APIDOC ## Initialize HyperDX ### Description Initializes the HyperDX SDK with essential configuration options. This is a required step before using other SDK functionalities. ### Method `HyperDX.init(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **apiKey** (string) - Required - Your HyperDX Ingestion API Key. - **service** (string) - Required - The service name events will show up as in HyperDX. - **tracePropagationTargets** (Array) - Optional - A list of regex patterns to match against HTTP requests to link frontend and backend traces. - **consoleCapture** (boolean) - Optional - Capture all console logs (default `false`). - **advancedNetworkCapture** (boolean) - Optional - Capture full HTTP request/response headers and bodies (default `false`). - **url** (string) - Optional - The OpenTelemetry collector URL, only needed for self-hosted instances. - **maskAllInputs** (boolean) - Optional - Whether to mask all input fields in session replay (default `false`). - **maskAllText** (boolean) - Optional - Whether to mask all text in session replay (default `false`). - **disableIntercom** (boolean) - Optional - Whether to disable Intercom integration (default `false`). - **otelResourceAttributes** (object) - Optional - Object containing OpenTelemetry resource attributes to be added to all spans. - **disableReplay** (boolean) - Optional - Whether to disable session replay (default `false`). - **recordCanvas** (boolean) - Optional - Whether to record canvas elements (default `false`). - **sampling** (object) - Optional - The sampling configuration for session recording. ### Request Example ```js import HyperDX from '@hyperdx/browser'; HyperDX.init({ apiKey: '', service: 'my-frontend-app', tracePropagationTargets: [/api.myapp.domain/i], consoleCapture: true, advancedNetworkCapture: true, otelResourceAttributes: { 'service.version': '1.0.0', 'deployment.environment': 'production', }, }); ``` ### Response None ``` -------------------------------- ### Run Smoke Tests Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Executes smoke tests. 'make smoke-sdk' runs HTTP + gRPC smoke tests, while 'make smoke' runs all BATS tests. ```bash make smoke-sdk # run HTTP + gRPC smoke tests make smoke # run all BATS tests ``` -------------------------------- ### Manually Instrument SDK with initSDK Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Manually initialize the OpenTelemetry SDK using `initSDK` in a separate instrumentation file. Configure options like console capture and resource attributes. ```ts import { initSDK } from '@hyperdx/node-opentelemetry'; initSDK({ consoleCapture: true, // optional, default: true additionalInstrumentations: [], // optional, default: [] additionalResourceAttributes: { // optional, default: {} // Add custom resource attributes to all telemetry data 'environment': 'production', 'deployment.version': '1.0.0', 'custom.attribute': 'value' }, }); // Other instrumentation code... // Details link: https://opentelemetry.io/docs/instrumentation/js/manual/#manual-instrumentation-setup ``` -------------------------------- ### Connect to WebSocket Server Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/utils/devServer/index.html Adds an event listener to establish a WebSocket connection. It dynamically constructs the WebSocket URL using parameters from the current URL. ```javascript let socket; document.getElementById('connectWebsocketsBtn').addEventListener('click', () => { const params = new URLSearchParams(window.location.search); socket = new WebSocket( `${params.get('wsProtocol')}://${ document.location.hostname }:${params.get('wsPort')}/`, ); }); ``` -------------------------------- ### Build a Single Package with Nx Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Builds a specific package using Nx. Alternatively, navigate to the package directory and run 'yarn build'. ```bash npx nx run @hyperdx/node-opentelemetry:build # Or from the package directory: cd packages/node-opentelemetry && yarn build ``` -------------------------------- ### Run otel-web Unit Tests Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Executes unit tests for the 'otel-web' package. Use 'test:unit:ci-node' for Node tests and 'test:unit:ci' for browser tests (ChromeHeadless). ```bash cd packages/otel-web && yarn test:unit:ci-node # Mocha node tests cd packages/otel-web && yarn test:unit:ci # Karma browser tests (ChromeHeadless) ``` -------------------------------- ### Connect to WebSocket Server Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/performance-tests/devServer/index.html Adds an event listener to establish a WebSocket connection. The connection URL is dynamically constructed using URL parameters and the current document location. ```javascript let socket; document.getElementById('connectWebsocketsBtn').addEventListener('click', () => { const params = new URLSearchParams(window.location.search); socket = new WebSocket( `${params.get('wsProtocol')}://${ document.location.hostname }:${params.get('wsPort')}/`, ); }); ``` -------------------------------- ### Perform Fetch Request Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/utils/devServer/index.html Sets up an event handler to perform a fetch request and log the JSON response. This is a standard way to retrieve data from an API. ```javascript regularFetchBtn.onclick = () => { fetch('/some-data') .then((response) => response.json()) .then(console.log); }; ``` -------------------------------- ### Configure Custom Resource Attributes Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Initialize the SDK with additional resource attributes to describe the service, such as environment, version, and region. These attributes are attached to all exported telemetry data. ```ts import { initSDK } from '@hyperdx/node-opentelemetry'; initSDK({ additionalResourceAttributes: { 'deployment.environment': process.env.NODE_ENV || 'development', 'service.version': process.env.APP_VERSION || '0.0.0', 'service.namespace': 'my-namespace', 'cloud.region': process.env.AWS_REGION, // Add any custom attributes your organization needs 'team.name': 'backend-team', 'feature.flag': 'new-checkout-flow' }, }); ``` -------------------------------- ### Initialize Sentry Node Instrumentation Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/instrumentation-sentry-node/README.md Initialize the SentryNodeInstrumentation with a NodeTracerProvider and register it with OpenTelemetry. ```javascript const { SentryNodeInstrumentation, } = require('@hyperdx/instrumentation-sentry-node'); const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node'); const { registerInstrumentations } = require('@opentelemetry/instrumentation'); const provider = new NodeTracerProvider(); provider.register(); registerInstrumentations({ instrumentations: [new SentryNodeInstrumentation()], }); ``` -------------------------------- ### Test Local Changes with HyperDX CLI Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/cli/README.md Run these commands to build the project and test your local changes to the CLI. ```sh yarn build node dist/index.js upload ... ``` -------------------------------- ### Run Application with HyperDX OpenTelemetry CLI Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Execute your application using the `opentelemetry-instrument` CLI for automatic instrumentation. ```sh npx opentelemetry-instrument index.js ``` -------------------------------- ### Configure Source Map Upload as npm Script Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/cli/README.md Add this script to your package.json for easy execution of the source map upload command. ```json // In package.json { "scripts": { "upload-sourcemaps": "npx @hyperdx/cli upload-sourcemaps --path=\"/path/to/sourcemaps\"" } } ``` -------------------------------- ### Run Application with Custom Instrumentation Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Execute your Node.js application using the -r flag to require the custom instrumentation file before your main application file. ```sh node -r './instrument.js' index.js ``` -------------------------------- ### Run All Unit Tests with Nx Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Executes all unit tests across the monorepo, managed by Nx. ```bash yarn ci:unit # npx nx run-many --target=ci:unit ``` -------------------------------- ### Manual Prettier Formatting Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Manually formats code according to Prettier guidelines. This command should be run from any package directory. ```bash yarn prettier ``` -------------------------------- ### Lint All Packages with Nx Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Lints all packages in the monorepo, respecting dependency order managed by Nx. ```bash yarn ci:lint # npx nx run-many --target=ci:lint ``` -------------------------------- ### Upload Source Maps with HyperDX CLI Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/cli/README.md Use this command in your build pipeline to upload source maps. Ensure you replace the placeholder path and service key with your actual values. ```sh npx @hyperdx/cli upload-sourcemaps --path="/path/to/sourcemaps" --serviceKey="your-service-account-api-key" ``` -------------------------------- ### Build Smoke Test Docker Images Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Builds the Docker images required for running smoke tests using Docker Compose. ```bash make build-smoke-images # docker compose build ``` -------------------------------- ### Enable Beta Mode for Trace Attributes Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Set the HDX_NODE_BETA_MODE environment variable to 1 to enable beta features like attaching user information to traces. ```sh export HDX_NODE_BETA_MODE=1 ``` -------------------------------- ### Configure OpenTelemetry Logger for Deno std/log Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/deno/README.md Set up a custom logger for the std/log module to export logs to OpenTelemetry. Ensure the OpenTelemetryHandler is imported and configured with the desired log level. ```typescript import * as log from 'https://deno.land/std@0.203.0/log/mod.ts'; import { OpenTelemetryHandler } from 'npm:@hyperdx/deno'; log.setup({ handlers: { otel: new OpenTelemetryHandler('DEBUG'), }, loggers: { 'my-otel-logger': { level: 'DEBUG', handlers: ['otel'], }, }, }); log.getLogger('my-otel-logger').info('Hello from Deno!'); ``` -------------------------------- ### Initialize SplunkRum Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/utils/devServer/index.html Initializes the SplunkRum agent with the specified configuration. Ensure this is called early in your application's lifecycle. ```javascript window.SplunkRum && window.SplunkRum.init({ beaconEndpoint: '/api/v2/spans', applicationName: 'splunk-otel-js-dummy-app', debug: true, }); ``` -------------------------------- ### TypeScript Import Ordering Convention Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Illustrates the conventional order for TypeScript imports, separating external packages from internal/relative imports with a blank line. ```typescript // 1. External packages (alphabetical) import { diag, trace } from '@opentelemetry/api'; import { InstrumentationBase } from '@opentelemetry/instrumentation'; // 2. Internal/relative imports (separated by blank line) import { name as PKG_NAME, version as PKG_VERSION } from '../package.json'; import { parseHeaders } from './utils'; ``` -------------------------------- ### Test the Application Endpoint Source: https://github.com/hyperdxio/hyperdx-js/blob/main/smoke-tests/hello-node-express-ts/README.md Use curl to send a request to the running application and verify the response. ```bash curl localhost:3000 ``` -------------------------------- ### Configure Environment Variables for HyperDX Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Set the HYPERDX_API_KEY and OTEL_SERVICE_NAME environment variables to ship telemetry to HyperDX. For self-hosted users, also set OTEL_EXPORTER_OTLP_ENDPOINT. ```sh export HYPERDX_API_KEY= \ OTEL_SERVICE_NAME='' ``` -------------------------------- ### Enable Network Capture Dynamically Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Dynamically enable advanced network capture to include full HTTP request/response headers and bodies. ```javascript HyperDX.enableAdvancedNetworkCapture(); ``` -------------------------------- ### Specify Custom HTTP Headers for Capture Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Configure specific headers to be captured for client requests and responses by setting environment variables like OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST. ```sh export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST=authorization,accept ``` -------------------------------- ### Run Unit Tests in a Single Package Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Runs unit tests for a specific package. The command may vary depending on the package's test runner (e.g., Jest or yarn test). ```bash cd packages/node-opentelemetry && npx jest cd packages/instrumentation-exception && yarn test cd packages/session-recorder && yarn test ``` -------------------------------- ### Enable Advanced Network Capture Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Set the HDX_NODE_ADVANCED_NETWORK_CAPTURE environment variable to 1 to enable the SDK to capture full HTTP request/response headers and bodies. ```sh export HDX_NODE_ADVANCED_NETWORK_CAPTURE=1 ``` -------------------------------- ### Run a Single Test File Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Executes a specific test file within a package using Jest, identified by a pattern. ```bash cd packages/node-opentelemetry && npx jest --testPathPattern="otel\.test" ``` -------------------------------- ### Enable Network Capture Dynamically Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Dynamically enables advanced network capture, which includes full HTTP request/response headers and bodies. ```APIDOC ## Enable Network Capture Dynamically ### Description Dynamically enables advanced network capture, which includes full HTTP request/response headers and bodies. ### Method `HyperDX.enableAdvancedNetworkCapture()` ### Parameters None ### Request Example ```js HyperDX.enableAdvancedNetworkCapture(); ``` ### Response None ``` -------------------------------- ### Resume Session Recorder Dynamically Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Dynamically resumes the session recording. ```APIDOC ## Resume Session Recorder Dynamically ### Description Dynamically resumes the session recording. ### Method `HyperDX.resumeSessionRecorder()` ### Parameters None ### Request Example ```js HyperDX.resumeSessionRecorder(); ``` ### Response None ``` -------------------------------- ### Handle Promise Rejection Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/utils/devServer/index.html Sets up an event handler to manually trigger an unhandled promise rejection. This is useful for testing error tracking. ```javascript rejectBtn.onclick = () => { Promise.reject('manual reject'); }; ``` -------------------------------- ### Set Global Attributes Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Attaches user information or metadata to the current client session and all subsequent events. Useful for searching and filtering sessions. ```APIDOC ## Set Global Attributes ### Description Attaches user information or metadata to the current client session and all subsequent events. Useful for searching and filtering sessions. ### Method `HyperDX.setGlobalAttributes(attributes)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **attributes** (object) - Required - An object containing user information and custom properties. Supported properties include `userId`, `userEmail`, `userName`, and `teamName`. Any other properties will be treated as custom attributes. ### Request Example ```js HyperDX.setGlobalAttributes({ userId: user.id, userEmail: user.email, userName: user.name, teamName: user.team.name, // Other custom properties... }); ``` ### Response None ``` -------------------------------- ### Send Custom Action Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Explicitly tracks a specific application event with an event name and optional metadata. ```APIDOC ## Send Custom Action ### Description Explicitly tracks a specific application event with an event name and optional metadata. ### Method `HyperDX.addAction(eventName, eventMetadata)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **eventName** (string) - Required - The name of the event to track. - **eventMetadata** (object) - Optional - An object containing metadata about the event. ### Request Example ```js HyperDX.addAction('Form-Completed', { formId: 'signup-form', formName: 'Signup Form', formType: 'signup', }); ``` ### Response None ``` -------------------------------- ### Set Global Attributes Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Attach user information or metadata to the current session and all subsequent events. This allows for easier searching and filtering in HyperDX. ```javascript HyperDX.setGlobalAttributes({ userId: user.id, userEmail: user.email, userName: user.name, teamName: user.team.name, // Other custom properties... }); ``` -------------------------------- ### Stop/Resume Session Recorder Dynamically Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Control the session recording dynamically by invoking `resumeSessionRecorder` or `stopSessionRecorder`. ```javascript HyperDX.resumeSessionRecorder(); ``` -------------------------------- ### Run Tests by Name Pattern Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Executes tests within a package that match a specific name pattern using Jest. ```bash cd packages/node-opentelemetry && npx jest --testNamePattern="console" ``` -------------------------------- ### Lint a Single Package Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Lints a specific package. Use 'yarn lint' for ESLint only or 'yarn ci:lint' for ESLint and tsc --noEmit. ```bash cd packages/node-opentelemetry && yarn lint # ESLint only cd packages/node-opentelemetry && yarn ci:lint # ESLint + tsc --noEmit ``` -------------------------------- ### Enable Resource Timing for CORS Requests Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md This snippet demonstrates how to configure an Express.js server with the `cors` and `on-headers` packages to add the `Timing-Allow-Origin` header. This header is crucial for capturing fine-grained resource timing information for cross-origin requests. ```APIDOC ## Enable Resource Timing for CORS Requests ### Description If your frontend application makes API requests to a different domain, you can optionally enable the `Timing-Allow-Origin` header to be sent with the request. This will allow HyperDX to capture fine-grained resource timing information for the request such as DNS lookup, response download, etc. via `PerformanceResourceTiming`. ### Usage If you're using `express` with `cors` packages, you can use the following snippet to enable the header: ### Code Example ```javascript var cors = require('cors'); var onHeaders = require('on-headers'); // ... all your stuff app.use(function (req, res, next) { onHeaders(res, function () { var allowOrigin = res.getHeader('Access-Control-Allow-Origin'); if (allowOrigin) { res.setHeader('Timing-Allow-Origin', allowOrigin); } }); next(); }); app.use(cors()); ``` ``` -------------------------------- ### Send Custom Actions Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Explicitly track specific application events, such as form submissions or sign-ups, by calling `addAction` with an event name and optional metadata. ```javascript HyperDX.addAction('Form-Completed', { formId: 'signup-form', formName: 'Signup Form', formType: 'signup', }); ``` -------------------------------- ### Add Pino Logger Transport Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Configure Pino logger to include the HyperDX transport for collecting logs. The mixin function and transport targets need to be set. ```ts import pino from 'pino'; import * as HyperDX from '@hyperdx/node-opentelemetry'; const MAX_LEVEL = 'info'; const logger = pino({ mixin: HyperDX.getPinoMixinFunction, transport: { targets: [ HyperDX.getPinoTransport(MAX_LEVEL), // other transports ], }, }); export default logger; ``` -------------------------------- ### Add Winston Logger Transport Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Configure Winston logger to include the HyperDX transport for collecting logs. Ensure the MAX_LEVEL is set appropriately. ```ts import winston from 'winston'; import * as HyperDX from '@hyperdx/node-opentelemetry'; const MAX_LEVEL = 'info'; const logger = winston.createLogger({ level: MAX_LEVEL, format: winston.format.json(), transports: [ new winston.transports.Console(), HyperDX.getWinstonTransport(MAX_LEVEL), // append this to the existing transports ], }); export default logger; ``` -------------------------------- ### Handle Route Change After Fetch Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/utils/devServer/index.html Adds an event listener that performs a fetch request and then updates the browser's history state upon successful completion. This demonstrates asynchronous route updates. ```javascript document.getElementById('routeAfterFetch').addEventListener('click', function () { fetch('page2.html').then(function (response) { history.pushState({}, 'title', '/thisIsSetAfterFetch'); }); }); ``` -------------------------------- ### Jest Configuration for ESM Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Configuration for Jest to support ES Modules (ESM) in TypeScript projects. Ensure this is set up in your Jest configuration file. ```javascript preset: 'ts-jest/presets/default-esm', transform: { '^.+\.m?[tj]s?$': ['ts-jest', { useESM: true }] } ``` -------------------------------- ### JavaScript Function Definitions Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/performance-tests/devServer/index.html Defines several utility functions for logging and error handling. ```javascript function whenDone() { console.log('whenDone'); } function throwit() { throw new Error('oh no'); } function clicky() { console.log('clicky'); } ``` -------------------------------- ### Create and Use HyperDX Logger in NestJS Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-logger/README.md Instantiate the HyperDX logger outside the NestJS application lifecycle and pass it to NestFactory.create. This ensures the logger is available during application bootstrapping. Remove `forRoot` and `forRootAsync` from your main module when using this approach. ```typescript import { HyperDXNestLoggerModule } from '@hyperdx/node-logger'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: HyperDXNestLoggerModule.createLogger({ apiKey: ***HYPERDX_API_KEY***, maxLevel: 'info', service: 'my-app', }) }); await app.listen(3000); } bootstrap(); ``` ```typescript import { Logger, Module } from '@nestjs/common'; @Module({ providers: [Logger], }) export class AppModule {} ``` ```typescript import { Controller, Logger } from '@nestjs/common'; @Controller('cats') export class CatsController { constructor(private readonly logger: Logger) {} meow() { this.logger.log({ message: '🐱' }); } } ``` -------------------------------- ### Handle Route Change Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/utils/devServer/index.html Adds an event listener to change the browser's history state when a specific element is clicked. This is useful for single-page applications. ```javascript document.getElementById('route').addEventListener('click', function () { history.pushState({}, 'title', '/thisIsArtificiallySet'); }); ``` -------------------------------- ### Attach User Information to Current Trace Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Use the setTraceAttributes function to tag all logs and spans within the current trace with user-specific identifiers. Recommended to call early in the request lifecycle. ```ts import { setTraceAttributes } from '@hyperdx/node-opentelemetry'; app.use((req, res, next) => { // Get user information from the request... // Attach user information to the current trace setTraceAttributes({ userId, userEmail, }); next(); }); ``` -------------------------------- ### Enable Resource Timing for CORS Requests with Express Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Configure your Express server to send the 'Timing-Allow-Origin' header for CORS requests. This allows HyperDX to capture detailed resource timing information. ```javascript var cors = require('cors'); var onHeaders = require('on-headers'); // ... all your stuff app.use(function (req, res, next) { onHeaders(res, function () { var allowOrigin = res.getHeader('Access-Control-Allow-Origin'); if (allowOrigin) { res.setHeader('Timing-Allow-Origin', allowOrigin); } }); next(); }); app.use(cors()); ``` -------------------------------- ### Trigger Click Event Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/otel-web/utils/devServer/index.html Simulates a click event to log a message. This can be used for testing or simple interactions. ```javascript function clicky() { console.log('clicky'); } ``` -------------------------------- ### GCP Cloud Function Event Handler Instrumentation Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Use `registerGCPCloudFunctionEventHandler` to automatically instrument your GCP Cloud Functions. This ensures traces are propagated through PubSub if the publisher has `enableOpenTelemetryTracing` enabled. ```typescript import functions from '@google-cloud/functions-framework'; import { registerGCPCloudFunctionEventHandler } from '@hyperdx/node-opentelemetry'; functions.cloudEvent( 'helloCloudEvent', registerGCPCloudFunctionEventHandler(async (event) => { // Your code here... }), ); ``` -------------------------------- ### Teardown and Re-run Smoke Tests Source: https://github.com/hyperdxio/hyperdx-js/blob/main/AGENTS.md Performs a teardown of existing smoke test environments and then re-runs all BATS tests. ```bash make resmoke # teardown + re-run ``` -------------------------------- ### Disable Network Capture Dynamically Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Dynamically disables advanced network capture. ```APIDOC ## Disable Network Capture Dynamically ### Description Dynamically disables advanced network capture. ### Method `HyperDX.disableAdvancedNetworkCapture()` ### Parameters None ### Request Example ```js HyperDX.disableAdvancedNetworkCapture(); ``` ### Response None ``` -------------------------------- ### Stop Session Recorder Dynamically Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Dynamically stops the session recording. ```APIDOC ## Stop Session Recorder Dynamically ### Description Dynamically stops the session recording. ### Method `HyperDX.stopSessionRecorder()` ### Parameters None ### Request Example ```js HyperDX.stopSessionRecorder(); ``` ### Response None ``` -------------------------------- ### Disable Console Log Capture Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Set the HDX_NODE_CONSOLE_CAPTURE environment variable to 0 to disable the SDK's automatic capture of console logs. ```sh export HDX_NODE_CONSOLE_CAPTURE=0 ``` -------------------------------- ### Auto Capture React Error Boundary Errors Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Automatically capture errors occurring within React error boundaries by passing your ErrorBoundary component to `attachToReactErrorBoundary`. ```javascript // Import your ErrorBoundary (we're using react-error-boundary as an example) import { ErrorBoundary } from 'react-error-boundary'; // This will hook into the ErrorBoundary component and capture any errors that occur // within any instance of it. HyperDX.attachToReactErrorBoundary(ErrorBoundary); ``` -------------------------------- ### Injecting NestJS HyperDX Logger Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-logger/README.md Inject the HyperDXNestLogger into your NestJS controllers or services using the HDX_LOGGER_MODULE_PROVIDER injection token. This allows you to use the logger instance for sending logs. ```javascript import { Controller, Inject } from '@nestjs/common'; import { HyperDXNestLoggerModule, HyperDXNestLogger } from '@hyperdx/node-logger'; @Controller('cats') export class CatsController { constructor( @Inject(HyperDXNestLoggerModule.HDX_LOGGER_MODULE_PROVIDER) private readonly logger: HyperDXNestLogger, ) { } meow() { this.logger.info({ message: '🐱' }); } } ``` -------------------------------- ### Attach to React Error Boundary Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md Hooks into a React ErrorBoundary component to automatically capture any errors that occur within it. ```APIDOC ## Attach to React Error Boundary ### Description Hooks into a React ErrorBoundary component to automatically capture any errors that occur within it. ### Method `HyperDX.attachToReactErrorBoundary(ErrorBoundaryComponent)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ErrorBoundaryComponent** (React.Component) - Required - The ErrorBoundary component to attach to. ### Request Example ```js // Import your ErrorBoundary (we're using react-error-boundary as an example) import { ErrorBoundary } from 'react-error-boundary'; // This will hook into the ErrorBoundary component and capture any errors that occur // within any instance of it. HyperDX.attachToReactErrorBoundary(ErrorBoundary); ``` ### Response None ``` -------------------------------- ### Retrieve Session ID Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/browser/README.md This function allows you to retrieve the unique identifier for the current user session within the HyperDX system. ```APIDOC ## Retrieve Session ID ### Description To retrieve the current session ID, you can call the `getSessionId` function. ### Method Signature `HyperDX.getSessionId()` ### Return Value - `string`: The unique session ID. ### Code Example ```javascript const sessionId = HyperDX.getSessionId(); ``` ``` -------------------------------- ### Custom Termination Handler with Manual Shutdown Source: https://github.com/hyperdxio/hyperdx-js/blob/main/packages/node-opentelemetry/README.md Disable the default shutdown handler by setting `stopOnTerminationSignals` to false and manually call the `shutdown` function when your application captures termination signals like SIGTERM or SIGINT. ```typescript import { shutdown } from '@hyperdx/node-opentelemetry'; process.on('SIGTERM', async () => { // Your shutdown code here... await shutdown(); process.exit(); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.