GithubHelp home page GithubHelp logo

rollbar / rollbar-react Goto Github PK

View Code? Open in Web Editor NEW
42.0 20.0 10.0 5.38 MB

React features to enhance using Rollbar.js in React Applications

Home Page: https://docs.rollbar.com/docs/react

License: MIT License

JavaScript 72.77% TypeScript 27.23%
error-monitoring error-reporting javascript observability react reactjs rollbar typescript

rollbar-react's Introduction

rollbar-logo

Rollbar React SDK

Proactively discover, predict, and resolve errors in real-time with Rollbar’s error monitoring platform. Start tracking errors today!


React features to enhance using Rollbar.js in React Applications.

This SDK provides a wrapper around the base Rollbar.js SDK in order to provide an SDK that matches the intention of how to build React Apps with a declarative API, features for the latest React API like hooks and ErrorBoundaries, as well as simplify using Rollbar within a React SPA.

Key benefits of using Rollbar React are:

  • Telemetry: The telemetry timeline provides a list of “breadcrumbs” events that can help developers understand and fix problems in their client-side javascript. Learn more about telemetry.
  • Automatic error grouping: Rollbar aggregates Occurrences caused by the same error into Items that represent application issues. Learn more about reducing log noise.
  • Advanced search: Filter items by many different properties. Learn more about search.
  • Customizable notifications: Rollbar supports several messaging and incident management tools where your team can get notified about errors and important events by real-time alerts. Learn more about Rollbar notifications.

In Beta

It is currently in a public Beta release right now as we push towards a 1.0 release that will have all of the features we want to provide full capability for using React SDK in your production apps. We expect a 1.0 release to come in the next month.

Setup Instructions

Prerequisites

These instructions provide an addendum to the Rollbar.js Setup Instructions.

After following those 2 steps, you will be ready.

Install Rollbar React SDK

To install with npm:

npm install @rollbar/react rollbar

To install with yarn:

yarn add @rollbar/react rollbar

To install by adding to package.json, add the following to your project's package.json file:

  
  "dependencies": {
    "@rollbar/react": "^0.8.0",
    "rollbar": "^2.24.0",
    
  }
  

then run either using npm or yarn (or other package manager):

npm install
# OR
yarn install

Usage and Reference

The React SDK is very new and has not been given the full documentation treatment we expect to get from Rollbar Docs, but that will be coming shortly and a direct link will be put here for your reference.

In the meantime, the basic usage reference is available below.

Simplest Usage Possible

To get you started quickly, here is an example that will get you started right away by providing the easiest and simplest usage possible:

import React from 'react';
import { Provider, ErrorBoundary } from '@rollbar/react'; // <-- Provider imports 'rollbar' for us

// same configuration you would create for the Rollbar.js SDK
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  environment: 'production',
};

export default function App() {
  return (
    {/* Provider instantiates Rollbar client instance handling any uncaught errors or unhandled promises in the browser */}
    <Provider config={rollbarConfig}>
      {/* ErrorBoundary catches all React errors in the tree below and logs them to Rollbar */}
      <ErrorBoundary>
        // all other app providers and components - Rollbar will just work
        
      </ErrorBoundary>
    </Provider>
  );
};

Using with Next.js App Router

The first step to using Rollbar with the Next.js App Router is to configure your Rollbar instance.

import Rollbar from 'rollbar';

const baseConfig = {
  captureUncaught: true,
  captureUnhandledRejections: true,
  environment: process.env.NODE_ENV,
};

export const clientConfig = {
  accessToken: process.env.NEXT_PUBLIC_POST_CLIENT_ITEM_TOKEN,
  ...baseConfig,
};

export const serverInstance = new Rollbar({
  accessToken: process.env.POST_SERVER_ITEM_TOKEN,
  ...baseConfig,
});

We suggest you create a single instance for use server side, to be certain there are not more than one, and a config to use in your client side components. React Server Components limit you to passing simple objects as props from Server Components to Client Components. The config object can be used by the Rollbar Provider to construct your Rollbar instance.

