# Node.js (fetch — No Dependencies)

For Node.js 18+ using the built-in `fetch` API:

{% code lineNumbers="true" %}

```
/**
 * HOW TO RUN:
 * 1. Save this file as `test-trust-sse-js.js` (standard CommonJS).
 * 2. Run the following command in your terminal:
 * node test-trust-sse-js.js
 */

const API_BASE_URL = "https://trust-sse.oten.com";
const API_KEY = "ot_live_-d5Il4kuuv..."; // Replace with your actual API Key
const URL_TO_SCAN = "https://google.com";

/**
 * Scans a URL using Server-Sent Events (SSE) via Fetch API
 * @param {string} url - The target URL to scan
 * @param {string} lang - Language for the response (default: "en")
 */
async function scanUrl(url, lang = "en") {
  const endpoint = new URL('/api/v1/scan-url', API_BASE_URL);
  endpoint.searchParams.set('url', url);
  endpoint.searchParams.set('lang', lang);

  try {
    // Node.js 18+ has native fetch built-in
    const response = await fetch(endpoint.toString(), {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Accept': 'text/event-stream',
      },
    });

    if (!response.ok) {
      console.error(`[Error] Status: ${response.status} ${response.statusText}`);
      const errorText = await response.text();
      console.error("[Detail]:", errorText);
      return;
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let currentEvent = null;

    console.log(">>> Connected to Stream (CommonJS Mode)\n");

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');

      for (const line of lines) {
        const trimmedLine = line.trim();
        if (!trimmedLine) continue;

        if (trimmedLine.startsWith('event:')) {
          currentEvent = trimmedLine.replace('event:', '').trim();
          continue;
        }

        if (trimmedLine.startsWith('data:')) {
          const rawData = trimmedLine.replace('data:', '').trim();

          switch (currentEvent) {
            case 'progress':
              console.log("[progress]", rawData);
              break;
            case 'heartbeat':
              console.log("[heartbeat] ❤️");
              break;
            case 'result':
              try {
                const parsed = JSON.parse(rawData);
                console.log("\n✅ [RESULT]:", JSON.stringify(parsed, null, 2));
              } catch {
                console.log("\n✅ [RESULT raw]:", rawData);
              }
              break;
            case 'error':
              console.error("❌ [event error]:", rawData);
              break;
            default:
              console.log(`[${currentEvent || 'message'}]`, rawData);
          }
          currentEvent = null;
        }
      }
    }
    console.log("\n>>> Stream Closed");

  } catch (err) {
    console.error("!!! Execution Error:", err);
  }
}

// Execute the function
scanUrl(URL_TO_SCAN);
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://oten.gitbook.io/oten-trust-support/documentation/api-reference/code-samples/node.js-fetch-no-dependencies.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
