Integrating Elastic APM with React Applications On-Premises: A Comprehensive Guide

Enhance performance monitoring and gain real user insights in your React applications using Elastic APM's Real User Monitoring (RUM) JavaScript Agent. Introduction Elastic APM (Application Performance Monitoring) provides developers with powerful tools to monitor application performance in real-time. By integrating Elastic APM with your React application, you can track user interactions, measure page load times, and identify performance bottlenecks. This guide provides step-by-step instructions on how to set up Elastic APM RUM JavaScript Agent in a React application for an on-premises Elastic Stack deployment. Prerequisites Elastic Stack on-premises deployment: Ensure you have Elasticsearch, Kibana, and APM Server installed and running. React application: An existing React project where you want to integrate Elastic APM. Node.js and npm/yarn: Installed on your development machine. Access to apm-server.yml: To configure the APM Server. Step 1: Install the Elastic APM RUM JavaScript Agent Navigate to your React project's directory and install the RUM agent: npm install @elastic/apm-rum --save Or with yarn: yarn add @elastic/apm-rum Step 2: Configure CORS in APM Server Since the RUM agent sends data from the browser, you need to enable and configure CORS (Cross-Origin Resource Sharing) in the APM Server to accept requests from your application's domain. Edit the APM Server Configuration Locate and open the apm-server.yml file in your APM Server installation. Enable RUM and Set Allowed Origins Add or update the following settings: apm-server: rum: enabled: true allow_origins: ['http://localhost:3000', 'https://your-production-domain.com'] enabled: true: Activates the RUM endpoint in the APM Server. allow_origins: A list of origins (protocol, domain, and port) that are allowed to send data to the APM Server. Replace with your application's development and production URLs. Restart the APM Server After saving the changes, restart the APM Server to apply the new configuration. sudo service apm-server restart Or depending on your setup: ./apm-server -e Step 3: Initialize the RUM Agent in Your React Application Create a file in your React application to initialize the APM agent. Create an Initialization File In the src directory of your React app, create a new file named apm.js: // src/apm.js import { init as initApm } from '@elastic/apm-rum'; const apm = initApm({ serviceName: 'my-react-app', serverUrl: 'http://your-apm-server-domain:8200', serviceVersion: '', // e.g., git revision or version number environment: process.env.NODE_ENV, }); export default apm; serviceName: A unique identifier for your application. serverUrl: The URL where your APM Server is accessible. Replace with your actual APM Server URL. serviceVersion: (Optional) Specify the version of your app. environment: Set the environment (e.g., 'development', 'production'). Modify Environment Variables If you prefer to keep the server URL and other configurations outside of your code: Create a .env file in the root of your project (if not already present). Add the following variables: REACT_APP_APM_SERVER_URL=http://your-apm-server-domain:8200 REACT_APP_SERVICE_NAME=my-react-app REACT_APP_SERVICE_VERSION=1.0.0 Update apm.js to use environment variables: import { init as initApm } from '@elastic/apm-rum'; const apm = initApm({ serviceName: process.env.REACT_APP_SERVICE_NAME, serverUrl: process.env.REACT_APP_APM_SERVER_URL, serviceVersion: process.env.REACT_APP_SERVICE_VERSION, environment: process.env.NODE_ENV, }); export default apm; Step 4: Include the RUM Agent in Your Application Import the apm.js file at the entry point of your application to initialize the agent before any other code runs. Modify index.js At the top of your src/index.js file, add: import './apm'; // Initializes Elastic APM import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(, document.getElementById('root')); Step 5: Verify the Integration Run Your Application Start your React application: npm start Or with yarn: yarn start Generate Some Activity Interact with your application to generate some user activity and performance data. Check Kibana APM Dashboard Open Kibana in your browser (e.g., http://your-kibana-domain:5601). Navigate to APM in the main menu. You should see your service my-react-app listed. Click on your service to view metrics such as transactions, errors, and load times. Advanced Topics 1. Custom Transactions To measure specific operations or user interactions, start and end custom transactions: import apm from './apm'; // Start a custom tra

Mar 12, 2025 - 15:51
 0
Integrating Elastic APM with React Applications On-Premises: A Comprehensive Guide

Enhance performance monitoring and gain real user insights in your React applications using Elastic APM's Real User Monitoring (RUM) JavaScript Agent.

Introduction

Elastic APM (Application Performance Monitoring) provides developers with powerful tools to monitor application performance in real-time. By integrating Elastic APM with your React application, you can track user interactions, measure page load times, and identify performance bottlenecks. This guide provides step-by-step instructions on how to set up Elastic APM RUM JavaScript Agent in a React application for an on-premises Elastic Stack deployment.

Prerequisites

  • Elastic Stack on-premises deployment: Ensure you have Elasticsearch, Kibana, and APM Server installed and running.
  • React application: An existing React project where you want to integrate Elastic APM.
  • Node.js and npm/yarn: Installed on your development machine.
  • Access to apm-server.yml: To configure the APM Server.

Step 1: Install the Elastic APM RUM JavaScript Agent

Navigate to your React project's directory and install the RUM agent:

npm install @elastic/apm-rum --save

Or with yarn:

yarn add @elastic/apm-rum

Step 2: Configure CORS in APM Server

Since the RUM agent sends data from the browser, you need to enable and configure CORS (Cross-Origin Resource Sharing) in the APM Server to accept requests from your application's domain.

  1. Edit the APM Server Configuration

Locate and open the apm-server.yml file in your APM Server installation.

  1. Enable RUM and Set Allowed Origins

Add or update the following settings:

   apm-server:
     rum:
       enabled: true
       allow_origins: ['http://localhost:3000', 'https://your-production-domain.com']
  • enabled: true: Activates the RUM endpoint in the APM Server.
  • allow_origins: A list of origins (protocol, domain, and port) that are allowed to send data to the APM Server. Replace with your application's development and production URLs.
  1. Restart the APM Server