There's a fully functional example that showcases the many ways in which you can integrate Rollbar into your modern web-app leveraging React Server Components and the Next.js App Router.

Components

The following components are available as named imports from @rollbar/react.

Provider Component

The Provider component is used to wrap your React App so an instance of Rollbar will be made available within your React tree.

This is a common pattern in React using a custom React Context that is available to the Components and hooks from this SDK library.

Configuration Only Usage

The simplest way to use the Provider is to provide a configuration as the config prop which will instantiate an instance of Rollbar for you and provide that to its child tree:

import React from 'react';
import { Provider } from '@rollbar/react';

// same configuration you would create for the Rollbar.js SDK
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  environment: 'production',
};

export function App(props) {
  return <Provider config={rollbarConfig}></Provider>;
}

Instance Usage

Sometimes you may need to instantiate an instance of Rollbar before adding it to your App tree. In that case use the instance prop to pass it to the Provider like this:

import React from 'react';
import Rollbar from 'rollbar';
import { Provider } from '@rollbar/react';

// same configuration you would create for the Rollbar.js SDK
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  environment: 'production',
};

const rollbar = new Rollbar(rollbarConfig);

export function App(props) {
  return <Provider instance={rollbar}></Provider>;
}

This method will also work with the global Rollbar instance when using the Rollbar.init(…) method.

React Native Usage

Rollbar provides a React Native SDK which also wraps the Rollbar.js to provide React Native capabilities based on that specific environment.

To use the Rollbar React SDK with the React Native SDK, pass the instance that it generates to the Provider's instance prop, like this:

import React from 'react';
import { Client } from 'rollbar-react-native';
import { Provider } from '@rollbar/react';

const rollbarClient = new Client('POST_CLIENT_ITEM_ACCESS_TOKEN');

export function App(props) {
  return <Provider instance={rollbarClient.rollbar}></Provider>;
}

ErrorBoundary Component

Rollbar's React SDK provides a new ErrorBoundary component which implements the interface for React's Error Boundaries introduced in React 16.

The ErrorBoundary is used to wrap any tree or subtree in your React App to catch React Errors and log them to Rollbar automatically.

The ErrorBoundary relies on the Provider above for the instance of Rollbar, so it will utilize whatever configuration has been provided.

Simple Usage

You can add an ErrorBoundary component to the top of your tree right after the Provider with no additional props and it will just work:

import React from 'react';
import { Provider, ErrorBoundary } from '@rollbar/react';

// same configuration you would create for the Rollbar.js SDK
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  environment: 'production',
};

export function App(props) {
  return (
    <Provider config={rollbarConfig}>
      <ErrorBoundary></ErrorBoundary>
    </Provider>
  );
}

Pass props to control behavior

The ErrorBoundary provides several props that allow customizing the behavior of how it will report errors to Rollbar.

These props take either a value or a function that will be invoked with the error and info from the Error Boundaries API's componentDidCatch method (i.e. signature is (error, info)).

import React from 'react';
import { Provider, ErrorBoundary, LEVEL_WARN } from '@rollbar/react';

// same configuration you would create for the Rollbar.js SDK
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  environment: 'production',
};

export function App(props) {
  return (
    <Provider config={rollbarConfig}>
      <ErrorBoundary
        level={LEVEL_WARN}
        errorMessage="Error in React render"
        extra={(error, info) =>
          info.componentStack.includes('Experimental')
            ? { experiment: true }
            : {}
        }
      ></ErrorBoundary>
    </Provider>
  );
}

Pass a Fallback UI

You may also include a Fallback UI to render when the error occurs so that the User does not experience a broken/blank UI caused during the render cycle of React.

It can accept a value that is a React Component

import React from 'react';
import { Provider, ErrorBoundary, LEVEL_WARN } from '@rollbar/react';

// same configuration you would create for the Rollbar.js SDK
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  environment: 'production',
};

const ErrorDisplay = (
  { error, resetError }, // <-- props passed to fallbackUI component
) => (
  <div>
    <h1>A following error has occured:</h1>
    <p>{error.toString()}</p>
  </div>
);

