GithubHelp home page GithubHelp logo

diederikvandenb / apollo-link-sentry Goto Github PK

View Code? Open in Web Editor NEW
119.0 6.0 34.0 1.75 MB

Apollo Link middleware which enriches SentryJS with GraphQL data

License: MIT License

JavaScript 4.71% TypeScript 95.29%
apollo graphql sentry error-reporting

apollo-link-sentry's Introduction

Apollo Link Sentry

Apollo Link to enrich Sentry events with GraphQL data

GitHub Workflow Status Code Coverage semantic-release

npm-version npm-downloads

Installation

yarn add apollo-link-sentry

Note: Due to a release issue, v3.0.0 of this package has been unpublished. Please use v3.0.1 Note: starting from v2.0.0 of this package we support @apollo/client v3.0.

Features

Turn this:

Before

Into this:

After

Basic setup

Initialize Sentry as you would normally. Then, add apollo-link-sentry to your Apollo Client's link array:

import { SentryLink } from 'apollo-link-sentry';

const client = new ApolloClient({
  link: ApolloLink.from([
    new SentryLink(/* See options */),
    new HttpLink({ uri: 'http://localhost:4000' }),
  ]),
  cache: new InMemoryCache(),
});

Options

See src/options.ts.

Compatibility with other Apollo Links

apollo-link-sentry aims to be friendly with other apollo-link packages, in the sense that we would like for you to be able to attach as much data as you want. For example, if you would like to add the HTTP headers you set with apollo-link-context, you can do that by setting includeContextKeys: ['headers'].

In case you find that there's a piece of data you're missing, feel free to open an issue.

Be careful what you include

Please note that Sentry sets some limits to how big events can be. For instance, events greater than 200KiB are immediately dropped (pre decompression). More information on that here. Be especially careful with the includeCache option, as caches can become quite large.

Furthermore, much of the data you are sending to Sentry can include (sensitive) personal information. This might lead you to violating the terms of the GDPR. Use Sentry's beforeBreadcrumb function to filter out all sensitive data.

Exclude redundant fetch breadcrumbs

By default, Sentry attaches all fetch events as breadcrumbs. Since this package tracks GraphQL requests as breadcrumbs, they would show up duplicated in Sentry.

You can use either one of the following options to exclude redundant fetch breadcrumbs:

  1. Disable the default integration for fetch requests entirely. Note that this is only recommended if you only use GraphQL requests in your application. The default integration can be disabled like this:

    Sentry.init({
      ...,
      defaultIntegrations: [
        new Sentry.BrowserTracing({ traceFetch: false }),
      ],
    });
  2. Use the beforeBreadcrumb option of Sentry to filter out the duplicates. The helpers in this package recognize every breadcrumb of category fetch where the URL contains /graphql as a GraphQL request.

    import { excludeGraphQLFetch } from 'apollo-link-sentry';
    
    Sentry.init({
      ...,
      beforeBreadcrumb: excludeGraphQLFetch,
    })

    If you have a custom wrapper, use the higher order function:

    import { withoutGraphQLFetch } from 'apollo-link-sentry';
    
    Sentry.init({
      ...,
      beforeBreadcrumb: withoutGraphQLFetch((breadcrumb, hint) => { ... }),
    })

FAQ

I don't see any events appearing in my Sentry stream

This package only adds breadcrumbs, you are still responsible for reporting errors to Sentry. You can do this by calling Sentry.captureException():

<Mutation mutation={MUTATION_THAT_MIGHT_FAIL}>
  {(mutate, { data, error, loading }) => {
    if (loading) return <div>loading</div>;
    if (error) return <div>{error.toString()}</div>;

    const onClick = () =>
      mutate().catch((error) => {
        Sentry.captureException(error);
      });

    return (
      <div>
        <button type="button" onClick={() => onClick()}>
          Mutate
        </button>
        {JSON.stringify(data)}
      </div>
    );
  }}
</Mutation>

apollo-link-sentry's People

Contributors

11bit avatar alexbjorlig avatar dependabot-preview[bot] avatar dependabot[bot] avatar diederikvandenb avatar javiermartinz avatar maraisr avatar mellisdesigns avatar narretz avatar repl-sarath avatar revmischa avatar seanohue avatar semantic-release-bot avatar slessi avatar spawnia avatar zichongkao 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

