React

Crash Reporting and Real User Monitoring for React applications with Raygun is available using the Raygun4JS provider.

Raygun4JS is a library you can easily add to your website and web applications which allows you to then monitor JavaScript errors and frontend performance issues affecting your users.

Once Raygun is installed, it will automatically start monitoring your application for errors with Crash Reporting and complete user sessions with Real User Monitoring.


There are two ways of installing Raygun into your project - choose the one that best suits your use case.

Install the Raygun4JS provider using NPM or Yarn.

# Yarn
yarn add raygun4js

# NPM
npm install raygun4js

Add the following snippet into the <head> of your document above every other script file.

<script type="text/javascript">
  !function(a,b,c,d,e,f,g,h){a.RaygunObject=e,a[e]=a[e]||function(){
  (a[e].o=a[e].o||[]).push(arguments)},f=b.createElement(c),g=b.getElementsByTagName(c)[0],
  f.async=1,f.src=d,g.parentNode.insertBefore(f,g),h=a.onerror,a.onerror=function(b,c,d,f,g){
  h&&h(b,c,d,f,g),g||(g=new Error(b)),a[e].q=a[e].q||[],a[e].q.push({
  e:g})}}(window,document,"script","//cdn.raygun.io/raygun4js/raygun.min.js","rg4js");
</script>
What is this snippet?

The snippet fetches the Raygun4JS script from our CDN asynchronously so it doesn't block the page load. It also catches errors that are thrown while the page is loading and only sends them when the provider has loaded.

Download the production script (minified), the development script (full source) or see here for other installation options.


Import the Raygun4JS provider into your application and configure it with your API key.
Here you can also enable the features you wish to use.

// App.js
import rg4js from 'raygun4js';

rg4js('apiKey', 'API_KEY');
rg4js('enableCrashReporting', true);
rg4js('enablePulse', true);

Configure the Raygun4JS provider with your API key by calling it underneath the snippet added in step 1.
Here you can also enable the features you wish to use.

<script type="text/javascript">
  rg4js('apiKey', 'API_KEY');
  rg4js('enableCrashReporting', true);
  rg4js('enablePulse', true);
</script>

Route changes for traditional websites are handled automatically by the CDN provider.

To track pageView events for Single Page Applications, you can use the trackEvent option.
Call trackEvent, passing it the pageView event type and the current pathname as the path.

rg4js('trackEvent', { 
  type: 'pageView', 
  path: location.pathname 
});

tip: More information about the trackEvent option can be found here.

Below is an example of how you can use React Router alongside the BrowserRouter to automatically track route changes.

// App.js
import { useEffect } from "react";
import {
  Routes,
  Route,
  Link,
  useLocation 
} from "react-router-dom";
import rg4js from 'raygun4js';

function App() {

  let location = useLocation();

  useEffect(function() {
    rg4js('trackEvent', { type: 'pageView', path: location.pathname });
  }, [location]);

  return (
    <>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
        </ul>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </>
  );
}

function Home() { return <p>Home</p> }
function About() { return <p>About</p> }

export default App;
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter as Router } from "react-router-dom";
import rg4js from 'raygun4js';
import App from './App';

rg4js('apiKey', process.env.REACT_APP_RAYGUN_API_KEY);
rg4js('enableCrashReporting', true);
rg4js('enablePulse', true);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>
);

You can setup user tracking to have a better idea of who is using your web application. To do so call the setUser method after your authentication step succeeds.

rg4js('setUser', {
  identifier: string,
  isAnonymous?: boolean,
  email?: string,
  firstName?: string,
  fullName?: string
});

note: The string properties on a User have a maximum length of 255 characters. Users who have fields that exceed this amount will not be processed.


While Real User Monitoring automatically tracks an extensive set of performance timings related to page and asset loading, you can also attach your own custom timing events.

Here we will use custom timings to track the CWV metrics of our SPA application.

// reportWebVitals.js
const reportWebVitals = onPerfEntry => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;
// App.js
import reportWebVitals from './reportWebVitals';

function sendMetricToRaygun(metric) {
  rg4js('trackEvent', {
      type: 'customTiming',
      name: metric.name,    
      duration: metric.value,
  });
}

reportWebVitals(sendMetricToRaygun);

Congratulations, you have successfully implemented Raygun into your application!

tip: We recommend raising a test exception to view your dashboard.
If your setup is not working get in touch

The provider is open source and available at the Raygun4js repository.