export function App(props) {
  return (
    <Provider config={rollbarConfig}>
      <ErrorBoundary level={LEVEL_WARN} fallbackUI={ErrorDisplay}></ErrorBoundary>
    </Provider>
  );
}

RollbarContext Component

Use the RollbarContext component to declaratively set the context value used by Rollbar.js when it's sending any messages to Rollbar.

This works for your ErrorBoundary from above or any other log or message sent to Rollbar while the RollbarContext is mounted on the tree.

Like ErrorBoundary above, RollbarContext relies on a Provider for an instance of a Rollbar.js client.

Basic Usage

To use the RollbarContext you must provide the context prop, a String that is used to set the context used by Rollbar.js to the value while mounted.

import React from 'react';
import { RollbarContext } from '@rollbar/react';

function HomePage() {
  return <RollbarContext context="home"></RollbarContext>;
}

Using with React Router

It's useful to set the context in Rollbar associated with areas of your application. On the server it's usually set when a specific page is requested. For SPAs like React Apps, using RollbarContext with your Router is one way to achieve the same result.

Here is an example of using RollbarContext with [React Router] if you have a top level set of routes:

import React from 'react';
import { Router, Switch, Route } from 'react-router-dom';
import { RollbarContext } from '@rollbar/react';
import { About, ContactDetails, ContactsList } from './pages';

const Routes = () => (
  <Router>
    <Switch>
      <Route path="/about">
        <RollbarContext context="/about">
          <About />
        </RollbarContext>
      </Route>
      <Route path="/contacts/:id">
        <RollbarContext context="contacts/details">
          <ContactDetails />
        </RollbarContext>
      </Route>
      <Route path="/contacts">
        <RollbarContext context="contacts">
          <ContactsList />
        </RollbarContext>
      </Route>
    </Switch>
  </Router>
);

export default Routes;

Here's another example of using RollbarContext within a component that manages its own route:

import React from 'react';
import { Route } from 'react-router-dom';
import { RollbarContext } from '@rollbar/react';

export default function About(props) {
  return (
    <Route path="/about">
      <RollbarContext context="/about"></RollbarContext>
    </Route>
  );
}

Functions

The following functions are available as named imports from @rollbar/react.

historyContext to create history.listener

A lot of SPAs and React Apps will use the history package to handle browser history. The historyContext function is a helper that creates a valid listener function to receive history changes and use those to change the Rollbar.js context.

historyContext is a factory function used to create a proper history.listen callback that will work for v4 and v5 of the history package.

Basic historyContext usage

The historyContext factory function requires an instance of Rollbar.js to wrap in order to create the listener callback function.

By default, if no options (see below) are provided, all history updates will update the context for Rollbar using the location.pathname as the value.

import Rollbar from 'rollbar';
import { createBrowserHistory } from 'history';
import { Provider } from '@rollbar/react';

// same configuration you would create for the Rollbar.js SDK
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  environment: 'production',
};

const rollbar = new Rollbar(rollbarConfig);

const history = createBrowserHistory();

history.listen(historyContext(rollbar));

Controlling historyContext behavior with options

The historyContext factory function accepts options as a 2nd argument that allow you to control the behavior of how and when the context will be set for the Rollbar.js client.

Use the formatter option to provide a function that will receive the history change event and return a String that you would like to be set as the context for Rollbar.

The signature is formatter(location, action): String where location is history.location and action is history.action.

The other option is filter which you can provide to tell the historyContext listener you create to control which history updates will change the context for Rollbar. All truthy values will tell the listener to make the change. Any falsy values will skip the update.

The signature is filter(location, action): Boolean where location is history.location and action is history.action.

Here's an example of using both:

import Rollbar from 'rollbar';
import { createBrowserHistory } from 'history';
import { Provider } from '@rollbar/react';

// same configuration you would create for the Rollbar.js SDK
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  environment: 'production',
};

const rollbar = new Rollbar(rollbarConfig);

const ROUTE_PARAMS_RE = /\/\d+/g;