apollo-link-sentry's Issues

Is SentryLink 2.0 becomes a terminating link?

Hi awesome devs,

Thanks for the great dependency. I just want to ask if SentryLink 2.0 and above becomes a terminating link like HTTP link?
Because I tried implementing it to my app and it doesn't trigger any api requests after adding sentry link before http link.

I hope you can help me with this.

Cheers,
Rem

Missing Typescript types for zen-observable in non-dev installation

When using apollo-link-sentry in Typescript project I get an error due to missing types for zen-observable.

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

2 import Observable from 'zen-observable';
                         ~~~~~~~~~~~~~~~~

This is because @types/zen-observable is dev dependency of apollo-link-sentry so it doesn't get installed on npm install apollo-link-sentry.

I suggest using zen-observable-ts which is a thin wrapper adding types. Then instead of

"dependencies": {
    "zen-observable": "^0.8.15"
  },

and

import Observable from 'zen-observable-ts';

we would use

"dependencies": {
    "zen-observable-ts": "^1.1.0"
  },

and

import { Observable } from 'zen-observable-ts';

`includeError` displaying errors as `"[Array]"`

I'm having an issue where the errors are shown as "[Array]", is there a way to map this appropriately? I had to add my own breadcrumb with errorLink. Thank you in advance, great package so far!

Screen Shot 2021-02-15 at 6 40 47 PM

Maintainership of this package

Hi @DiederikvandenB πŸ‘‹

You previously expressed to me that you are no longer actively using this package. Because of that, I can totally see why you wouldn't want to invest effort into supporting it.

Would you be open to take me on as an additional maintainer? I vow to keep up the high quality of this package and will try to do my best to support it going forward.

Missing dependencies on NextJS build

My build fails with the following output;

info  - Creating an optimized production build
Failed to compile.

./node_modules/apollo-link-sentry/lib/SentryLink.js:6:0
Module not found: Can't resolve '@sentry/types'

Import trace for requested module:
./node_modules/apollo-link-sentry/lib/index.js
./src/utils/client.ts
./src/utils/useApollo.ts
./src/pages/_app.tsx

https://nextjs.org/docs/messages/module-not-found

./node_modules/apollo-link-sentry/lib/sentry.js:4:0
Module not found: Can't resolve '@sentry/minimal'

Import trace for requested module:
./node_modules/apollo-link-sentry/lib/SentryLink.js
./node_modules/apollo-link-sentry/lib/index.js
./src/utils/client.ts
./src/utils/useApollo.ts
./src/pages/_app.tsx

https://nextjs.org/docs/messages/module-not-found

I see that @sentry/types and @sentry/minimal are as dev dependencies in the package.json, but apparently are also required in production? Or maybe the dependencies of @sentry/browser have changed, and having that as a peer dependency is no longer enough?

Enable `apollo-link-sentry` tree-shaking via ESM

Because apollo-link-sentry only distributes commonjs – which compiles to require('@sentry/browser') – tree shaking is not possible at the moment. This results in @sentry/replay being bundled in our assets. Removing references to this package removes the extra replay import.

I believe one way to solve this would be for this package to export ESM code.

Question: Possible to only attach breadcrumbs when an error occurs?

Description

I'm wondering if there is a way to only attach the network request as a breadcrumb if there are graphQLErrors or a networkError occurs, otherwise don't attach a breadcrumb.

Context: The main reason I want this is because I think adding a ton of sentry breadcrumbs is going to be a performance hit. I might be wrong?

Code

For example, I do this inside my onErrorLink but I would love to use this library instead to attach breadcrumbs only when a network/graphql error occurs.

const onErrorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
  if (graphQLErrors) {
    graphQLErrors.forEach(({ message, locations, path }) => {
          sentryBreadcrumb(
        `[GraphQL error]: Operation: ${operation.operationName}, Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    }
if (networkError) {
    sentryBreadcrumb(`[Network error]: Operation: ${operation?.operationName}`, {
      networkError,
      operation: JSON.stringify(operation),
    })
  }
}

Importing apollo-link-sentry package gives 350kb of unwanted and unused code.

This is really strange bug I came up with, but here is the reproduction repo (it took me really long time to make): ~zerdox/apollo-link-sentry-441

UPD: Now you can reproduce issue using both rollup and webpack. Originally it was found using vite, so I left it as an option too.

So how to see the issue?

  1. Clone repo (git clone), install dependencies (npm i), build the project (npm run build:rollup)
  2. Search phrase Unexpected single quote character in whole project (including node_modules and other ingnored by default folders. I've included .vscode/settings.json for that)
  3. You can see that search results includes files dist-rollup/index.xxx.js (this is bundle chunk which will go to user's browser) and node_modules/graphql/language/lexer.js, which is somehow maybe dependency (and not devdep) for this project?

How I can confirm it's an issue with apollo-link-sentry?

  1. Simply comment src/apollo.js:4 which imports this package (and it hasn't even been used!)
  2. Build the project again (npm run build:rollup). Repeat the search in your IDE.
  3. Now you can see this unwanted piece of code is now not included in user's bundle.

This bug is really strange because I was trying to fight with it in my production project and this issue could be fixed by removing prettier from devDependencies (which I was using only for formatting my code through npm script). All this started because my pagespeed (lighthouse) rank was low and it was complaining about 80kb of unused code. I started eliminating unused code from user's bundle chunks and this is the first piece of unused code I stumble upon.

Is my reproduction enough? I hope this will be fixed ASAP because importing apollo-link-sentry gives ~350kb of unused code (you can check size of the file by using ls -lh ./dist-rollup/*

I would not be so confused about this if apollo-link-sentry package listed graphql as it's dependencies, but what I see is:
image
deepmerge, dot-prop, tslib, zen-observable are the only dependencies (which don't have any dependencies)

excludeGraphQLFetch should remove unsupported fragment definitions

Summary
Currently the breadcrumbs include fragments that are imported into the query. Not sure about what other people think but they pollute the breadcrumbs list in sentry and are not handled super well graphql.undefined. It would be nice to either remove them from the list or support them in some way.

Approach

  • add another exclusion helper called excludeGraphQLFragments and remove those breadcrumbs.

Screen Shot 2021-10-26 at 10 32 01 am

y

Newest version breaks with react-native

Hi,

I'm using this library to monitor issues with my GraphQL queries in React Native. The newest version 3.1.1 breaks compatibility with sentry for React Native, as it now imports from @sentry/browser.

Do you intend to support React Native or is this library web only?

Thank you,
Thomas

Severity is undefined

Error:

chunk-6N5EL7GV.js?v=7ce2726b:1619 Uncaught TypeError: Cannot read properties of undefined (reading 'Info')
    at severityForResult (apollo-link-sentry.js?v=7ce2726b:1519:104)
    at Object.next (apollo-link-sentry.js?v=7ce2726b:1468:36)
    at notifySubscription (chunk-STF4VR7B.js?v=7ce2726b:11629:13)
    at onNotify (chunk-STF4VR7B.js?v=7ce2726b:11673:3)
    at SubscriptionObserver2.next (chunk-STF4VR7B.js?v=7ce2726b:11729:9)
    at chunk-BJKTG7PL.js?v=7ce2726b:418:22
function severityForResult(result) {
  return result.errors && result.errors.length > 0 ? browser_1.Severity.Error : browser_1.Severity.Info;
}

It's this line:

: Severity.Info;

apollo-link-sentry doesn't seem to natively support IE11

apollo-link-sentry is bundled with our main production code using Webpack + Babel but there seems to be unsupported syntax for IE11 when adding this module.

const and => arrow functions are present in the compiled code.

Could this project be updated to add build support for IE11?

v3.0.0 npm package contains code for old version

When installing the newest release, i would expect the package to contain the results of the latest build. Instead, the contents of node_modules/apollo-link-sentry/lib contain the code of the previous v2.

Remove peer dependencies

Peer dependencies are for signaling that your package is a plugin for another package, but the user should provide the dependency themselves. I think it makes sense to have apollo, @sentry/browser, and possibly graphql as peer dependencies.

On the other hand, I suspect tslib and zen-observable should instead be put into dependencies. There is no reason why the user should provide them themselves. (If this is about dependency deduplication, any user who cares should leverage the resolutions field.)

Question: recommended way to limit size of breadcrumbs?

In our project we have some large queries and mutations.

What is the recommended way to limit the size of the queries/variables --> using the transform fn?

Do you like an idea of a PR adding a option to specify a limit for the query/variables length - and then truncate if above?

Let me know what you think.

Specify level for sentry enrichments

I would like to scope certain sentry enrichments to only appear on error. It would be useful for includeFetchResult, includeError, includeVariables, setTransaction, setFingerprint, etc to be included when there is an error from a query. includeQuery is useful for all sentry issues in my case.

Possible solution

@spawnia suggested to add optional strings for each level i.e. includeFetchResult: 'on-error'. Building off that idea, I would turn it into a list and my ideal config would look like

const sentryLink = new SentryLink({
    setFingerprint: ['on-error'],
    setTransaction: ['on-error'],
    attachBreadcrumbs: {
      includeQuery: ['on-error', 'on-success'],
      includeVariables: ['on-error'],
      includeFetchResult: ['on-error'],
      includeError:  ['on-error'],
    },
  })

Prior thread #278 (comment)

Sentry v8 compatibility

Sentry v8 has been released, which has breaking changes that affect the ability to use plugin.

The issue seems to be this dependency:

"@sentry/browser": "^7.41.0"

https://docs.sentry.io/platforms/javascript/migration/v7-to-v8/#conflicting-dependency-versions-with-bundler-plugins

The Sentry JavaScript Bundler Plugins (@sentry/webpack-plugin, @sentry/vite-plugin, @sentry/esbuild-plugin, @sentry/rollup-plugin) used to depend on certain Sentry SDK packages on version 7 wich may clash with version 8 of the SDK.

This is not one of the mentioned plugins but the same conflict situation seems to be occurring. When trying to use this plugin, I get tthis error:

ApolloError: getHubFromCarrier(...).isOlderThan is not a function
    at new ApolloError2 (chunk-RTGEHEDD.js?v=aff74ec4:280:26)
    at chunk-RTGEHEDD.js?v=aff74ec4:5479:66
    at both (chunk-ZQZ3ZDHD.js?v=aff74ec4:2856:17)
    at chunk-ZQZ3ZDHD.js?v=aff74ec4:2845:26
    at new Promise (<anonymous>)
    at Object.then (chunk-ZQZ3ZDHD.js?v=aff74ec4:2844:16)
    at Object.error (chunk-ZQZ3ZDHD.js?v=aff74ec4:2858:39)
    at notifySubscription (chunk-ZQZ3ZDHD.js?v=aff74ec4:1788:13)
    at onNotify (chunk-ZQZ3ZDHD.js?v=aff74ec4:1827:3)
    at SubscriptionObserver2.error (chunk-ZQZ3ZDHD.js?v=aff74ec4:1868:5) 

Create-React-App warns about missing SourceMap

I'm running into an issue where create-react-app warns about failing to parse source maps:

WARNING in ./node_modules/apollo-link-sentry/lib/SentryLink.js Module Warning (from ./node_modules/source-map-loader/dist/cjs.js): Failed to parse source map from '<private>/node_modules/apollo-link-sentry/src/SentryLink.ts' file: Error: ENOENT: no such file or directory, open '<private>/node_modules/apollo-link-sentry/src/SentryLink.ts'

This unfortunately makes this unable to use for me since our build treats warnings as errors...
And i have no ideas how to circumvent this so any help is greatly appreciated!
Thanks for the nice project!

Can't use package without supporting esnext

I couldn't use the most recent version of this package without supporting esnext on my project.
Can you build this package by targeting an ES/JS version which is widely supported?

`ERROR in ./node_modules/apollo-link-sentry/lib-esm/excludeGraphQLFetch.js 3:36
Module parse failed: Unexpected token (3:36)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export const excludeGraphQLFetch = (breadcrumb) => {
| if (breadcrumb.category === 'fetch') {

    const url = breadcrumb.data?.url ?? '';

| if (url.includes('/graphql')) {
| return null;

ERROR in ./node_modules/apollo-link-sentry/lib-esm/SentryLink.js 7:11
Module parse failed: Unexpected token (7:11)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import { attachBreadcrumbToSentry, setFingerprint, setTransaction, } from './sentry';
| export class SentryLink extends ApolloLink {

options;

| constructor(options = {}) {
| super();`

Transform function can change response for downstream links

I am trying to include the result that the backend is sending with the include fetch results flag. If I modify the breadcrumb information It modifies it for the code calling the request instead of only modifying what is sent to sentry.

Here is an example:

Screen Shot 2022-11-18 at 2 32 20 PM

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.