### Start APM Server for Testing Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Starts the APM server and Fleet server using Docker Compose. Ensure you have Docker installed. Replace placeholders for nodeVersion and version. ```sh NODEJS_VERSION= STACK_VERSION= docker compose -f ./dev-utils/docker-compose.yml up -d fleet-server ``` -------------------------------- ### Install Dependencies and Enable Hooks Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Installs project dependencies. This also enables the git pre-commit hook for code formatting and linting. ```sh npm install ``` -------------------------------- ### Bootstrap Monorepo Dependencies Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Installs and links all packages in the monorepo using Lerna. Run this after cloning the repository. ```sh git clone git@github.com:elastic/apm-agent-rum-js.git && cd apm-agent-rum-js npx lerna bootstrap ``` -------------------------------- ### Install Elastic APM React Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Install the `@elastic/apm-rum-react` package as a dependency to your application using npm. ```bash npm install @elastic/apm-rum-react --save ``` -------------------------------- ### Start a New Transaction Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use to create a custom transaction. By default, custom transactions are not managed by the agent, but can be started as managed by passing `{ managed: true }`. ```javascript const transaction = apm.startTransaction(name, type, options) ``` -------------------------------- ### Example URL Grouping Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/custom-transaction-name.md Illustrates how URLs are grouped into more generic transaction names like '/blog/:id' and '/guide/en/*'. This helps in visualizing traces by avoiding excessive unique transactions. ```text // Blog Posts - '/blog/:id' https://www.elastic.co/blog/reflections-on-three-years-in-the-elastic-public-sector https://www.elastic.co/blog/say-heya-to-the-elastic-search-awards https://www.elastic.co/blog/and-the-winner-of-the-elasticon-2018-training-subscription-drawing-is // Documentation - '/guide/en/*' https://www.elastic.co/guide/en/elastic-stack/current/index.html https://www.elastic.co/guide/en/apm/get-started/current/index.html https://www.elastic.co/guide/en/infrastructure/guide/current/index.html ``` -------------------------------- ### Run RUM Agent Benchmarks Source: https://github.com/elastic/apm-agent-rum-js/blob/main/packages/rum/test/benchmarks/BENCHMARKS.md Execute the benchmark script to build the RUM agent, start the server, and collect performance metrics for both basic and heavy scenarios. ```bash node packages/rum/test/benchmarks/run.js ``` -------------------------------- ### Install APM RUM Agent via npm Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Install the APM RUM agent as a project dependency using npm. This is the first step for integrating the agent with JavaScript bundlers. ```bash npm install @elastic/apm-rum --save ``` -------------------------------- ### Access APM Agent Instance in Vue Components (Composition API) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Access the APM agent instance within Vue components using `inject('$apm')` with the Composition API and ` ``` -------------------------------- ### Install @elastic/apm-rum-vue package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Install the official Elastic APM Vue package as a dependency to your application using npm. ```bash npm install --save @elastic/apm-rum-vue ``` -------------------------------- ### apm.startTransaction() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Starts and returns a new transaction. Transactions can be managed by the agent or unmanaged, with managed transactions automatically ending when tasks are complete. ```APIDOC ## `apm.startTransaction()` [apm-start-transaction] ```js const transaction = apm.startTransaction(name, type, options) ``` Starts and returns a new transaction. Arguments: * `name` - The name of the transaction (string). Defaults to `Unknown` * `type` - The type of the transaction (string). Defaults to `custom` * `options` - Options to modify the created transaction (object). This argument is optional. The following options are supported: * `managed` - Controls whether the transaction is managed by the agent or not. Defaults to `false`. Use this method to create a custom transaction. By default, custom transactions are not managed by the agent, however, you can start a managed transaction by passing `{ managed: true }` as the `options` argument. There are some differences between managed and unmanaged transactions: * For managed transactions, the agent keeps track of the relevant tasks during the lifetime of the transaction and automatically ends it once all of the tasks are finished. Unmanaged transactions need to be ended manually by calling the [`end`](/reference/transaction-api.md#transaction-end) method. * Managed transactions include information captured via our auto-instrumentations (e.g. XHR spans). See [Supported Technologies](/reference/supported-technologies.md) for a list of instrumentations. * There can only be one managed transaction at any given time — starting a second managed transaction will end the previous one. There are no limits for unmanaged transactions. ::::{note} This method returns `undefined` if apm is disabled or if [active](/reference/configuration.md#active) flag is set to `false` in the config. :::: ``` -------------------------------- ### Install Elastic APM Angular Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/angular-integration.md Install the `@elastic/apm-rum-angular` package using npm. For older Angular versions, specific package versions are recommended. ```bash npm install @elastic/apm-rum-angular --save ``` -------------------------------- ### apm.startSpan() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Starts and returns a new span associated with the current active transaction. Spans can be blocking and can have a specified parent ID. ```APIDOC ## `apm.startSpan()` [apm-start-span] ```js const span = apm.startSpan(name, type, options) ``` Starts and returns a new span associated with the current active transaction. Arguments: * `name` - The name of the span (string). Defaults to `Unknown` * `type` - The type of the span (string). Defaults to `custom` * `options` - The following options are supported: * `blocking` - Blocks the associated transaction from ending until this span is ended. Blocked spans automatically create an internal task. Defaults to false. * `parentId` - Parent id associated with the new span. Defaults to current transaction id * `sync` - Denotes if the span is synchronous or asynchronous. Defaults to null Blocked spans allow users to control the early closing of [managed transactions](/reference/custom-transactions.md#custom-managed-transactions) in few cases when the app contains lots of async activity which cannot be tracked by the agent. ::::{note} This method returns `undefined` if apm is disabled or if [active](/reference/configuration.md#active) flag is set to `false` in the config. :::: ``` -------------------------------- ### Install APM RUM Vue Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/packages/rum-vue/README.md Install the necessary package for integrating Elastic APM RUM into your Vue application using npm. ```bash npm install @elastic/apm-rum-vue ``` -------------------------------- ### Instrument Vue Application with APM Plugin Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Configure and install the ApmVuePlugin, providing the Vue Router instance and essential agent configuration like `serviceName`. This enables automatic capturing of page load and SPA navigation events. ```javascript import { createApp, defineComponent, h } from 'vue' import { createRouter, createWebHashHistory } from 'vue-router' import { ApmVuePlugin } from '@elastic/apm-rum-vue' import App from './App.vue' const Home = defineComponent({ render: () => h("div", {}, "home") }) const router = createRouter({ history: createWebHashHistory(), routes: [ { path: '/', component: Home } ] }) createApp(App) .use(router) .use(ApmVuePlugin, { router, config: { serviceName: 'app-name', // agent configuration } }) // app specific code .mount('#app') ``` -------------------------------- ### Use APM Plugin with Vue Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Install the ApmVuePlugin in your Vue application using `app.use()`. This requires the Vue Router instance and agent configuration. ```javascript app.use(ApmVuePlugin, options) ``` -------------------------------- ### Start a Custom Span Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Starts and returns a new custom span associated with the current transaction. Spans measure time until `span.end()` is called. Defaults to `unnamed` span name and `custom` span type. ```javascript const span = transaction.startSpan('My custom span') ``` -------------------------------- ### transaction.startSpan Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Starts and returns a new custom span associated with the current transaction. Spans measure the time until span.end() is called. ```APIDOC ## `transaction.startSpan([name][, type][, options])` ### Description Start and return a new custom span associated with this transaction. ### Arguments * `name` - The name of the span (string). Defaults to `unnamed` * `type` - The type of span (string). Defaults to `custom` * `options` - The following options are supported: * `blocking` - Blocks the associated transaction from ending until this span is ended. Blocked spans automatically create an internal task. Defaults to false. * `parentId` - Parent id associated with the new span. Defaults to current transaction id * `sync` - Denotes if the span is synchronous or asynchronous. ### Request Example ```js const span = transaction.startSpan('My custom span') ``` ``` -------------------------------- ### Run Tests for a Specific Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Runs tests for a single package, specified by the SCOPE environment variable. For example, to run tests for the @elastic/apm-rum package. ```sh APM_SERVER_URL= SCOPE=@elastic/apm-rum npm run test ``` -------------------------------- ### Start Custom Transaction and Span Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/custom-transactions.md Initiates a custom transaction and an associated HTTP span for an external request. Captures an error if the fetch request fails and ensures both the span and transaction are ended. ```javascript const transaction = apm.startTransaction('Application start', 'custom') const url = 'http://example.com/data.json' const httpSpan = transaction.startSpan('GET ' + url, 'external.http') fetch(url) .then((resp) => { if (!resp.ok) { apm.captureError(new Error(`fetch failed with status ${resp.status} ${resp.statusText}`)) } httpSpan.end() transaction.end() }) ``` -------------------------------- ### apm.observe() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Listens for RUM agent internal events, such as transaction start and end, allowing for custom logic execution via callbacks. ```APIDOC ## `apm.observe()` [observe] ```js apm.observe(name, callback) ``` Arguments: * `name` - The name of the event. * `callback` - A callback function to execute once the event is fired. Use this method to listen for RUM agent internal events. The following events are supported for the transaction lifecycle: * `transaction:start` event is fired on every transaction start. * `transaction:end` event is fired on transaction end and before it is added to the queue to be sent to APM Server. The callback function for these events receives the corresponding transaction object as its only argument. The transaction object can be modified through methods and properties documented in [Transaction API](/reference/transaction-api.md): ```js apm.observe('transaction:start', function (transaction) { if (transaction.type === 'custom') { transaction.name = window.document.title transaction.addLabels({ 'custom-label': 'custom-value' }) } }) ``` ``` -------------------------------- ### Start a New Span Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Starts and returns a new span associated with the current active transaction. Blocked spans can control the early closing of managed transactions when the app contains lots of async activity. ```javascript const span = apm.startSpan(name, type, options) ``` -------------------------------- ### Observe Agent Events Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use this method to listen for RUM agent internal events, such as transaction start and end. The callback function receives the transaction object, which can be modified. ```javascript apm.observe(name, callback) ``` ```javascript apm.observe('transaction:start', function (transaction) { if (transaction.type === 'custom') { transaction.name = window.document.title transaction.addLabels({ 'custom-label': 'custom-value' }) } }) ``` -------------------------------- ### Access APM Agent Instance in Vue Components (Options API) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/vue-integration.md Access the APM agent instance within Vue components using `this.$apm`. Start spans to measure component lifecycle timings. ```html ``` -------------------------------- ### Mark Transaction Point with transaction.mark(key) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Marks the current point in time relative to the start of the transaction. Use this method to mark significant events that happen while the transaction is active. Special characters in the key will be replaced by underscores. ```javascript transaction.mark(key) ``` -------------------------------- ### apm.init([config]) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Initializes the agent with the given configuration and returns itself. It registers global listeners for errors and page load metrics. ```APIDOC ## apm.init([config]) Initializes the agent with the given configuration and returns itself. Under the hood, init does the following: * Registers a global `error` listener to track JavaScript errors on the page. * Adds a `onload` event listener to collect the page load metrics. When the agent is inactive, both `error` and `onload` listeners will not be registered on the page. Both XHR and Fetch API are patched as soon as the agent script is executed on the page and does not get changed even if the agent is inactive. The reason is to allow users to initialize the agent asynchronously on the page. ``` -------------------------------- ### Get Current Transaction Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use this method to get the current active transaction. If there is no active transaction it will return `undefined`. ```javascript apm.getCurrentTransaction() ``` -------------------------------- ### Sample 10% of Page Loads Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/configuration.md Use this option to sample a percentage of page loads. Ensure the agent is active for instrumentation to run. ```javascript var options = { active: Math.random() < 0.1 } ``` -------------------------------- ### Initialize APM RUM Agent with Script Tags (Synchronous) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Use this pattern to load the APM RUM agent bundle and initialize it using the global `elasticApm` object. This method is synchronous and may block page rendering. ```html ``` -------------------------------- ### Initialize APM Agent with Sampling Source: https://github.com/elastic/apm-agent-rum-js/wiki/Home Activate the APM agent based on a sampling algorithm. Call this method before the 'load' event fires. ```javascript var active = Math.random() < 0.1 import { init as initApm } from 'elastic-apm-js-base' var apm = initApm({ active: active, serviceName: '', serverUrl: '' }) ``` -------------------------------- ### Manually Release All Packages Source: https://github.com/elastic/apm-agent-rum-js/blob/main/RELEASE.md Run this command to publish all packages to NPM. It automatically determines version bumps, creates Git tags, generates changelogs, and publishes to NPM. Use '-- (minor|patch|major)' to override the semantic version bump. ```bash GITHUB_TOKEN= APM_SERVER_URL= npm run release ``` -------------------------------- ### Initialize APM RUM Agent with Script Tags (Asynchronous) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md This asynchronous pattern loads the agent script without blocking page rendering. It initializes the agent upon script load, but distributed tracing may not work for requests made before initialization. ```html ``` -------------------------------- ### Initialize Elastic APM Tracer for OpenTracing Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/opentracing.md Initialize the Elastic APM RUM agent and create an OpenTracing compatible tracer. This is the first step to using OpenTracing APIs with Elastic APM. ```javascript const { init: initApm, createTracer } = require('@elastic/apm-rum/dist/bundles/elastic-apm-opentracing.umd.js') const elasticApm = initApm({ // ... }) const elasticTracer = createTracer(elasticApm) ``` -------------------------------- ### Server Configuration for OPTIONS Request Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/distributed-tracing.md When using distributed tracing, the server must respond to `OPTIONS` requests with the appropriate CORS headers to allow `traceparent` and `tracestate` headers. ```text Access-Control-Request-Headers: traceparent, tracestate Access-Control-Request-Method: [request-method] Origin: [request-origin] ``` -------------------------------- ### Run All Tests Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Executes all tests across all packages. Ensure the APM server is running and set the APM_SERVER_URL environment variable. ```sh APM_SERVER_URL= npm run test ``` -------------------------------- ### Manually Release Single Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/RELEASE.md Use this command to publish a single package to NPM. It utilizes 'lerna publish' under the hood. ```bash npm run release-package -- @elastic/apm-rum ``` -------------------------------- ### Manually Release Artifacts to GitHub Source: https://github.com/elastic/apm-agent-rum-js/blob/main/RELEASE.md Execute this command in the root directory to package and create a GitHub release for '@elastic/apm-rum' using the previous annotated tag. Ensure GITHUB_TOKEN with push access is set. ```bash npm run github-release ``` -------------------------------- ### transaction.block Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Blocks the currently running auto-instrumented or custom transactions from getting automatically closed once the associated spans are ended. This is useful when auto-instrumented code misses important activity. ```APIDOC ## `transaction.block(flag)` ### Description Blocks the currently running auto-instrumented or custom transactions from getting automatically closed once the associated spans are ended. ### Arguments * `flag` - Boolean. Defaults to false. ### Request Example ```js // get the current active autoinstrumented transaction (page-load, route-change, etc.) const activeTransaction = apm.getCurrentTransaction() if (activeTransaction) { activeTransaction.block(true) } // Perform some more async tasks and unblock it activeTransaction.block(false) ``` ``` -------------------------------- ### Initialize RUM Agent with Trace Context Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/distributed-tracing.md Use this when your backend service generates HTML dynamically. Inject the trace ID, parent span ID, and sampled status to ensure the page load is the root of the trace. Refer to your backend agent's API for methods to extract this information. ```javascript var apm = initApm({ ... pageLoadTraceId: , pageLoadSpanId: , pageLoadSampled: }) ``` -------------------------------- ### Get and Block Active Transaction Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/transaction-api.md Retrieves the current active transaction and blocks it from automatic closure. This is useful when dealing with uninstrumented asynchronous tasks. Remember to unblock the transaction when these tasks are complete. ```javascript // get the current active autoinstrumented transaction (page-load, route-change, etc.) const activeTransaction = apm.getCurrentTransaction() if (activeTransaction) { activeTransaction.block(true) } // Perform some more async tasks and unblock it activeTransaction.block(false) ``` -------------------------------- ### Initialize APM Agent Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Initialize the APM RUM agent with configuration options. This registers global error and load listeners. ```javascript var apm = require('@elastic/apm-rum').init(...) ``` -------------------------------- ### Run Unit Tests in Watch Mode Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Runs unit tests for a package in watch mode, automatically re-running tests when files change. Use --grep to target specific test files. ```sh npx lerna run --scope @elastic/apm-rum karma:dev -- --grep ``` -------------------------------- ### Run Linters Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Executes the linting process using ESLint and Prettier to check code style and identify potential issues. ```sh npm run lint ``` -------------------------------- ### Run Integration Tests for a Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Executes the integration tests for a specified package using Lerna. Replace @elastic/apm-rum with the target package. ```sh npx lerna run --scope @elastic/apm-rum test:integration ``` -------------------------------- ### Set Transaction Sample Rate Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/performance-tuning.md Configure the transactionSampleRate to control the ratio of requests traced. A value of 0.2 means 20% of requests will be traced. ```javascript import { apm } from "@elastic/apm-rum" apm.init({ transactionSampleRate: 0.2 }) ``` -------------------------------- ### Run Unit Tests for a Package Source: https://github.com/elastic/apm-agent-rum-js/blob/main/CONTRIBUTING.md Executes only the unit tests for a specified package using Lerna. Replace @elastic/apm-rum with the target package. ```sh npx lerna run --scope @elastic/apm-rum test:unit ``` -------------------------------- ### Register Global OpenTracing Tracer Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/opentracing.md Register the created Elastic APM tracer as the global OpenTracing tracer. This allows any OpenTracing instrumentation to automatically use the Elastic APM tracer. ```javascript const opentracing = require('opentracing-javascript') opentracing.initGlobalTracer(elasticTracer); // ... const tracer = opentracing.globalTracer(); ``` -------------------------------- ### Configure APM RUM Agent with Bundlers Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Import and initialize the APM RUM agent within your application code when using bundlers. Configure essential parameters like `serviceName`, `serverUrl`, and `serviceVersion`. ```js import { init as initApm } from '@elastic/apm-rum' const apm = initApm({ // Set required service name (allowed characters: a-z, A-Z, 0-9, -, _, and space) serviceName: '', // Set custom APM Server URL (default: http://localhost:8200) serverUrl: 'http://localhost:8200', // Set service version (required for sourcemap feature) serviceVersion: '' }) ``` -------------------------------- ### Server Response Headers for CORS Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/distributed-tracing.md The server should respond to `OPTIONS` requests with these headers to permit cross-origin requests including distributed tracing headers. ```text Access-Control-Allow-Headers: traceparent, tracestate Access-Control-Allow-Methods: [allowed-methods] Access-Control-Allow-Origin: [request-origin] ``` -------------------------------- ### Import ApmRoutes for React Router v6+ Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Import the `ApmRoutes` component from the `@elastic/apm-rum-react` package to instrument application routes. ```javascript import { ApmRoutes } from '@elastic/apm-rum-react' ``` -------------------------------- ### Import withTransaction for Component Instrumentation Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Import the `withTransaction` higher-order component from the `@elastic/apm-rum-react` package to instrument individual React components. ```javascript import { withTransaction } from '@elastic/apm-rum-react' ``` -------------------------------- ### Rollup Production Build Configuration Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Configure Rollup for an optimized production build by using the `replace` plugin. This ensures the correct build environment is set, optimizing the agent for production. ```js const replace = require('rollup-plugin-replace') plugins: [ replace({ 'process.env.NODE_ENV': JSON.stringify('production') }) ] ``` -------------------------------- ### Configure Distributed Tracing Origins Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/configuration.md Specify origins to monitor for distributed tracing. Supports exact string matches or RegExp objects. ```javascript var options = { distributedTracingOrigins: ['https://example.com', /https?:::\/:::\/example\.com:\d{4}/] } ``` -------------------------------- ### Initialize APM Agent with Custom Request Handler Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/configuration.md Initialize the APM agent with a custom `apmRequest` function to intercept and modify outgoing requests to the APM server. The function should return `true` to proceed with the request or `false` to discard it. ```javascript apm.init({ apmRequest: (requestParams) => true}) ``` ```javascript apm.init({ apmRequest({ xhr }) { xhr.setRequestHeader('custom', 'header') return true } }) ``` ```javascript apm.init({ apmRequest({ url, method, headers, payload }) { // Handle the APM request here or at some later point. fetch(url, { method, headers, body: payload }); return false } }) ``` -------------------------------- ### Instrument Angular Application with ApmModule and ApmService Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/angular-integration.md Configure your Angular application module to use `ApmModule` and `ApmService` for APM integration. Initialize the agent with service details and optionally set user context. ```typescript import { NgModule } from '@angular/core' import { BrowserModule } from '@angular/platform-browser' import { Routes, RouterModule } from '@angular/router' import { ApmModule, ApmService } from '@elastic/apm-rum-angular' const routes: Routes = [ { path: 'contact', component: ContactListComponent }, { path: 'contact/:id', component: ContactDetailComponent } ] @NgModule({ imports: [ApmModule, BrowserModule, RouterModule.forRoot(routes)], declarations: [AppComponent, ContactListComponent, ContactDetailComponent], providers: [ApmService], bootstrap: [AppComponent] }) export class AppModule { constructor(service: ApmService) { // Agent API is exposed through this apm instance const apm = service.init({ serviceName: 'angular-app', serverUrl: 'http://localhost:8200' }) apm.setUserContext({ 'username': 'foo', 'id': 'bar' }) } } ``` -------------------------------- ### Ignore Transactions with Strings and Regex Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/configuration.md Configure which transaction names to ignore by providing an array of strings for exact matches or RegExp objects for pattern matching. ```javascript const options = { ignoreTransactions: [/login*/, '/app'] } ``` -------------------------------- ### Webpack Production Build Configuration Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/install-agent.md Configure Webpack for an optimized production build by including the `EnvironmentPlugin`. This helps in removing debug messages and reducing bundle size. ```js const { EnvironmentPlugin } = require('webpack') plugins: [ new EnvironmentPlugin({ NODE_ENV: 'production' }) ] ``` -------------------------------- ### Set User Context Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Enrich performance data and errors with user information like ID, username, and email. Properties are shallow merged on multiple calls within the same transaction. ```javascript apm.setUserContext(context) ``` -------------------------------- ### CORS Preflight Request Headers Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/configuring-cors.md When using a proxy, these headers may be necessary for the preflight OPTIONS request. ```javascript Access-Control-Request-Headers: Content-Type Access-Control-Request-Method: POST Origin: [request-origin] ``` -------------------------------- ### apm.setCustomContext(context) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Enriches collected errors and transactions with custom information to aid in debugging performance issues or errors. The context can be any JSON-encodable object. ```APIDOC ## apm.setCustomContext(context) Call this to enrich collected errors and transactions with any information that you think will help you debug performance issues or errors. The provided custom context is stored under `context.custom` in Elasticsearch on both errors and transactions. It’s possible to call this function multiple times within the scope of the same active transaction. For each call, the properties of the context argument are shallow merged with the context previously given. The given `context` argument must be an object and can contain any property that can be JSON encoded. ``` -------------------------------- ### Configure Custom Page Load Transaction Name Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/custom-transaction-name.md Initialize the APM RUM agent with a custom `pageLoadTransactionName` to group transactions under a specific category, such as '/homepage'. This avoids using full URLs and provides more meaningful transaction names. ```javascript import {apm} from '@elastic/apm-rum' apm.init({ serviceName: "service-name", pageLoadTransactionName: '/homepage' }) ``` -------------------------------- ### Set Initial Page Load Transaction Name Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Use this method to set the name of the `page-load` transaction that is sent automatically on page load event. ```javascript apm.setInitialPageLoadName(name) ``` -------------------------------- ### Instrument Lazy Loaded Routes with `withTransaction` Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md When using React.lazy for components, auto-instrumentation via ApmRoute is not possible. Use the `withTransaction` API to manually instrument code for lazy-rendered routes and capture associated spans. ```javascript import React, { Component, Suspense, lazy } from 'react' import { Route, Switch } from 'react-router-dom' import { withTransaction } from '@elastic/apm-rum-react' const Loading = () =>
Loading
const LazyRouteComponent = lazy(() => import('./lazy-component')) function Routes() { return ( ) } // lazy-component.jsx class LazyComponent extends Component {} export default withTransaction('LazyComponent', 'component')(LazyComponent) ``` -------------------------------- ### Enable Cross-Origin Requests in RUM Agent Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/distributed-tracing.md Configure the `distributedTracingOrigins` option to include cross-origin requests in traces. This adds the `traceparent` header to requests made to the specified origins. ```javascript var apm = initApm({ ... distributedTracingOrigins: ['https://api.example.com'] }) ``` -------------------------------- ### apm.setInitialPageLoadName() Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Sets the name of the page-load transaction that is automatically sent on page load events. ```APIDOC ## `apm.setInitialPageLoadName()` [set-initial-page-load-name] ```js apm.setInitialPageLoadName(name) ``` Arguments: * `name` - The name of the page-load transaction (string). Use this method to set the name of the `page-load` transaction that is sent automatically on page load event. See the [custom initial page load transaction names](/reference/custom-transaction-name.md) documentation for more details. ``` -------------------------------- ### Capture Errors in Unsupported Browsers Source: https://github.com/elastic/apm-agent-rum-js/blob/main/packages/rum/test/e2e/standalone-html/opentracing.html This snippet is used for testing error capturing in unsupported browsers. It overrides the global `onerror` handler to capture any errors that occur. ```javascript test /***** * Used for testing errors on unsupported browsers *****/ window.capturedTestErrors = [] window.onerror = function(err) { window.capturedTestErrors.push(err) } ``` -------------------------------- ### Import ApmRoute for React Router v4/v5 Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Import the `ApmRoute` component from the `@elastic/apm-rum-react` package for older versions of `react-router`. ```javascript import { ApmRoute } from '@elastic/apm-rum-react' ``` -------------------------------- ### Instrument React Routes with ApmRoute (v<2.0.0) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/react-integration.md Replace `Route` components with `ApmRoute` to monitor specific routes. This approach is for `react-router` versions 4 and 5. Ensure the `component` property is provided for instrumentation. ```javascript class App extends React.Component { render() { return (
( )} />
) } } ``` -------------------------------- ### apm.addLabels({ [name]: value }) Source: https://github.com/elastic/apm-agent-rum-js/blob/main/docs/reference/agent-api.md Sets labels on transactions and errors, which are indexed by Elasticsearch and therefore searchable. Labels can be any string, boolean, or number. ```APIDOC ## apm.addLabels({ [name]: value }) Set labels on transactions and errors. Starting with APM Server 7.6+, the labels are added to spans as well. Labels are key/value pairs that are indexed by Elasticsearch and therefore searchable (as opposed to data set via `apm.setCustomContext()`). You can set multiple labels. Arguments: * `name` - Any string. All periods (.), asterisks (*), and double quotation marks (") will be replaced by underscores (_), as those characters have special meaning in Elasticsearch * `value` - Any string, boolean, or number. All other data types will be converted to a string before being sent to the APM Server. ``` -------------------------------- ### Capture Errors on Unsupported Browsers Source: https://github.com/elastic/apm-agent-rum-js/blob/main/packages/rum/test/e2e/standalone-html/index.html This snippet is used for testing error capturing on unsupported browsers. It overrides the global `onerror` handler to push any captured errors into a global array for later assertion. ```javascript /** * Used for testing errors on unsupported browsers */ window.capturedTestErrors = [] window.onerror = function(err) { window.capturedTestErrors.push(err) } ```