> ## Documentation Index
> Fetch the complete documentation index at: https://docs.auxia.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Web SDK: Render from Your Own Code

> Fetch treatments with the Auxia Web SDK and render them from your own code, with getTreatments or fetchAndRenderTreatments.

Use these methods when you need fine-grained control over a surface: your page code decides where the treatment goes, and optionally how it is rendered.

<Note>
  Most surfaces don't need this. With [Render from the Auxia Console](/api-reference/sdk/javascript-sdk), `Auxia.initialize()` is the only code on your site. Both approaches use the same script and can run side by side, one per surface, in the same project.
</Note>

***

## Table of Contents

1. [Quick Start](#quick-start)
2. [Installation](#installation)
3. [Initialization](#initialization)
4. [SDK Methods Overview](#sdk-methods-overview)
5. [Method 1: fetchAndRenderTreatments](#method-1-fetchandrendertreatments)
6. [Method 2: getTreatments](#method-2-gettreatments)
7. [Contextual Attributes](#contextual-attributes)
8. [Complete Examples](#complete-examples)
9. [Error Handling](#error-handling)

***

## Quick Start

Here's a minimal example to get Auxia treatments rendering on your page. Each part is explained in detail in the sections that follow.

```html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://auxia.net/interactions/v1/interactions.js"></script>
  <script>
    const auxia = Auxia.initialize({
      apiKey: "YOUR_API_KEY",
      projectId: "YOUR_PROJECT_ID",
      userId: "user@example.com"
    });

    auxia.fetchAndRenderTreatments({
      surfaceRequests: [
        {
          surfaceName: "HOME_PAGE",
          surfaceHtmlElementId: "treatment-container",
          minimumTreatmentCount: 1,
          maximumTreatmentCount: 3
        }
      ],
      languageCode: "en"
    });
  </script>
</head>
<body>
  <div id="treatment-container"></div>
</body>
</html>
```

> **Note:** Don't worry if the code above looks unfamiliar. Each component—installation, initialization, and the SDK methods—is explained step-by-step in the following sections.

***

## Installation

Include the Auxia SDK script in your HTML page:

```html theme={null}
<script src="https://auxia.net/interactions/v1/interactions.js"></script>
```

This script exposes a global `Auxia` object that you use to initialize and interact with the service.

### Prerequisites

Before integrating, ensure you have:

* An **API Key** provided by Auxia
* Your **Project ID** from the Auxia Console
* A configured **Surface** in the Auxia Console (e.g., "HOME\_PAGE", "CHECKOUT\_BANNER")

***

## Initialization

Before calling any SDK methods, you must initialize it with your credentials:

```javascript theme={null}
const auxia = Auxia.initialize({
  apiKey: "YOUR_API_KEY",
  projectId: "YOUR_PROJECT_ID",
  userId: "user@example.com"
});
```

### Configuration Options

| Parameter | Type | Required | Description |
| - | - | - | - |
| `apiKey` | string | Yes | Your Auxia API key |
| `projectId` | string | Yes | Your Auxia project ID |
| `userId` | string | No | Identifier for the current user (can be set later) |

### Updating User ID

If the user ID is not available at initialization (e.g., the user logs in after page load), you can update it later:

```javascript theme={null}
auxia.updateUserId("logged-in-user@example.com");
```

***

## SDK Methods Overview

The Auxia SDK provides **two methods** for fetching treatments:

| Method | Description | Use When |
| - | - | - |
| `fetchAndRenderTreatments()` | Fetches treatments AND automatically renders them to specified DOM elements | You want Auxia to handle both fetching and displaying treatments |
| `getTreatments()` | Fetches treatments only, returns data for you to handle | You need custom rendering logic or want full control over how treatments are displayed |

Both methods accept similar parameters. The key difference is that `fetchAndRenderTreatments()` requires you to specify where to render each treatment, while `getTreatments()` simply returns the treatment data.

***

## Method 1: fetchAndRenderTreatments

Use this method when you want the SDK to both fetch treatments from Auxia and automatically render them into your page. This method returns `Promise<void>` - the treatments are rendered directly to the DOM.

<Info>
  **Renderer Configuration**

  Auxia configures renderers for each surface. Contact your Auxia POC to set up or modify renderers for your surfaces.
</Info>

<Tip>
  **Automatic Interaction Logging**

  When using `fetchAndRenderTreatments`, the SDK automatically handles `logTreatmentInteraction` calls for treatment views, clicks, and dismissals.
</Tip>

### Basic Usage

```javascript theme={null}
auxia.fetchAndRenderTreatments({
  surfaceRequests: [
    {
      surfaceName: "HOME_PAGE",
      surfaceHtmlElementId: "banner-container",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 5
    }
  ],
  languageCode: "en"
});
```

### Request Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `surfaceRequests` | array | Yes | Array of surface request objects (see below) |
| `languageCode` | string | Yes | Language code for treatment content (e.g., "en", "ja", "ko") |
| `contextualAttributes` | array | No | Additional context for personalization (see [Contextual Attributes](#contextual-attributes)) |

### Surface Request Parameters

Each object in the `surfaceRequests` array must include:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `surfaceName` | string | Yes | Name of the surface configured in Auxia Console |
| `surfaceHtmlElementId` | string | Yes | ID of the DOM element where the treatment should be rendered |
| `minimumTreatmentCount` | number | Yes | Minimum number of treatments to return (use 0 if treatments are optional) |
| `maximumTreatmentCount` | number | Yes | Maximum number of treatments to return (must be >= 1) |

> **Note:** For surfaces configured as pop-ups, modals, or slide-ups, the SDK renders the treatment as an **overlay appended to the document body** — not inside the container element you specify via `surfaceHtmlElementId`. This is intentional: overlay treatment types (pop-ups, modals, slide-ups) are designed to appear on top of existing page content regardless of where they are triggered. You can use a placeholder value for `surfaceHtmlElementId` (e.g., `"popup-surface"`) for these surfaces. Contact your Auxia POC to configure overlay renderers or to request that a slide-up render inside a specific container element.

### HTML Setup

Your page must have container elements with IDs matching the `surfaceHtmlElementId` values:

```html theme={null}
<div id="banner-container">
  <!-- Auxia will render treatment content here -->
</div>
```

### Fetching Multiple Surfaces

You can request treatments for multiple surfaces in a single call:

```javascript theme={null}
auxia.fetchAndRenderTreatments({
  surfaceRequests: [
    {
      surfaceName: "HEADER_BANNER",
      surfaceHtmlElementId: "header-banner",
      minimumTreatmentCount: 0,
      maximumTreatmentCount: 1
    },
    {
      surfaceName: "PRODUCT_RECOMMENDATIONS",
      surfaceHtmlElementId: "product-recs",
      minimumTreatmentCount: 3,
      maximumTreatmentCount: 6
    },
    {
      surfaceName: "FOOTER_PROMO",
      surfaceHtmlElementId: "footer-promo",
      minimumTreatmentCount: 0,
      maximumTreatmentCount: 2
    }
  ],
  languageCode: "en"
});
```

With corresponding HTML:

```html theme={null}
<header>
  <div id="header-banner"></div>
</header>

<main>
  <section id="product-recs"></section>
</main>

<footer>
  <div id="footer-promo"></div>
</footer>
```

### Adding Contextual Attributes

You can pass additional context to improve personalization:

```javascript theme={null}
auxia.fetchAndRenderTreatments({
  surfaceRequests: [
    {
      surfaceName: "HOME_PAGE",
      surfaceHtmlElementId: "promo-banner",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 1
    }
  ],
  languageCode: "en",
  contextualAttributes: [
    { key: "userSegment", stringValue: "premium" },
    { key: "cartItemCount", integerValue: 3 },
    { key: "isLoggedIn", boolValue: true }
  ]
});
```

See [Contextual Attributes](#contextual-attributes) for all supported attribute types.

### Complete fetchAndRenderTreatments Example

```html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
  <title>My App</title>
  <script src="https://auxia.net/interactions/v1/interactions.js"></script>
</head>
<body>
  <header>
    <div id="promo-banner"></div>
  </header>

  <main>
    <h1>Welcome</h1>
    <div id="recommendations"></div>
  </main>

  <script>
    const auxia = Auxia.initialize({
      apiKey: "YOUR_API_KEY",
      projectId: "YOUR_PROJECT_ID",
      userId: getUserId()
    });

    auxia.fetchAndRenderTreatments({
      surfaceRequests: [
        {
          surfaceName: "PROMO_BANNER",
          surfaceHtmlElementId: "promo-banner",
          minimumTreatmentCount: 0,
          maximumTreatmentCount: 1
        },
        {
          surfaceName: "RECOMMENDATIONS",
          surfaceHtmlElementId: "recommendations",
          minimumTreatmentCount: 3,
          maximumTreatmentCount: 6
        }
      ],
      languageCode: "en",
      contextualAttributes: [
        { key: "pageType", stringValue: "home" }
      ]
    });
  </script>
</body>
</html>
```

***

## Method 2: getTreatments

Use this method when you need full control over how treatments are rendered. The SDK fetches treatments and returns them as data, allowing you to build your own UI.

<Warning>
  **Manual Interaction Logging Required**

  When using `getTreatments`, you are responsible for calling `logTreatmentInteraction` to track treatment views, clicks, and dismissals. See [Log Treatment Interactions](/api-reference/log-treatment-interactions) for details.
</Warning>

### Basic Usage

```javascript theme={null}
auxia.getTreatments({
  surfaceRequests: [
    {
      surfaceName: "HOME_PAGE",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 5
    }
  ],
  languageCode: "en"
}).then((response) => {
  console.log(response.treatments);
});
```

### Request Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `surfaceRequests` | array | Yes | Array of surface request objects (see below) |
| `languageCode` | string | Yes | Language code for treatment content |
| `contextualAttributes` | array | No | Additional context for personalization |

### Surface Request Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `surfaceName` | string | Yes | Name of the surface configured in Auxia Console |
| `minimumTreatmentCount` | number | Yes | Minimum number of treatments to return |
| `maximumTreatmentCount` | number | Yes | Maximum number of treatments to return (must be >= 1) |

> **Note:** Unlike `fetchAndRenderTreatments`, you do NOT need `surfaceHtmlElementId` since you handle rendering yourself.

### Response Structure

The method returns a Promise that resolves to:

```javascript theme={null}
{
  responseId: "uuid-string",
  treatments: [
    {
      treatmentId: "treatment-123",
      treatmentTrackingId: "tracking-456",
      rank: 1,
      contentLanguageCode: "en",
      treatmentType: "BANNER",
      surface: "HOME_PAGE",
      contentFields: [
        { fieldName: "html", value: "<div>...</div>" },
        { fieldName: "title", value: "Special Offer" },
        { fieldName: "imageUrl", value: "https://..." },
        { fieldName: "ctaText", value: "Learn More" },
        { fieldName: "ctaUrl", value: "https://..." }
      ]
    }
  ]
}
```

### Treatment Object Properties

| Property | Type | Description |
| - | - | - |
| `treatmentId` | string | Unique identifier for the treatment |
| `treatmentTrackingId` | string | Tracking identifier for analytics |
| `rank` | number | Treatment ranking/position |
| `contentLanguageCode` | string | Language of the treatment content |
| `treatmentType` | string | Type of treatment (configured in Auxia Console) |
| `surface` | string | Surface name the treatment belongs to |
| `contentFields` | array | Array of content field objects |

### Content Fields

Each treatment contains `contentFields`—an array of name-value pairs configured in the Auxia Console. Common fields include:

| Field Name | Description |
| - | - |
| `html` | HTML content to render |
| `title` | Treatment title |
| `description` | Treatment description |
| `imageUrl` | Image URL |
| `ctaText` | Call-to-action button text |
| `ctaUrl` | Call-to-action destination URL |

### Working with Content Fields

```javascript theme={null}
auxia.getTreatments({
  surfaceRequests: [
    {
      surfaceName: "PRODUCT_CARDS",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 4
    }
  ],
  languageCode: "en"
}).then((response) => {
  response.treatments.forEach((treatment) => {
    // Get specific fields
    const title = treatment.contentFields.find(f => f.fieldName === "title")?.value;
    const imageUrl = treatment.contentFields.find(f => f.fieldName === "imageUrl")?.value;
    const ctaUrl = treatment.contentFields.find(f => f.fieldName === "ctaUrl")?.value;

    console.log(title, imageUrl, ctaUrl);
  });
});
```

### Custom Rendering Example

```javascript theme={null}
auxia.getTreatments({
  surfaceRequests: [
    {
      surfaceName: "PRODUCT_CARDS",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 4
    }
  ],
  languageCode: "en",
  contextualAttributes: [
    { key: "category", stringValue: "electronics" }
  ]
}).then((response) => {
  const container = document.getElementById("product-grid");

  response.treatments.forEach((treatment) => {
    const title = treatment.contentFields.find(f => f.fieldName === "title")?.value;
    const imageUrl = treatment.contentFields.find(f => f.fieldName === "imageUrl")?.value;
    const ctaUrl = treatment.contentFields.find(f => f.fieldName === "ctaUrl")?.value;
    const ctaText = treatment.contentFields.find(f => f.fieldName === "ctaText")?.value || "Learn More";

    const card = document.createElement("div");
    card.className = "product-card";
    card.innerHTML = `
      <img src="${imageUrl}" alt="${title}">
      <h3>${title}</h3>
      <a href="${ctaUrl}" class="cta-button">${ctaText}</a>
    `;

    container.appendChild(card);

    const logInteraction = (interactionType) => auxia.logTreatmentInteraction({
      treatmentTrackingId: treatment.treatmentTrackingId,
      surfaceName: treatment.surface,
      treatmentId: treatment.treatmentId,
      interactionType
    });

    logInteraction("VIEWED");
    card.querySelector(".cta-button").addEventListener("click", () => logInteraction("CLICKED"));
  });
});
```

With `getTreatments`, recording interactions is up to your code: log `VIEWED` when the treatment is shown, `CLICKED` when it is clicked, and `DISMISSED` when it is closed.

***

## Contextual Attributes

Contextual attributes allow you to pass additional information about the user, session, or page context to improve treatment personalization.

### Supported Attribute Types

| Type | Format | Example |
| - | - | - |
| String | `{ key: "...", stringValue: "..." }` | `{ key: "userSegment", stringValue: "premium" }` |
| Integer | `{ key: "...", integerValue: ... }` | `{ key: "cartItemCount", integerValue: 3 }` |
| Double | `{ key: "...", doubleValue: ... }` | `{ key: "accountBalance", doubleValue: 1500.50 }` |
| Boolean | `{ key: "...", boolValue: ... }` | `{ key: "isFirstVisit", boolValue: true }` |
| Timestamp | `{ key: "...", timestampValue: ... }` | `{ key: "lastPurchaseDate", timestampValue: new Date() }` |
| Timestamp (ms) | `{ key: "...", timestampMillisecondsValue: ... }` | `{ key: "sessionStart", timestampMillisecondsValue: Date.now() }` |

### Common Contextual Attributes

Here are examples of commonly used contextual attributes:

| Attribute | Type | Description |
| - | - | - |
| `userSegment` | string | User tier or segment (e.g., "premium", "basic") |
| `pageType` | string | Current page type (e.g., "home", "product", "checkout") |
| `cartValue` | double | Current cart value |
| `cartItemCount` | integer | Number of items in cart |
| `isLoggedIn` | boolean | Whether user is authenticated |
| `daysSinceLastPurchase` | integer | Days since user's last purchase |
| `deviceType` | string | Device type (e.g., "mobile", "desktop") |
| `productCategory` | string | Current product category being viewed |

### Usage Example

```javascript theme={null}
auxia.fetchAndRenderTreatments({
  surfaceRequests: [
    {
      surfaceName: "CHECKOUT_UPSELL",
      surfaceHtmlElementId: "upsell-container",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 3
    }
  ],
  languageCode: "en",
  contextualAttributes: [
    { key: "userSegment", stringValue: "premium" },
    { key: "cartValue", doubleValue: 150.00 },
    { key: "cartItemCount", integerValue: 3 },
    { key: "isLoggedIn", boolValue: true },
    { key: "productCategory", stringValue: "electronics" }
  ]
});
```

***

## Complete Examples

<Accordion title="Example 1: Basic Page with Banner" defaultOpen>
  ```html theme={null}
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>My Store</title>
    <script src="https://auxia.net/interactions/v1/interactions.js"></script>
  </head>
  <body>
    <header>
      <div id="promo-banner"></div>
    </header>

    <main>
      <h1>Welcome to My Store</h1>
    </main>

    <script>
      const auxia = Auxia.initialize({
        apiKey: "YOUR_API_KEY",
        projectId: "YOUR_PROJECT_ID",
        userId: "user@example.com"
      });

      auxia.fetchAndRenderTreatments({
        surfaceRequests: [
          {
            surfaceName: "PROMO_BANNER",
            surfaceHtmlElementId: "promo-banner",
            minimumTreatmentCount: 0,
            maximumTreatmentCount: 1
          }
        ],
        languageCode: "en"
      });
    </script>
  </body>
  </html>
  ```
</Accordion>

<Accordion title="Example 2: User Authentication Flow">
  ```html theme={null}
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>My App</title>
    <script src="https://auxia.net/interactions/v1/interactions.js"></script>
  </head>
  <body>
    <div id="welcome-banner"></div>
    <div id="personalized-offers"></div>

    <script>
      // Initialize without user ID for anonymous visitors
      const auxia = Auxia.initialize({
        apiKey: "YOUR_API_KEY",
        projectId: "YOUR_PROJECT_ID"
      });

      // Show generic banner for anonymous users
      auxia.fetchAndRenderTreatments({
        surfaceRequests: [
          {
            surfaceName: "WELCOME_BANNER",
            surfaceHtmlElementId: "welcome-banner",
            minimumTreatmentCount: 1,
            maximumTreatmentCount: 1
          }
        ],
        languageCode: "en"
      });

      // When user logs in, update user ID and fetch personalized content
      function onUserLogin(user) {
        auxia.updateUserId(user.email);

        auxia.fetchAndRenderTreatments({
          surfaceRequests: [
            {
              surfaceName: "PERSONALIZED_OFFERS",
              surfaceHtmlElementId: "personalized-offers",
              minimumTreatmentCount: 1,
              maximumTreatmentCount: 5
            }
          ],
          languageCode: "en",
          contextualAttributes: [
            { key: "membershipTier", stringValue: user.tier },
            { key: "accountAgeDays", integerValue: user.accountAgeDays }
          ]
        });
      }
    </script>
  </body>
  </html>
  ```
</Accordion>

<Accordion title="Example 3: Custom Rendering with getTreatments">
  ```html theme={null}
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Product Recommendations</title>
    <script src="https://auxia.net/interactions/v1/interactions.js"></script>
    <style>
      .product-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; }
      .product-card { border: 1px solid #ddd; padding: 15px; text-align: center; }
      .product-card img { max-width: 100%; }
      .cta-button { display: inline-block; padding: 10px 20px; background: #007bff; color: white; text-decoration: none; }
    </style>
  </head>
  <body>
    <h1>Recommended For You</h1>
    <div id="product-grid" class="product-grid"></div>

    <script>
      const auxia = Auxia.initialize({
        apiKey: "YOUR_API_KEY",
        projectId: "YOUR_PROJECT_ID",
        userId: "user@example.com"
      });

      auxia.getTreatments({
        surfaceRequests: [
          {
            surfaceName: "PRODUCT_RECOMMENDATIONS",
            minimumTreatmentCount: 1,
            maximumTreatmentCount: 4
          }
        ],
        languageCode: "en",
        contextualAttributes: [
          { key: "pageType", stringValue: "home" }
        ]
      }).then((response) => {
        const container = document.getElementById("product-grid");

        response.treatments.forEach((treatment) => {
          const title = treatment.contentFields.find(f => f.fieldName === "title")?.value || "";
          const imageUrl = treatment.contentFields.find(f => f.fieldName === "imageUrl")?.value || "";
          const ctaUrl = treatment.contentFields.find(f => f.fieldName === "ctaUrl")?.value || "#";
          const ctaText = treatment.contentFields.find(f => f.fieldName === "ctaText")?.value || "View";

          const card = document.createElement("div");
          card.className = "product-card";
          card.innerHTML = `
            <img src="${imageUrl}" alt="${title}">
            <h3>${title}</h3>
            <a href="${ctaUrl}" class="cta-button">${ctaText}</a>
          `;

          container.appendChild(card);
        });
      });
    </script>
  </body>
  </html>
  ```
</Accordion>

***

## Error Handling

Error handling is managed by the Auxia SDK. Contact your Auxia POC for more details on error handling behavior and configurations.