const historyListener = historyContext(rollbar, {
  // optional: default uses location.pathname
  formatter: (location, action) =>
    location.pathname.replace(ROUTE_PARAMS_RE, ''),
  // optional: true return sets Rollbar context
  filter: (location, action) => !location.pathname.includes('admin'),
});
const unlisten = history.listen(historyListener);

Hooks

The following hooks are available as named imports from @rollbar/react for use in Functional Components making use of the React Hooks API introduced in React 16.8.

Reliance on Provider

All of these hooks below require there to be a Provider in the React Tree as an ancestor to the component using the hook.

useRollbar hook

To consume the Rollbar.js instance directly from the Provider in your React Tree and make use of the client API within your [Functional Component], use the useRollbar hook which will return the instance from the currently scoped React Context.

Here is a basic example:

import { useRollbar } from '@rollbar/react';

function ContactDetails({ contactId }) {
  const rollbar = useRollbar(); // <-- must have parent Provider
  const [contact, setContact] = useState();

  useEffect(async () => {
    try {
      const { data } = await getContactFromApi(contactId);
      setContact(data.contact);
    } catch (error) {
      rollbar.error('Error fetching contact', error, { contactId });
    }
  }, [contactId]);

  return <div></div>;
}

useRollbarContext hook

As an alternative to the RollbarContext component, you can use the useRollbarContext hook in your [Functional Component] to set the context in the Rollbar.js client provided by the Provider above in the React Tree.

Here's an example of using it in several components:

// src/pages/HomePage.js
import { useRollbarContext } from '@rollbar/react';

function HomePage(props) {
  useRollbarContext('home#index');

  return <div></div>;
}

// src/pages/UsersPage.js
import { useRollbarContext } from '@rollbar/react';
import UserTable from '../components/users/UserTable';

function UsersPage(props) {
  useRollbarContext('users#list');

  return <UserTable data={props.users} />;
}

// src/pages/UserDetailsPage.js
import { useRollbarContext } from '@rollbar/react';
import UserDetails from '../components/users/UserDetails';

function UserDetailsPage(props) {
  useRollbarContext('users#details');

  return <UserDetails user={props.user} />;
}

useRollbarPerson hook

It's very usefull in Rollbar to log the identity of a person or user using your App for 2 major reasons:

  1. It allows you to know exactly who has been affected by an item or error in your App
  2. It allows Rollbar to tell you the impact a given item or error is having on your users

To make it convenient and easy to set the identity of a person in your React App, the @rollbar/react package has the userRollbarPerson hook.

To use it, simply pass an Object that has keys and values used to identify an individual user of your App, and for any future events or messages logged to Rollbar will include that person data attached to the log.

Here is a simple example of using it once the current user has been determined:

import { useState } from 'react';
import { useRollbarPerson } from '@rollbar/react';
import LoggedInHome from './LoggedInHome';
import LoggedOutHome from './LoggedOutHome';

function Home() {
  const [currentUser, setCurrentUser] = useState();
  useRollbarPerson(currentUser);

  useEffect(() => {
    (async () => {
      const user = await Auth.getCurrentUser();
      setCurrentUser(user);
    })();
  });

  if (currentUser != null) {
    return <LoggedInHome />;
  }

  return <LoggedOutHome />;
}

useRollbarCaptureEvent hook

Rollbar.js already provides automated Telemetry with the default configuration autoInstrument: true in the client which will capture useful telemetry events and data for you.

To provide more breadcrumbs useful for identifying the cause of an item or error, you can add your own capture events that will be included in the Telemetry of an item in Rollbar with the useRollbarCaptureEvent hook.

The useRollbarCaptureEvent hook is designed to capture a new event in your [Functional Component] any time the metadata or level you provide to the hook changes. On rerenders, no event is captured if there is not a change to the references provided to those 2 arguments (utilizing the dependencies array arg underneath within the call to the built-in React useEffect hook).

Here is an example of using useRollbarCaptureEvent in the render cycle of a [Functional Component] to send a telemetry event related to the data that will be rendered in the component

import { useEffect, useState } from 'react';
import { useRollbar, useRollbarCaptureEvent, LEVEL_INFO } from '@rollbar/react';

