Skip to content

Allow passing HttpRequest to XhrFactory.build() for request-aware XHR customization #68572

@abdulkareemnalband

Description

@abdulkareemnalband

Which @angular/* package(s) are relevant/related to the feature request?

common

Description

HttpClient uses XhrFactory.build() to create XMLHttpRequest instances.

Currently, build() does not receive the associated HttpRequest, so a custom XhrFactory cannot access request-specific data.

In our case, metadata is added to the request using HttpContext. We want to read that metadata in a custom XhrFactory and attach it to the created XMLHttpRequest. Existing tracing/instrumentation code can then pick up the metadata from the XHR object.

Without access to the HttpRequest, there is no clean way to connect HttpContext metadata with the created XHR instance.

Proposed solution

Allow XhrFactory.build() to optionally receive the HttpRequest.

Example:

abstract class XhrFactory {
  abstract build(req: HttpRequest<unknown>): XMLHttpRequest;
}

Angular’s internal usage could pass the request when creating the XHR:

const xhr = this.xhrFactory.build(req);

A custom implementation could then read metadata from HttpContext and attach it to the XHR:

@Injectable()
export class CustomXhrFactory implements XhrFactory {
  build(req: HttpRequest<unknown>): XMLHttpRequest {
    const xhr = new XMLHttpRequest();

    const metadata = req.context.get(MY_METADATA_CONTEXT_TOKEN);

    if (metadata) {
      (xhr as any).__metadata = metadata;
    }

    return xhr;
  }
}

The parameter should be optional so existing XhrFactory implementations continue to work.

Alternatives considered

HTTP interceptors

Interceptors can access HttpRequest and HttpContext, but they cannot access the underlying XMLHttpRequest. So they cannot attach the metadata to the XHR object.

Shared/global state

Metadata could be stored globally before the XHR is created and then read inside XhrFactory.build().

This is fragile, especially with concurrent requests, and adds hidden coupling.

Using headers

Headers can carry metadata over the network, but they do not help with attaching metadata to the in-memory XHR object that existing tracing/instrumentation code reads.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: common/httpIssues related to HTTP and HTTP Clientneeds: clarificationThis issue needs additional clarification from the reporter before the team can investigate.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions