getsentry / sentry-javascript

Official Sentry SDKs for JavaScript
https://sentry.io
MIT License
7.86k stars 1.55k forks source link

The sentry-trace header is not being sent with fetch requests #3547

Closed taylorlapeyre closed 3 years ago

taylorlapeyre commented 3 years ago

Example event: https://sentry.io/organizations/project-wren/issues/2399314422/events/85d536082ab64b56bf22835c708d986f/

Package + Version

Version:

1.4.9

Description

It seems like the sentry-trace header is not being sent in fetch requests that we send from our app's frontend. We construct our requests this way:

function generateHeaders() {
  const headers = new Headers({
    'Content-Type': 'application/json',
  });

  const token = getSessionToken();

  if (token) {
    headers.set('Authorization', `Bearer ${token}`);
  }

  // another internal header not relevant, 
  headers.set('...', 'something');

  return headers;
}

async function post(endpoint, body) {
  const request = new Request(`${API_URL}/${endpoint}`, {
    method: 'POST',
    headers: generateHeaders(),
    body: JSON.stringify(body),
  });

  const response = await fetch(request);

  if (contentType && contentType.includes('application/json')) {
    const responseBody = await response.json();
    return [response, responseBody];
  }

  return [response, null];
}

We aren't seeing any distributed tracing for our backend service for requests being initiated this way, and the sentry header is not present:

Screen Shot 2021-05-14 at 2 23 16 PM

Our Sentry init:

Sentry.init({
  dsn: '...'
  integrations: [
    new Integrations.BrowserTracing(),
    new SentryFullStory('project-wren'),
  ],
  environment: getReleaseStageFromURL(),
  release: window.appVersion,
  tracingOrigins: ['localhost', 'wren.co'],
  ignoreErrors: [
    'disguiseToken',
    'cancelled',
    'Illegal invocation',
    'Failed to load Stripe.js',
    'Non-Error promise rejection captured',
    'chunk',
  ],
  beforeSend(event) {
    const user = getStore().getState().user;
    if (event.exception) {
      Sentry.showReportDialog({
        eventId: event.event_id,
        user: {
          name: user.firstName,
          email: user.email,
        },
      });
    }

    return event;
  },

  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for performance monitoring.
  // We recommend adjusting this value in production
  tracesSampleRate: 0.5,
});
kamilogorek commented 3 years ago

There has to be an active transaction in order for sentry-trace header to be sent. You can try to call Sentry.getCurrentHub().getScope().getTransaction() just before you send an API request to see whether there's something to be even attached.

bzeskis commented 3 years ago

Hi Taylor, have you managed to find a solution?

taylorlapeyre commented 3 years ago

Hey @bzeskis, yes this can be closed!

fliespl commented 2 years ago

@taylorlapeyre do you mind sharing you solution? Currently struggling with same :) Pageload metrics are being sent, but later on XHR/Fetch requests are not.

boukeversteegh commented 2 years ago

I'm having the same issue. I cannot find documentation that explains how I can configure sentry to keep tracing after the initial pageload.

Sentry.init({
  Vue,
  dsn: config.api.sentry.dsn,
  integrations: [
    new Integrations.BrowserTracing({
      routingInstrumentation: Sentry.vueRouterInstrumentation(router),
      tracingOrigins: [config.hosts.com, config.services.api.host],
    }),
  ],
  tracesSampleRate: 1.0,
})

When I look at the options in BrowserTracing, it implies that it will generate a new transaction automatically on each URL change, and that each transaction lasts at most 1 second.

However, only the very first API request will get a sentry-trace, and everything after doesn't.


Update: I found out the issue in my case is not 'first' vs 'subsequent' requests. My first request was done with window.fetch, whereas my follow up requests were done with an API client generated by swagger-codegen (typescript-fetch). Once I change my first request to use the API client as well, no traces are added even for the first request.

In short, there's an issue with tracing using typescript-fetch api clients with sentry, I may report an issue if I cannot solve it.

boukeversteegh commented 2 years ago

Potentially related issue: https://github.com/getsentry/sentry-javascript/issues/4439