function BookDetails({ bookId }) {
  const rollbar = useRollbar(); // <-- must have ancestor Provider, same with useRollbarCaptureEvent
  const [book, setBook] = useState();

  useEffect(async () => {
    try {
      const { data } = await getBook(bookId);
      setBook(data.book);
    } catch (error) {
      rollbar.error('Error fetching book', error, { bookId }); // <-- use rollbar to log errors as normal
    }
  }, [bookId]);

  useRollbarCaptureEvent(book, LEVEL_INFO); // <-- only fires when book changes

  return <div></div>;
}

rollbar-react's People

Contributors

bxsx avatar chromeq avatar criles25 avatar danfry1 avatar dependabot[bot] avatar emesa avatar eudaimos avatar ijsnow avatar matux avatar mudetroit avatar paulserraino avatar quinnturner avatar viniciushiga avatar waltjones avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rollbar-react's Issues

Provider config should not be required if instance provided

Provider requires a config prop but it is unused if an instance is provided.

export class Provider extends Component {
  static propTypes = {
    Rollbar: PropTypes.func,
    config: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired,
    instance: PropTypes.instanceOf(Rollbar),
  }
...

process is not defined - nx webkit typescript react project

I have an nx monorepo project with a typescript react app inside it. When i use @rollbar/react within this project i am seeing errors for process is not defined. These errors only appear when i have captureUncaught: true and/or captureUnhandledRejections: true in my Rollbar config.

Pictures of the error

image

image

Rollbar config

const rollbarConfig: Rollbar.Configuration = {
  enabled: process.env.NODE_ENV !== 'development',
  accessToken: 'REDACTED',
  environment: getRollbarEnvironment(),
  captureUncaught: true,
  captureUnhandledRejections: true,
  payload: {
    context: 'root',
    client: {
      javascript: {
        source_map_enabled: true,
      },
    },
  },
};

Environment:
OSX
node: 18.12.1
rollbar: 2.26.1
@rollbar/react: 0.11.1
react: 18.2.0
nx: 15.5.3

Incorrect typescript type on fallbackUI prop on ErrorBoundary

The fallbackUI prop of ErrorBoundary has incorrect type in index.d.ts:

fallbackUI?: ReactNode;

But the docs says it should be a react component. If I pass a react component:

const FatalError = () => {
    return 'Error';
}

<ErrorBoundary fallbackUI={FatalError}>
   ...
</ErrorBoundary>

typescript will complain with

No overload matches this call.
  Overload 1 of 2, '(props: ErrorBoundaryProps | Readonly<ErrorBoundaryProps>): ErrorBoundary', gave the following error.
    Type 'FC<{}>' is not assignable to type 'ReactNode'.
  Overload 2 of 2, '(props: ErrorBoundaryProps, context: any): ErrorBoundary', gave the following error.
    Type 'FC<{}>' is not assignable to type 'ReactNode'.

React Hook "useRollbarPerson" cannot be called inside a callback

Hi, I am trying to utilize the useRollbarPerson following the example provided in the documentation. I run into the following build error (the project uses Next.js with TypeScript), though:

Error: React Hook "useRollbarPerson" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.  react-hooks/rules-of-hooks

I assume this is a combination of the function name starting with use and it not being used in the function component itself. I am trying to use the function, as the example in the documentation here does, within a useEffect hook.

Is there maybe a proposed way around this issue? Or should this function possibly be renamed (e.g., setRollbarPerson)?

Errors not reported in some circumstances

Description

When using the ErrorBoundary there are errors reported to the console which do not seem to be reported to Rollbar properly.

Steps to recreate

