Because
Node.jsSDK

HTTP tracing

Trace outbound HTTP requests with because.fetch.

because.fetch(name, url, init?)

A drop-in replacement for fetch that captures request and response details as an http span on the active trace.

await because.startTrace('api-call', async () => {
  const data = await because.fetch<MyResponse>(
    'get-user',
    'https://api.example.com/users/1'
  );
});

The span captures:

  • Request method, URL, headers, and body
  • Response status, headers, and body
  • Duration in milliseconds

Parameters

ParameterTypeDescription
namestringLabel for the span in the dashboard
urlstring | URLRequest URL
initRequestInitStandard fetch options (method, headers, body, etc.)

Generic type

Pass a generic to type the parsed JSON response:

type Post = { id: number; title: string };

const post = await because.fetch<Post>('get-post', url);
//    ^? Post

POST example

const result = await because.fetch<CreateResponse>(
  'create-record',
  'https://api.example.com/records',
  {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Acme Corp' })
  }
);

Manual HTTP spans

If you need to capture HTTP details from a request you made yourself, use addSpan with type 'http':

import type {
  HttpRequestInput,
  HttpResponseOutput
} from '@refactorlabs/because';

because.addSpan('http', 'external-api', {
  input: {
    method: 'POST',
    url: 'https://api.example.com/infer',
    content_type: 'json',
    body: { prompt: 'Hello' }
  } satisfies HttpRequestInput,
  output: {
    status: 200,
    content_type: 'json',
    body: { result: 'World' }
  } satisfies HttpResponseOutput,
  durationMs: 340
});

On this page