After saving the changes, restart the APM Server to apply the new configuration.

   sudo service apm-server restart

Or depending on your setup:

   ./apm-server -e

Step 3: Initialize the RUM Agent in Your React Application

Create a file in your React application to initialize the APM agent.

  1. Create an Initialization File

In the src directory of your React app, create a new file named apm.js:

   // src/apm.js
   import { init as initApm } from '@elastic/apm-rum';

   const apm = initApm({
     serviceName: 'my-react-app',
     serverUrl: 'http://your-apm-server-domain:8200',
     serviceVersion: '', // e.g., git revision or version number
     environment: process.env.NODE_ENV,
   });

   export default apm;
  • serviceName: A unique identifier for your application.
  • serverUrl: The URL where your APM Server is accessible. Replace with your actual APM Server URL.
  • serviceVersion: (Optional) Specify the version of your app.
  • environment: Set the environment (e.g., 'development', 'production').
  1. Modify Environment Variables

If you prefer to keep the server URL and other configurations outside of your code:

  • Create a .env file in the root of your project (if not already present).
  • Add the following variables:

     REACT_APP_APM_SERVER_URL=http://your-apm-server-domain:8200
     REACT_APP_SERVICE_NAME=my-react-app
     REACT_APP_SERVICE_VERSION=1.0.0
    
  • Update apm.js to use environment variables:

     import { init as initApm } from '@elastic/apm-rum';
    
     const apm = initApm({
       serviceName: process.env.REACT_APP_SERVICE_NAME,
       serverUrl: process.env.REACT_APP_APM_SERVER_URL,
       serviceVersion: process.env.REACT_APP_SERVICE_VERSION,
       environment: process.env.NODE_ENV,
     });
    
     export default apm;
    

Step 4: Include the RUM Agent in Your Application

Import the apm.js file at the entry point of your application to initialize the agent before any other code runs.

  1. Modify index.js

At the top of your src/index.js file, add:

   import './apm'; // Initializes Elastic APM

   import React from 'react';
   import ReactDOM from 'react-dom';
   import App from './App';

   ReactDOM.render(<App />, document.getElementById('root'));

Step 5: Verify the Integration

  1. Run Your Application

Start your React application:

   npm start

Or with yarn:

   yarn start
  1. Generate Some Activity

Interact with your application to generate some user activity and performance data.

  1. Check Kibana APM Dashboard
  • Open Kibana in your browser (e.g., http://your-kibana-domain:5601).
  • Navigate to APM in the main menu.
  • You should see your service my-react-app listed.
  • Click on your service to view metrics such as transactions, errors, and load times.

Advanced Topics

1. Custom Transactions

To measure specific operations or user interactions, start and end custom transactions:

import apm from './apm';

// Start a custom transaction
const customTransaction = apm.startTransaction('Custom Operation', 'custom');

// Perform the operation
performOperation();

// End the transaction
customTransaction.end();

2. Capturing Errors

While the agent automatically captures unhandled errors, you can manually capture exceptions:

import apm from './apm';

try {
  // Code that may throw an error
} catch (error) {
  apm.captureError(error);
}

3. Distributed Tracing

If your React application communicates with backend services also instrumented with Elastic APM:

  • Ensure that the RUM agent propagates the traceparent header in outgoing requests.
  • This enables end-to-end tracing across frontend and backend services.

4. Adding Context Information

Add custom context such as user information or custom labels:

apm.setUserContext({
  id: 'user-id',
  username: 'username',
  email: 'user@example.com',
});

apm.addLabels({
  feature: 'shopping-cart',
});

Troubleshooting

  • No Data in APM Dashboard:

    • Verify that the serverUrl in your apm.js file is correct and accessible.
    • Check the browser console for any CORS errors or network issues.
    • Ensure that the APM Server's allow_origins setting includes the origin of your React application.
  • CORS Errors:

    • Confirm that the allow_origins array in apm-server.yml includes the correct protocol, domain, and port.
    • Remember to restart the APM Server after making changes.
  • Environment Variables Not Working:

    • Ensure that variables in .env are prefixed with REACT_APP_ for Create React App to expose them to the frontend.
    • Restart the development server after adding or changing environment variables.

Additional Considerations

Security

  • The RUM agent's configuration is exposed in the frontend code. Avoid including sensitive information such as passwords or private keys.
  • The secretToken is not required for the RUM agent when connecting to the APM Server unless you have configured the APM Server to require it. In such cases, be aware that this token will be visible in the client-side code.

Performance Impact

  • The RUM agent is designed to have minimal impact on your application's performance.
  • Use sampling and rate limiting if necessary, especially for high-traffic applications.

Conclusion

Integrating Elastic APM with your on-premises React application setup enables you to monitor real user experiences effectively. By following this guide, you now have:

  • Set up the Elastic APM RUM JavaScript Agent in your React application.
  • Configured the APM Server to accept RUM data from your application's domain.
  • Initialized the agent to start collecting performance metrics and errors.
  • Verified the integration through the Kibana APM dashboard.

With these insights, you can proactively identify and resolve performance issues, enhancing the user experience of your application.

Further Reading and Resources

  • APM Real User Monitoring JavaScript Agent Reference [5.x] | Elastic

    • Explore detailed documentation on RUM agent configuration, API reference, and advanced topics.
  • Framework-Specific Integrations

    • Learn more about the React integration and best practices.
  • Advanced Topics

    • Delve into topics like interpreting long task spans, custom page load transaction names, and performance tuning.

Note: This guide is based on the Elastic APM RUM JavaScript Agent version 5.x. Ensure that you refer to the appropriate version of the documentation for your implementation.