  1. Create a new app using create react app
  2. install @rollbar/react and rollbar
  3. Update the app.js file to the following
import { Provider as RollbarProvider, ErrorBoundary } from "@rollbar/react";

import "./App.css";

const rollbarConfig = {
  accessToken:  <Put a project key in here>,
  captureUncaught: true,
  captureUnhandledRejections: true,
  payload: {
    environment: `dev`,
  },
};

function ErrorFallback() {
  return <div>Oops</div>;
}

function App() {
  return (
    <RollbarProvider config={rollbarConfig}>
      <ErrorBoundary fallbackUI={ErrorFallback}>{undefined}</ErrorBoundary>
    </RollbarProvider>
  );
}

export default App;
  1. Start the app up

Note now that the error caused by trying to render undefined appears in the console, but does not appear in the rollbar project

Failed to compile

Hello,
While compiling there is a error message :

Failed to compile.
./node_modules/@rollbar/react/dist/index.js
Module not found: Can't resolve 'rollbar' in 'blablabla/node_modules/@rollbar/react/dist'

TypeScript types don't match implementation

Currently, the TypeScript type definitions do not match the documentation nor the implementation. Here are the problems I've encountered so far in one afternoon of integrating the library:

  • <ErrorBoundary> has a fallbackUI prop, which is a ReactNode (the result of rendering a component) in types, but is assumed to be a function (a functional component) in the implementation. The correct type would most likely be React.ComponentType<{}> or React.FC<{}>.
  • historyContext has multiple issues:
    • The documentation (and implementation) claims to support both History v4 and History v5, but the types are only compatible with V4.
    • filter and formatter functions receive location as a string, but it is in fact a Location object, not a string.
    • filter and formatter are documented as optional, but they are required arguments in types.
    • Furthermore, the types are not correct even for V4:
      • The function returns a callback which receives an object consisting of action and filter, but this seems like a copy-paste mistake and the correct signature is probably (location: Location, action: string).
      • You need to define your own Location type, unless you want to take a dependency on history.

Typescript Types not available in npm package

Looks like some types were included in v0.9.0 but when I install via npm install @rollbar/react then the correct version is installed but types are still missing.

I think the index.d.ts is not included in the package:
image

So the types are not available in the code:

error TS7016: Could not find a declaration file for module '@rollbar/react'. '.../node_modules/@rollbar/react/lib/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/rollbar__react` if it exists or add a new declaration (.d.ts) file containing `declare module '@rollbar/react';`

8 import { Provider as RollbarProvider, ErrorBoundary as RollbarErrorBoundary } from '@rollbar/react';

Buggy behavior in Next.js app when hostSafeList is set in rollbar config

We discovered a weird behavior happening when using the ErrorBoundary component in a next.js app with the hostSafeList property set in the rollbar config.

we have a simple app set up as follows:

// _app.tsx
<RollbarProvider instance={rollbar}>
  <ErrorBoundary>
  // other providers and app components
    <Component {...pageProps} />
  </ErrorBoundary>
 </RollbarProvider>

This doesn’t seem to be working the way we expect (at least we suspect that). If we call rollbar.error explicitly from our application we see the error making it all the way to rollbar as expected. However, if we go into a component in our component tree and throw an exception, we do not see that being sent to rollbar. This is how we are throwing the error in said component:

// in a component down in the tree
 useEffect(() => {
    // rollbar.error('testing rollbar') this works
    throw new Error('testing rollbar uncaught') // this doesn't work
  })

This is what our instance config looks like:

{
  accessToken: process.env.NEXT_PUBLIC_ROLLBAR_TOKEN,
  hostSafeList: [
    'mydomain.com',
    'subdomain.mydomain.com'
  ],
  captureUncaught: true,
  captureUnhandledRejections: true,
  environment: process.env.NEXT_PUBLIC_APP_ENV,
  payload: {
    environment: process.env.NEXT_PUBLIC_APP_ENV,
    client: {
      javascript: {
        source_map_enabled: true,
        code_version: process.env.NEXT_PUBLIC_CIRCLE_SHA1,
        guess_uncaught_frames: true
      }
    }
  },
  scrubFields: [
    'first_name',
    'last_name',
    'full_name',
    'phone',
    'email',
    'firstName',
    'lastName',
    'fullName',
    'address',
    'street_address',
    'streetAddress'
  ]
}

We expected to see those thrown errors sent to rollbar but that is not happening. As soon as you remove the hostSafeList property from the config it works as expected.
Not sure why this might be happening, will continue to investigate and report here if we find what the issue is.

All console.logs in Chrome Devtools are swallowed in telemetry.js

I've implement React Rollbar according to the documentation and the error logs are reaching the dashboard as expected:

import { Provider as ErrorProvider } from '@rollbar/react';


export const rollbarConfig = {
    accessToken: import.meta.env.VITE_ROLLBAR_ACCESS_TOKEN,
    environment: 'development',
    captureUncaught: true,
    captureUnhandledRejections: true,
};

// and in the component render wrapping the root app element with...
<ErrorProvider config={rollbarConfig}>
     <App />
</ErrorProvider>

The issue is the stack of every console.log in the app now shows it originated at telemetry.js line 518:

day -> 1 telemetry.js:518

Is there a flag to disable this behaviour to see the original source line while developing.

Changing the environment field in the configuration to development did NOT work.

App Crashing whenever attempting simple usage of `RollbarContext`

Hello all,

I am working on my initial rollbar integration, so I apologise if this is just a silly misunderstanding or if this is the incorrect forum.

I was looking to give my rollbar errors more context by route in my react app. I started adding RollbarContext wrappers with simple context strings in them to the routes, but I was getting an error whenever I navigated to these routes.

Below, I have an example of the simplest possible usage of this with our react app. It is in the root component, wrapping all of the routes, inside a correctly initialized Provider. ( I am 100% sure that the provider is initialized correctly) It gives the error from the following screenshot now whenever I open the app.


Screen Shot 2021-11-11 at 2 41 49 PM

Screen Shot 2021-11-11 at 2 44 21 PM


Anybody here have any insight as to what I may be doing incorrectly here?

Thank you so much for your help!

Is there a way to log caught exceptions to Rollbar from class components?

Is there a way to log caught exceptions to Rollbar from class components using @rollbar/react?

At present, it appears that Provider and ErrorBoundary only log uncaught exceptions. Logging caught exceptions in functional components seems to be possible using the useRollbar hook to access the Rollbar instance created by Provider.

Is there a way something similar can be achieve for children class components, or would I also have to import rollbar and instantiate it myself in class components? Or perhaps create a HOC that passes in the rollbar instance?

Fallback UI throws React error and does not render fallback UI

As titled, Fallback UI does not render using fallbackUI prop on <ErrorBoundary /> component.

Using React 17.0.2 and Next.js 11.1.0.

The tag <fallbackUI> is unrecognized in this browser.
If you meant to render a React component, start its name with an uppercase letter.

Upgrade Peer Dependencies for React 18

We are using React 18 for our project, and receive the below error when trying to npm install @rollbar/react. It's possible to work around this with --legacy-peer-deps flag, but would be great if this was no longer needed.

npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"18.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.0.0-0 || ^17.0.0-0" from @rollbar/[email protected]
npm ERR! node_modules/@rollbar/react
npm ERR!   @rollbar/react@"0.11.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Invalid hook usage in documentation

The README documents the useRollbarPerson hook being used in this manner

import { useState } from 'react';
import { useRollbarPerson } from '@rollbar/react';
import LoggedInHome  from './LoggedInHome';
import LoggedOutHome from './LoggedOutHome';

function Home() {
  const [currentUser, setCurrentUser] = useState();

  useEffect(async () => {
    const user = await Auth.getCurrentUser();
    if (user) {
      useRollbarPerson(user);
    }
    setCurrentUser(user);
  });

  if (currentUser != null) {
    return <LoggedInHome />;
  }

  return <LoggedOutHome />;
}

That usage pattern is flagged by the eslint hook plugin as violating the Rules of Hooks, specifically that the hook is called in a function that is neither a custom hook nor a React component.

It is also worth noting that it is an improper usage of useEffect in the first place as it is being passed an async function and needs to be given a sync one.

Request is sent to Rollbar several times

If several Providers used and each of them has captureUnhandledRejections: true field in config, then if there is the error bubbled up to window.onerror, it will cause rollbar to send requests depending on number of Provider usage on page

historyContext: incomplete/outdated information

historyContext does not return something that can be used with history.listen().

export function historyContext(
  rollbar: Rollbar,
  args: {
    formatter: (location: string, action: string) => string;
    filter: (location: string, action: string) => boolean;
  }
): (
  v4Location: {
    action: string;
    filter: (location: string, action: string) => boolean;
  },
  v4action: string
) => void;

Cannot read properties of undefined (reading 'context')

I'm trying to use RollbarContext and it's giving me an error on its componentDidMount function as it's trying to access rollbar.options.payload.context (see here). Looking at the rollbar.options object, there's no payload.

image

This is how I'm using the <RollbarContext>:

const rollbarConfig = {
  accessToken: '<token>',
  environment: 'testenv',
};
...
    <Provider config={rollbarConfig}>
       <ErrorBoundary>
        <Router>
          <Route path={rootPath}>
            <Switch>
              {Object.entries(routes).map(([path, route]) => {
                return (
                  <RollbarContext context={path}>
                    <LazyRoute ... />
                  </RollbarContext>
                );
              })}
              <Redirect from="*" to="/app/404" />
            </Switch>
          </Route>
        </Router>
      </ErrorBoundary>
    </Provider>

I'm using the following versions of the libraries:

<RollbarContext /> implementation doesn't match docs

Docs: https://docs.rollbar.com/docs/react#rollbarcontext-component

1 - RollbarContext requires the onRender prop

Calling

<RollbarContext context="home"></RollbarContext>

doesn't actually set Rollbar's context to 'home'. On further examination of the RollbarContext component, I saw I needed to add a onRender prop for it to work:

<RollbarContext context="home" onRender></RollbarContext>

This doesn't align with the docs linked above.

2 - RollbarContext type is incorrect

Given the requirement of the onRender prop, RollbarContext's type is incomplete.

Next.js AppRoute Example: How can we log an error in the middleware

Hi, I tried the Next.js App Router example. (#122)

I modified the middleware to log error.

Before

export function middleware(request: NextRequest) {
rollbar.configure({ payload: { context: request.nextUrl.pathname } });
return NextResponse.next();
}

After

export function middleware(request: NextRequest) {
  rollbar.configure({ payload: { context: request.nextUrl.pathname } });

  rollbar.error('error!', (err, response) => {
    // insufficient privileges: post_client_item scope is required but the access token only has post_server_item.
    console.log('error', err, response);
  });

  return NextResponse.next();
}

But as commented above, this causes insufficient privileges error.

If I change the server token to a client post token here:

accessToken: process.env.POST_SERVER_ITEM_TOKEN,

The middleware can log the error.
But should I use the client post token in the middleware?

Is there a way to recommend?

Analysis: 100% of dependency updates in this repository can be merged.

Hey there 👋

Our bot, Adaptly, found that 9 out of 9 currently open dependency update PRs can be merged.
That's 100% right there:

View Safe to Merge PRs1. build(deps): bump word-wrap from 1.2.3 to 1.2.4 in /examples/typescript
2. build(deps): bump word-wrap from 1.2.3 to 1.2.4 in /examples/create-react-app
3. build(deps-dev): bump word-wrap from 1.2.3 to 1.2.4 in /examples/nextjs
4. build(deps-dev): bump word-wrap from 1.2.3 to 1.2.4
5. build(deps): bump semver from 6.3.0 to 6.3.1 in /examples/typescript
6. build(deps): bump semver from 6.3.0 to 6.3.1 in /examples/create-react-app
7. build(deps): bump tough-cookie from 4.1.2 to 4.1.3 in /examples/typescript
8. build(deps): bump tough-cookie from 4.0.0 to 4.1.3 in /examples/create-react-app
9. build(deps): bump tough-cookie from 4.0.0 to 4.1.3

feels

🔎   How does Adaptly know this?

It analyses changelogs of dependencies updated in a PR.
If no breaking changes are found in the changelogs, PR is marked as good to merge.

✨ Try Adaptly yourself

Feel free to try Adaptly on your repositories and finally
merge dependency update PRs. Let us know if you have any questions.

Best of luck with your projects,
Lauris
[email protected]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.