Elastic APM Real User Monitoring (RUM) JavaScript Agent
repository·main·Indexed 43 days ago
https://github.com/elastic/apm-agent-rum-jsA client-side monitoring tool for capturing real user experience data, including performance metrics, errors, and distributed traces from web browsers. It provides a comprehensive API for initializing the agent, managing custom transactions and spans, enriching data with user and custom contexts, and integrating with frameworks like Angular via the @elastic/apm-rum-angular package.
What's inside Elastic APM RUM
- The Elastic APM Real User Monitoring (RUM) JavaScript agent is the official agent for monitoring real user interactions in web applications. It allows developers to capture performance data, errors, and distributed traces directly from the browser and send them to an Elastic APM Server.
Overview of Elastic APM RUM JavaScript Agent features
mainThe Elastic APM Real User Monitoring (RUM) JavaScript Agent tracks performance metrics and errors in web applications. It uses browser timing APIs (Navigation Timing, Resource Timing, Paint Timing, User Timing, etc.) to capture:
- Page load metrics and URLs visited/referrer.
- Static Asset load times (JS, CSS, images, fonts).
- API requests via
XMLHttpRequestandFetch. - Single page application (SPA) navigations.
- User interactions (click events that trigger network activity).
- User-centric metrics (Long tasks, FCP, LCP, INP, FID, etc.).
- Network connection information.
- JavaScript errors.
- Distributed tracing for outgoing requests to enable end-to-end visibility across microservices.
- Breakdown metrics.
What is a Transaction in Elastic APM RUM?
mainA transaction is a logical grouping of multiple spans. It represents a high-level operation or a period of time in your application. To begin a transaction, you must first callapm.startTransaction(). Transactions can be auto-instrumented (like page loads or route changes) or custom-created by the developer.Access the Span API
mainThe
SpanAPI allows you to track specific units of work within a transaction. You acquire an instance of theSpanobject by calling theapm.startSpan()method on yourAgentinstance.const span = apm.startSpan({ name: 'span_name' });Use the Span API to measure event duration
mainA
Spanmeasures the duration of a single event. A span begins when it is created and continues untilspan.end()is called. To obtain aSpanobject, use theapm.startSpan()method.// Example pattern for using a span const span = apm.startSpan({ name: 'my-event', type: 'custom' }); // ... perform work ... span.end();Serverless compatibility limitation
mainThe Elastic APM RUM JavaScript Agent is not compatible with Elastic Serverless. It cannot send data to the APM endpoint for serverless projects.Understand Page Load Metrics
mainThe RUM agent captures the overall user experience of page loading as part of a
page-loadtransaction. This includes resource timing information as Spans and navigation marks to create a waterfall view.Key metrics captured include:
- Domain lookup: Duration of the DNS query (
domainLookupEnd-domainLookupStart). - Making a connection to the server: TCP connection and TLS negotiation time (
connectEnd-connectStart). - Requesting and receiving the document: Overall server response time (
responseEnd-requestStart). - Parsing the document, executing sync. scripts: HTML parsing time including synchronous stylesheets and scripts (
tagsdomInteractive-domLoading). - Fire "DOMContentLoaded" event: When the browser completes parsing (
domContentLoadedEventEnd-domContentLoadedEventStart). - Fire "load" event: When the browser finishes loading the document and dependent resources (
loadEventEnd-loadEventStart). - Time to first byte (TTFB): Captured as the transaction mark
transaction.marks.agent.timeToFirstByte.
Note: The
page-loadtransaction is measured relative to thefetchStarttimestamp from the Navigation Timing API. To accurately measure the duration of the load event, use theFire load eventSpan or the transaction marktransaction.marks.agent.domCompletein the Elasticsearch document.- Domain lookup: Duration of the DNS query (
Access the Agent API
mainTheAgentAPI provides all functions and properties for managing the RUM agent. You obtain an instance of theAgentobject (commonly referred to asapmin documentation) by initializing the agent. This can be done either by including a script element on your page or by requiring theelastic-apm-rummodule in a Node.js environment.How CORS preflight requests work with the RUM agent
mainWhen the RUM agent initiates its first
POSTrequest to a different origin, the browser performs a preflightOPTIONSrequest. This request must succeed for the actual data transmission to proceed. If RUM support is not enabled in the APM Server, this check will fail.Proxy Configuration
If you are using a proxy between the agent and the APM Server, ensure your proxy handles the following headers:
Request headers (from browser/proxy):
Access-Control-Request-Headers: Content-TypeAccess-Control-Request-Method: POSTOrigin: [request-origin]
Response headers (from proxy/server):
Access-Control-Allow-Headers: Content-TypeAccess-Control-Allow-Methods: POST, OPTIONSAccess-Control-Allow-Origin: [request-origin]
Using
sendCredentialsIf you have enabled the
sendCredentialsconfiguration option in the RUM agent, your proxy or server response must include the following header to allow authenticated requests:Access-Control-Allow-Credentials: trueAdditionally, the
Access-Control-Allow-Originheader must explicitly match the page's origin (it cannot be a wildcard*when credentials are sent).// Required response headers when sendCredentials is true Access-Control-Allow-Origin: [request-origin] Access-Control-Allow-Credentials: trueUnderstand User-Centric Metrics (Core Web Vitals)
mainThe agent captures responsiveness metrics to help understand how users perceive performance. Many of these are Core Web Vitals:
- First Contentful Paint (FCP): Time from page start to when any content is displayed. Captured as a transaction mark for
page-loadin Chromium-based browsers. - Largest Contentful Paint (LCP): Time until the largest text/image/video element is displayed. Captured as a transaction mark for
page-load(Chrome >77). - Interaction to Next Paint (INP): Quantifies responsiveness to all click, tap, and keyboard interactions.
- First Input Delay (FID): Time between a user's first interaction and the browser's response. Captured as a
First Input Delayspan forpage-load(Chrome >85). - Total Blocking Time (TBT): Sum of blocking time (>50ms) for long tasks between FCP and transaction completion. Captured as a
Total Blocking Timespan. - Cumulative Layout Shift (CLS): Score representing unexpected layout shifts during the page lifespan.
- Long Tasks: Any task monopolizing the UI thread for >50ms. Captured as
Longtask<name>spans for all managed transactions. - User Timing: Custom performance entries created via
performance.measureare recorded as spans by their measure name.
- First Contentful Paint (FCP): Time from page start to when any content is displayed. Captured as a transaction mark for
Understand breakdown metrics for SPA and custom transactions
mainFor transactions other than standard page loads—such as Single Page Application (SPA) route changes or user-created transactions—breakdown metrics are calculated based on the associated spans within that transaction.
- Span Type Distribution: The breakdown represents the percentage of time spent per span type. For example, if an SPA navigation spends 20% of its time downloading resources and 80% waiting for an API response, the breakdown will show
resourceat 20% andhttpat 80%. - Concurrent Spans: For transactions containing concurrent asynchronous spans, the breakdown includes the sum of time spent by each span type.
- Span Type Distribution: The breakdown represents the percentage of time spent per span type. For example, if an SPA navigation spends 20% of its time downloading resources and 80% waiting for an API response, the breakdown will show
Use OpenTracing with Elastic APM RUM
mainThe Elastic APM RUM agent provides an implementation of the OpenTracing API. The
ElasticApmTracertranslates OpenTracing API calls into Elastic APM data.In this mapping:
- The first span of a service is converted to an Elastic APM
Transaction. - Subsequent spans are mapped to Elastic APM
Spanobjects.
- The first span of a service is converted to an Elastic APM