Skip to content

Async logic to parse response body in beforeSend to enrich resource context #3767

@derekhubbard

Description

@derekhubbard

What are you trying to achieve and what is your issue? Please describe.
I'm trying to enrich resource events with data from the resource response body. My resource is an XHR for a GraphQL resource, and the response is a Blob. Getting the text of the Blob and parsing it as JSON is an async operation, and it seems like the browser sdk is not waiting for the promise returned by the beforeSend function to complete before sending the resource event.

In the example code below, the data added to the event context before the async call to context.xhr.response.text() are included in the event attributes. The additional data added to the event context after the async call are not included in the event attributes. It seems the event is sent to Datadog when the promise is returned rather than waiting for it to be resolved.

Example code:

const beforeSend = async (event, context) => {
  // Add custom context to the event if it is a resource event for a graphql request
  if (event.type === 'resource' && event.resource.type === 'xhr' && event.resource.url.includes('/graphql')) {
    event.context['disneyland'] = 'california';

    if (context.xhr && context.xhr.response) {
      try {
        let responseBody;
        if (context.xhr.response instanceof Blob) {
          // Handle Blob response
          const text = await context.xhr.response.text();
          responseBody = JSON.parse(text);
        } else {
          // Handle regular JSON response
          responseBody = JSON.parse(context.xhr.response);
        }
        event.context['disneyworld'] = 'florida';
        event.context['responsebody'] = responseBody;
      } catch (e) {
        // If parsing fails, we just skip adding the response body to the context
      }
    }
  }
  return true;
};
Image

Describe the solution you'd like
If the beforeSend function returns a promise, the event should not be sent to Datadog until the promise is resolved/rejected.

Describe alternatives you've considered
I have also considered sending my own custom resource events for this, rather than relying on the resource events generated automatically for my GraphQL requests. It seems like this was supported by the browser sdk at one point maybe, but I'm not currently seeing any functions in the sdk to support sending custom resource events.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions