Integrating OpenTelemetry SDK in a React Project
OpenTelemetry is a powerful observability framework that allows developers to collect and export telemetry data from their applications. In this article, we'll walk through the steps to integrate OpenTelemetry into a React project, enabling you to monitor performance and trace requests effectively.
Prerequisites
Before we start, ensure you have the following:
- A React application set up (you can use Create React App).
- Basic understanding of JavaScript and React.
- Node.js and npm installed on your machine.
Step 1: Install OpenTelemetry Packages
First, we need to install the necessary OpenTelemetry packages. Open your terminal and run:
npm install @opentelemetry/api @opentelemetry/sdk-trace-web @opentelemetry/instrumentation-fetch @opentelemetry/instrumentation-xml-http-request
Explanation
-
@opentelemetry/api
: The core API for OpenTelemetry. -
@opentelemetry/sdk-trace-web
: The SDK for web applications. -
@opentelemetry/instrumentation-fetch
: For tracing fetch requests. -
@opentelemetry/instrumentation-xml-http-request
: For tracing XMLHttpRequests.
Step 2: Set Up OpenTelemetry in Your Application
Next, we need to initialize OpenTelemetry in our React application. Create a new file named otel.js
in the src
directory.
// src/otel.js
import { NodeTracerProvider } from '@opentelemetry/node';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { BatchSpanProcessor } from '@opentelemetry/tracing';
import { SimpleSpanProcessor } from '@opentelemetry/tracing';
import { ConsoleSpanExporter } from '@opentelemetry/tracing';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
import { XMLHttpRequestInstrumentation } from '@opentelemetry/instrumentation-xml-http-request';
// Initialize the provider
const provider = new WebTracerProvider();
// Set up span processor and exporter
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
// Register instrumentations
registerInstrumentations({
instrumentations: [
new FetchInstrumentation(),
new XMLHttpRequestInstrumentation(),
],
});
// Register the provider
provider.register();
Explanation
- We create a
WebTracerProvider
to handle tracing for web applications. - We use
SimpleSpanProcessor
andConsoleSpanExporter
for demonstration, which logs spans to the console. - We register instrumentations to automatically trace fetch and XMLHttpRequest calls.
Step 3: Import OpenTelemetry in Your Application
Now, we need to import our OpenTelemetry setup in the main entry point of your application. Open src/index.js
and add the following line at the top:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import './otel'; // Import OpenTelemetry setup
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Explanation
By importing ./otel
, we initialize OpenTelemetry when the application starts, allowing it to begin tracing as soon as possible.
Step 4: Create a Sample Component to Test Tracing
Let’s create a simple component that makes a fetch request. Create a new file called FetchData.js
in the src
directory:
// src/FetchData.js
import React, { useEffect, useState } from 'react';
const FetchData = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const result = await response.json();
setData(result);
};
fetchData();
}, []);
return (
<div>
<h1>Fetched Data</h1>
{data && data.map(item => (
<div key={item.id}>
<h3>{item.title}</h3>
<p>{item.body}</p>
</div>
))}
</div>
);
};
export default FetchData;
Explanation
- This component fetches data from a placeholder API and displays it.
- The fetch request will be automatically traced by OpenTelemetry due to our previous setup.
Step 5: Use the Component in Your App
Finally, use the FetchData
component in your main App.js
file:
// src/App.js
import React from 'react';
import FetchData from './FetchData';
const App = () => {
return (
<div>
<h1>OpenTelemetry in React</h1>
<FetchData />
</div>
);
};
export default App;
Explanation
- The
FetchData
component is rendered within the main application, allowing us to see the fetched data and the associated traces.
Step 6: Run Your Application
Now, run your application with:
npm start
Open your browser and navigate to http://localhost:3000
. You should see the fetched data displayed, and you can check your console for any OpenTelemetry traces.
Conclusion
You have successfully integrated OpenTelemetry into your React application! This setup allows you to trace HTTP requests and monitor your application's performance. You can further enhance this integration by exporting traces to a backend observability platform like Jaeger or Zipkin for more advanced analysis.
Feel free to explore more OpenTelemetry features and customize your setup according to your needs!
Top comments (0)