Networking and distributed tracing
How requests made with fetch and XMLHttpRequest are captured, how the traceparent header joins them to backend traces on Android and iOS, propagating a JavaScript span to your API, and recording requests the SDKs cannot see.
React Native has no network stack of its own. fetch, XMLHttpRequest and libraries built on them, such as axios, hand requests to OkHttp on Android and to URLSession on iOS — and the native SDKs already instrument both. There is nothing to wrap in JavaScript. What you do configure is which requests are captured and which of them carry a traceparent header to your backend.
What is captured
Each request becomes a span of type perf.network_request, named METHOD /path — for example GET /v1/orders — with the URL, method, status code, body sizes and duration. A request that gets no HTTP response (DNS failure, timeout, connection refused) is recorded with the error type and message.
| Android | iOS | |
|---|---|---|
| Instrumented client | OkHttp, instrumented at build time by the Gradle plugin | URLSession |
| Also covers | Native libraries that use OkHttp or HttpURLConnection | Native libraries that use URLSession |
| Not covered | WebSockets, native clients that use neither | WebSockets, native clients that use something else |
| The SDK's own uploads | Excluded automatically | Excluded automatically |
Because capture is native, requests made while JavaScript is still loading are recorded too, when the SDK was started natively.
Excluding requests
Exclude hosts you do not want recorded: analytics beacons, a second OTLP backend, health checks.
| Platform | Setting | Matching |
|---|---|---|
| Android | sdk_config.networking.disabled_url_patterns in sophonz-config.json | Regular expressions |
| iOS, JS start | sdkConfig.ios.disabledUrlPatterns | Substring of the URL |
| iOS, native start | URLSessionCaptureService.Options(ignoredURLs:) | Substring of the URL |
{
"sdk_config": {
"networking": {
"disabled_url_patterns": ["analytics\\.example\\.com", "otlp\\.example\\.com"]
}
}
}await initialize({
sdkConfig: {
ios: {
collectorUrl: "https://in.sophonz.ai",
appKey: "sk_ios_replace_me",
disabledUrlPatterns: ["analytics.example.com", "otlp.example.com"],
},
},
});Distributed tracing
A backend instrumented with OpenTelemetry continues a trace when a request carries a W3C traceparent header. The native SDKs add that header to the requests they capture, using the request span's own trace and span id, so the backend's spans become children of the app's network span and the portal can show the request from tap to database.
The two platforms start from opposite defaults.
Android
Injection is off by default. Turn it on in sophonz-config.json, and limit it to hosts you control:
{
"sdk_config": {
"networking": {
"enable_traceparent_injection": true,
"traceparent_only_allow_domains": ["api.example.com"],
"enable_network_span_forwarding": true
}
}
}| Key | Default | Effect |
|---|---|---|
enable_traceparent_injection | false | Add traceparent to captured OkHttp requests |
traceparent_only_allow_domains | unset | Only these hosts receive it |
enable_network_span_forwarding | false | Also record the traceparent on the request span as spz.w3c_traceparent, including requests recorded with recordNetworkRequest |
With Expo, put the same networking object in the plugin's androidSDKConfig prop.
iOS
Injection is on for every host by default. From JavaScript there is only an off switch:
await initialize({
sdkConfig: {
ios: {
collectorUrl: "https://in.sophonz.ai",
appKey: "sk_ios_replace_me",
disableNetworkSpanForwarding: true, // no traceparent on any request
},
},
});To send it only to your own hosts, start the SDK natively and pass an allowlist:
import Foundation
import SophonzIO
@objcMembers class SophonzInitializer: NSObject {
static func start() {
let builder = CaptureServicesOptionsBuilder()
builder.addUrlSessionCaptureService(
withOptions: URLSessionCaptureService.Options(
ignoredURLs: ["otlp.example.com"],
traceparent: URLSessionCaptureService.Traceparent(onlyAllowDomains: ["api.example.com"])
)
)
builder.addDefaults()
do {
try Sophonz.start(
options: .withCollector(
url: "https://in.sophonz.ai",
appKey: "sk_ios_replace_me",
platform: .reactNative,
captureServices: builder.build()
)
)
} catch {
print("[sophonz] failed to start: \(error)")
}
}
}Domain entries must be bare hostnames; subdomains match. An entry containing /, whitespace or a leading dot is dropped with a warning, and an empty array sends the header nowhere. See iOS configuration.
CAUTION — Third-party APIs see your trace ids
Without an allowlist, every host the app calls receives traceparent — payment providers, CDNs, analytics. That leaks internal trace ids, and a few strict APIs reject unknown headers. Restrict the header to your own domains on both platforms.
An existing header is kept
If a request already has a traceparent header, neither SDK replaces it. That is how a span you create in JavaScript can become the parent of the backend's spans instead of the network span:
import {trace} from "@opentelemetry/api";
import type {SophonzNativeSpan} from "@sophonz/react-native-tracer-provider";
const tracer = trace.getTracer("checkout");
export async function submitOrder(order: Order) {
const span = tracer.startSpan("submit-order");
try {
// the native side assigns the ids, so wait for them
const {traceId, spanId} = await (span as SophonzNativeSpan).spanContextAsync();
const response = await fetch("https://api.example.com/v1/orders", {
method: "POST",
headers: {
"content-type": "application/json",
traceparent: `00-${traceId}-${spanId}-01`,
},
body: JSON.stringify(order),
});
span.setAttribute("http.response.status_code", response.status);
return await response.json();
} finally {
span.end();
}
}The tracer provider must be registered globally for trace.getTracer to reach it; see OpenTelemetry and OTLP.
The backend side
The backend has to accept and continue the header. With the Sophonz server SDKs that is the default:
- Node.js middleware
- Python middleware
- Java, Go and other OpenTelemetry SDKs with the W3C trace context propagator, which is the OpenTelemetry default
CORS does not apply to requests made by the app itself: fetch in React Native is not a browser, and no preflight is sent. It does apply to pages loaded in a WebView, which follow the browser SDK rules, including Access-Control-Allow-Headers: traceparent on your API.
Recording requests manually
For requests the SDKs cannot see — a native module with its own HTTP client, a request relayed over a WebSocket — record the outcome yourself.
import {logNetworkClientError, recordNetworkRequest} from "@sophonz/react-native";
const start = Date.now();
try {
const result = await nativePaymentsClient.charge(cart);
await recordNetworkRequest(
"https://payments.example.com/v2/charges",
"POST",
start,
Date.now(),
result.requestBytes,
result.responseBytes,
result.statusCode,
);
} catch (e) {
await logNetworkClientError(
"https://payments.example.com/v2/charges",
"POST",
start,
Date.now(),
"ConnectionError",
(e as Error).message,
);
}Times are epoch milliseconds. A size or status of 0 or less is treated as unknown and left off the span. The method must be a standard HTTP method; on Android anything else is rejected and the call resolves false.
A manually recorded span carries spz.w3c_traceparent on iOS unless disableNetworkSpanForwarding is set, and on Android when enable_network_span_forwarding is on. No header is sent anywhere — the request has already happened.
NOTE — Do not record captured requests again
Calling recordNetworkRequest for a fetch produces a second span for the same request. Use it only for traffic that bypasses OkHttp and URLSession.
Checking
- Open a session and look for
perf.network_requestspans named after your API paths. - For tracing, inspect a request at the backend: it should carry
traceparent: 00-<32 hex>-<16 hex>-01. On Android, no header usually meansenable_traceparent_injectionis stillfalse; on iOS, the host is missing fromonlyAllowDomainsordisableNetworkSpanForwardingis on. - A second OTLP backend showing up as a stream of network spans means its host is not excluded.