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

# CDN Installation

> Install the Moss SDK via CDN for non-React applications or simple script tag integration, similar to Intercom's installation method.

# CDN Installation Guide

The Moss SDK supports CDN installation for applications that don't use React or prefer a simple script tag approach. This method automatically configures the SDK using your application settings from the Moss Dashboard.

## Prerequisites

* A registered application in the [Moss Dashboard](https://dashboard.moss.ai)
* Your Application ID (UUID format)
* A website where you want to install the SDK

## 🚀 Quick Start

### Basic Installation

The simplest way to get started is with a single script tag:

```html theme={null}
<!-- Replace YOUR_APP_ID with your actual Application ID -->
<script src="https://cdn.moss.ai/moss-sdk@latest?applicationId=YOUR_APP_ID"></script>
```

### Installation with User ID

For logged-in users, include the userId directly in the script URL:

```html theme={null}
<!-- Include userId parameter for immediate user identification -->
<script src="https://cdn.moss.ai/moss-sdk@latest?applicationId=YOUR_APP_ID&userId=user123"></script>
```

### All-in-One Installation

```html theme={null}
<!-- Everything configured in the script tag -->
<script src="https://cdn.moss.ai/moss-sdk@latest?applicationId=YOUR_APP_ID&userId=user123" 
        data-api-base="https://your-api.example.com"></script>
```

The SDK will:

* ✅ Automatically fetch configuration from your dashboard
* ✅ Use the provided user ID or generate anonymous one
* ✅ Display the floating assistant button
* ✅ Handle all initialization automatically

## 📋 Getting Your Application ID

1. **Sign up** at [Moss Dashboard](https://dashboard.moss.ai)
2. **Create a new application** or select an existing one
3. **Copy the Application ID** from your application settings
4. **Configure SDK settings** in the dashboard (optional)

<img src="https://mintlify.s3.us-west-1.amazonaws.com/moss/images/dashboard-app-id.png" alt="Application ID in Dashboard" />

## ⚙️ Configuration Options

### Method 1: Pre-load Configuration

Set `window.mossSettings` before the SDK loads to customize behavior:

```html theme={null}
<script>
  window.mossSettings = {
    // User identification
    userId: "user123",
    
    // UI preferences
    language: "en", // 'en' or 'ko'
    debugMode: false,
    
    // Custom user data
    configuration: {
      userName: "John Doe",
      userEmail: "john@example.com",
      userRole: "admin"
    }
  };
</script>

<!-- Load SDK after configuration -->
<script src="https://cdn.moss.ai/moss-sdk@latest?applicationId=YOUR_APP_ID"></script>
```

### Method 2: Page Sanitization

Configure how the SDK captures page content for better context accuracy by passing a sanitization function:

```html theme={null}
<script>
  // Define the sanitization function as a const
  const mySanitizationScript = function(document) {
    // Complex XPath-based selection
    const xpath = '//*[@id="root"]/div/div[1]';
    const result = document.evaluate(xpath, document, null, 
                                    XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    if (result.singleNodeValue) {
      result.singleNodeValue.setAttribute('data-clippy-ignore', 'true');
    }
    
    // Dynamic content filtering
    document.querySelectorAll('.dynamic-content').forEach(el => {
      if (el.textContent.includes('confidential')) {
        el.setAttribute('data-clippy-ignore', 'true');
      }
    });
    
    // Remove sensitive data attributes
    document.querySelectorAll('[data-user-ssn]').forEach(el => {
      el.removeAttribute('data-user-ssn');
    });
  };

  // Configure Moss SDK and assign the function
  window.mossSettings = {
    pageSanitizationScript: mySanitizationScript
  };
</script>
<script src="https://cdn.moss.ai/moss-sdk@latest?applicationId=YOUR_APP_ID"></script>
```

### Method 3: Custom API Base URL

If you're using a custom backend deployment:

```html theme={null}
<script src="https://cdn.moss.ai/moss-sdk@latest?applicationId=YOUR_APP_ID" 
        data-api-base="https://your-api.example.com"></script>
```

## 🎮 Global API

Once loaded, the SDK exposes a global `MossSDK` object for runtime control:

### User Identification

```javascript theme={null}
// Identify a logged-in user
window.MossSDK.identify("user456", {
  name: "Jane Smith",
  email: "jane@example.com",
  plan: "premium"
});
```

### Runtime Configuration

```javascript theme={null}
// Update configuration at runtime
window.MossSDK.updateConfig({
  debugMode: true,
  language: "ko"
});
```

### Lifecycle Management

```javascript theme={null}
// Manual initialization with custom config
window.MossSDK.boot({
  userId: "new-user",
  debugMode: true
});

// Clean shutdown (useful for logout)
window.MossSDK.shutdown();

// Check SDK status
if (window.MossSDK && window.MossSDK._initialized) {
  console.log("SDK is ready!");
  console.log("Current user:", window.MossSDK._config.userId);
}
```

## 📱 Single Page App Integration

For SPAs, update the SDK when routes or user state changes:

```javascript theme={null}
// On route change
function onRouteChange(newUserId) {
  if (newUserId) {
    window.MossSDK.identify(newUserId);
  }
}

// On user login
function onUserLogin(user) {
  window.MossSDK.identify(user.id, {
    name: user.name,
    email: user.email,
    plan: user.subscription
  });
}

// On user logout
function onUserLogout() {
  window.MossSDK.shutdown();
  // Optionally restart for anonymous users
  window.MossSDK.boot();
}
```

## 🔒 Security & Domain Restrictions

Configure allowed domains in your dashboard to restrict where the SDK can be loaded:

<img src="https://mintlify.s3.us-west-1.amazonaws.com/moss/images/domain-restrictions.png" alt="Domain Restrictions in Dashboard" />

The SDK will automatically check the requesting domain and block unauthorized usage.

## 🆚 CDN vs NPM Installation

| Feature                | CDN Installation         | NPM Installation     |
| ---------------------- | ------------------------ | -------------------- |
| **Setup**              | Single script tag        | npm install + import |
| **Bundle Size**        | \~200KB (self-contained) | \~50KB (peer deps)   |
| **React Required**     | No                       | Yes                  |
| **Auto-configuration** | Yes (from dashboard)     | Manual configuration |
| **Global API**         | Yes                      | No                   |
| **TypeScript Support** | Limited                  | Full                 |
| **Tree Shaking**       | No                       | Yes                  |

## 🚨 Troubleshooting

### SDK Not Loading

1. **Check Network**: Look for failed requests in DevTools Network tab
2. **Verify Application ID**: Ensure it matches your dashboard exactly
3. **Check Domain**: Make sure your domain is whitelisted (if configured)
4. **Console Errors**: Look for JavaScript errors in the browser console

### Configuration Not Applied

1. **Timing**: Ensure `window.mossSettings` is set before the script tag
2. **Validation**: Check console for configuration validation errors
3. **Debug Mode**: Enable debug mode to see detailed logs:
   ```javascript theme={null}
   window.mossSettings = { debugMode: true };
   ```

### User Identification Issues

1. **Call After Load**: Make sure to call `identify()` after SDK initialization
2. **Check Storage**: User IDs are stored in localStorage for persistence
3. **Verify Format**: Ensure user data follows the expected format

## 🔧 Advanced Configuration

### Custom Configuration Fields

You can pass any custom data through the configuration object:

```javascript theme={null}
window.mossSettings = {
  configuration: {
    // Custom application data
    theme: "dark",
    features: ["chat", "voice", "screen-share"],
    apiVersion: "v2",
    
    // User preferences
    notifications: true,
    language: "en-US",
    
    // Business context
    accountType: "enterprise",
    permissions: ["read", "write", "admin"]
  }
};
```

This data will be available to the AI assistant for providing contextual help.

### Error Handling

```javascript theme={null}
// Listen for SDK initialization
window.addEventListener('error', function(e) {
  if (e.filename && e.filename.includes('moss-sdk')) {
    console.error('Moss SDK failed to load:', e.message);
    // Handle SDK load failure
  }
});

// Check initialization after a delay
setTimeout(() => {
  if (!window.MossSDK || !window.MossSDK._initialized) {
    console.warn('Moss SDK did not initialize properly');
    // Show fallback UI or retry
  }
}, 5000);
```

## 📊 Analytics & Monitoring

The SDK automatically tracks:

* Initialization success/failure
* User identification events
* Configuration updates
* Session management
* Error occurrences

Access these metrics through your Moss Dashboard analytics section.

## 🔗 Next Steps

1. **Test Installation**: Use the browser console to verify `window.MossSDK` exists
2. **Customize Settings**: Configure your application in the Moss Dashboard
3. **Test User Flows**: Try the `identify()` and `updateConfig()` methods
4. **Monitor Usage**: Check analytics in your dashboard
5. **Advanced Features**: Explore the full [SDK Reference](/en/sdk-reference/sdk)

## 📚 Related Documentation

* [NPM Installation](/en/installation) - For React applications
* [Quickstart Guide](/en/quickstart) - Getting started with React
* [SDK Reference](/en/sdk-reference/sdk) - Complete API documentation
* [Dashboard Guide](https://docs.moss.ai/dashboard) - Managing your applications
