Using OpenReplay with React

Getting the tracker to work on a React application is quite straightforward.

Assuming you’re building a SPA (Single Page Application), all you have to do, is to add the following code to your entry point:

import { tracker } from '@openreplay/tracker';

tracker.configure({
  projectKey: "<your project key>", 
  ingestPoint: "https://openreplay.mydomain.com/ingest" // only required if using the self-hosted version of OpenReplay
});

function YourMainComponent({props}) {
    //some code here...

    useEffect(() => {
        tracker.start();
    }, [])

    return //....
}

Alternatively, you can also use the Tracker class directly to handle its instance manually:

import Tracker from '@openreplay/tracker';

const tracker = new Tracker({
  projectKey: "<your project key>",  
  ingestPoint: "https://openreplay.mydomain.com/ingest" // only required if using the self-hosted version of OpenReplay
});

function YourMainComponent({props}) {
    //some code here...

    useEffect(() => {
        tracker.start();
    }, [])

    return //....
}

In other words, you can instantiate the tracker at the start of the script, and once the page loads, you can start it using a useEffect hook.

Handling the “projectKey” in your code

Section titled Handling the “projectKey” in your code

For security reasons, avoid hardcoding your projectKey directly in your application code. Instead, store it in a configuration file or environment system.

Several approaches are available depending on your project setup:

  • Environment Variables: If using Create React App, leverage its built-in support for environment variables
  • Configuration Files: Use dedicated config files that are excluded from version control
  • Environment Management: Tools like dotenv can help manage different keys across environments

Below is an example:

// Access the key from environment variables
const openReplayKey = process.env.REACT_APP_OPENREPLAY_KEY;

Building something more complex?

Section titled Building something more complex?

If you’re building a complex application with React, chances are you’re using Next, Remix or a similar framework. Make sure to check out our Tracker Setup section to find the framework you’re working with.

If you have any issues setting up the tracker on your React project, please reach out to us on our Slack community and ask our devs directly!