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

# Client API

> Complete reference for createGlood() function and GloodClient interface

# Client API

The client API provides the core functionality for creating and configuring your Glood SDK instance.

## createGlood()

Creates a new Glood client instance with the specified configuration.

### Signature

```typescript theme={null}
function createGlood(config: GloodConfig): GloodClient
```

### Parameters

| Parameter | Type          | Required | Description                               |
| --------- | ------------- | -------- | ----------------------------------------- |
| `config`  | `GloodConfig` | Yes      | Configuration object for the Glood client |

### Basic Usage

```typescript theme={null}
import { createGlood, recommendations } from '@glood/hydrogen';

const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
}).use(recommendations());
```

### Advanced Usage

```typescript theme={null}
import { createGlood, recommendations, CONSENT_TYPES } from '@glood/hydrogen';

const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  version: 3, // 2 | 3 — defaults to 3
  apps: {
    recommendations: {
      endpoint: 'https://storefront.glood.ai',
      pixel: {
        enabled: true,
        endpoint: 'https://storefront.glood.ai',
        consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING],
      },
    },
  },
  debug: process.env.NODE_ENV === 'development',
  settings: {
    customKey: 'customValue',
  },
}).use(recommendations());
```

<Note>
  The `version` option selects the headless API version. **Version `3` (default)** is
  the full suite — init, sections, events, and the recommendations variants.
  **Version `2`** is legacy and only supports recommendations, authenticating by shop
  header alone (no bearer token).
</Note>

### Error Handling

The function throws errors for invalid configurations:

```typescript theme={null}
// Throws: "Glood: apiKey is required and must be a non-empty string"
createGlood({ myShopifyDomain: 'store.myshopify.com' });

// Throws: "Glood: myShopifyDomain is required and must be a valid Shopify domain"
createGlood({ apiKey: 'key' });

// Throws when version is not 2 or 3
createGlood({
  apiKey: 'key',
  myShopifyDomain: 'store.myshopify.com',
  version: 4, // ❌ only 2 or 3 are valid
});

// Warns: Domain format doesn't match typical Shopify format
createGlood({
  apiKey: 'key',
  myShopifyDomain: 'custom-domain.com'
});
```

## GloodConfig Interface

Configuration object for creating a Glood client.

### Properties

| Property          | Type                  | Required | Default        | Description                                            |
| ----------------- | --------------------- | -------- | -------------- | ------------------------------------------------------ |
| `apiKey`          | `string`              | Yes      | -              | Your Glood API key for authentication                  |
| `myShopifyDomain` | `string`              | Yes      | -              | Your Shopify domain (e.g., 'store-name.myshopify.com') |
| `version`         | `2 \| 3`              | No       | `3`            | Headless API version. Throws if not 2 or 3.            |
| `apps`            | `object`              | No       | Auto-generated | App-specific configurations                            |
| `debug`           | `boolean`             | No       | `false`        | Enable debug logging                                   |
| `settings`        | `Record<string, any>` | No       | `{}`           | Additional custom settings                             |

### App Configuration

The `apps` property allows per-app customization:

```typescript theme={null}
interface GloodConfig {
  apps?: {
    recommendations?: RecommendationsAppConfig;
  };
}
```

The recommendations app config has this structure:

```typescript theme={null}
interface RecommendationsAppConfig {
  endpoint: string;              // Main API endpoint
  pixel: {
    enabled: boolean;            // Enable/disable pixel tracking
    endpoint: string;            // Pixel tracking endpoint
    consent: ConsentType[];      // Required consent types
  };
  subscribedEvents?: EventType[]; // Events to subscribe to (optional)
}
```

### Default App Configuration

When `apps` is not provided, these defaults are used:

```typescript theme={null}
{
  recommendations: {
    endpoint: 'https://storefront.glood.ai',
    pixel: {
      enabled: true,
      endpoint: 'https://storefront.glood.ai',
      consent: ['analytics', 'marketing'],
    },
  },
}
```

## GloodClient Interface

The client instance returned by `createGlood()`.

### Properties

| Property | Type                     | Description                                  |
| -------- | ------------------------ | -------------------------------------------- |
| `config` | `GloodConfig`            | The configuration used to create this client |
| `debug`  | `boolean`                | Whether debug mode is enabled                |
| `apps`   | `Map<AppName, GloodApp>` | Map of registered app instances              |

### Methods

#### use()

Registers an app module with the client.

```typescript theme={null}
use(appModuleOrFactory: GloodAppModule | ((config?: any) => GloodAppModule)): GloodClient
```

**Parameters:**

* `appModuleOrFactory`: App module function or factory

**Returns:** The client instance (for method chaining)

**Usage:**

```typescript theme={null}
import { recommendations } from '@glood/hydrogen';

const glood = createGlood(config)
  .use(recommendations());
```

#### getEnabledApps()

Returns all registered app instances.

```typescript theme={null}
getEnabledApps(): GloodApp[]
```

**Returns:** Array of enabled app instances

**Usage:**

```typescript theme={null}
const apps = glood.getEnabledApps();
console.log('Enabled apps:', apps.map(app => app.name));
```

#### getApp()

Gets a specific app by name.

```typescript theme={null}
getApp(name: AppName): GloodApp | undefined
```

**Parameters:**

* `name`: App name ('recommendations')

**Returns:** App instance or `undefined` if not found

**Usage:**

```typescript theme={null}
const recommendationsApp = glood.getApp('recommendations');
if (recommendationsApp) {
  console.log('Recommendations endpoint:', recommendationsApp.endpoint);
}
```

#### getInitData()

Reads the `/v3/headless/init` response saved after the page-load session init. This is the synchronous, non-React counterpart to the [`useGloodInit()`](/for-developers/glood-hydrogen-sdk/api-reference/components#usegloodinit) hook.

```typescript theme={null}
getInitData(): InitResponse | null
```

**Returns:** The `InitResponse` once init has resolved, or `null` if init hasn't run yet or the client is configured for `version: 2` (init is v3-only).

**Usage:**

```typescript theme={null}
const session = glood.getInitData();
if (session) {
  console.log('visit:', session.visit_id, 'user:', session.user_id);
  console.log('currency:', session.config?.shop?.currency);
}
```

<Note>
  Read-only for app code. The value is written only by the SDK's page-load init
  flow (`runHeadlessInit`, run automatically by `GloodProvider` for v3 clients).
</Note>

## Configuration Examples

### Basic Setup

Minimal configuration with defaults:

```typescript theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
}).use(recommendations());
```

### Environment-Specific Setup

Different configurations for different environments:

```typescript theme={null}
const isDevelopment = process.env.NODE_ENV === 'development';
const isStaging = process.env.NODE_ENV === 'staging';

const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: process.env.SHOPIFY_DOMAIN!,
  apps: {
    recommendations: {
      endpoint: isDevelopment
        ? 'https://dev-storefront.glood.ai'
        : isStaging
        ? 'https://staging-storefront.glood.ai'
        : 'https://storefront.glood.ai',
      pixel: {
        enabled: !isDevelopment, // Disable pixels in development
        endpoint: 'https://storefront.glood.ai',
        consent: ['analytics', 'marketing'],
      },
    },
  },
  debug: isDevelopment,
}).use(recommendations());
```

### Legacy v2 Setup

Pin the client to the legacy v2 recommendations API:

```typescript theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  version: 2, // legacy — recommendations only
}).use(recommendations());
```

## Error Handling

The client provides comprehensive error handling:

### Validation Errors

```typescript theme={null}
try {
  const glood = createGlood({
    apiKey: '', // Invalid: empty string
    myShopifyDomain: 'invalid-domain',
  });
} catch (error) {
  console.error('Configuration error:', error.message);
  // "Glood: apiKey must be a non-empty string"
}
```

### Runtime Errors

```typescript theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  debug: true, // Enable debug logging
});

// Errors will be logged with full details in debug mode
```

### Domain Validation

```typescript theme={null}
// Valid Shopify domains
createGlood({
  apiKey: 'key',
  myShopifyDomain: 'store.myshopify.com', // ✅ Valid
});

createGlood({
  apiKey: 'key',
  myShopifyDomain: 'store.shopify.com', // ✅ Valid (Shopify Plus)
});

// Warning for non-standard domains
createGlood({
  apiKey: 'key',
  myShopifyDomain: 'custom-domain.com', // ⚠️ Warning logged
});
```

## Best Practices

### 1. Environment Variables

Always use environment variables for sensitive data:

```typescript theme={null}
// ✅ Good
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: process.env.SHOPIFY_DOMAIN!,
});

// ❌ Bad - hardcoded credentials
const glood = createGlood({
  apiKey: 'hardcoded_key',
  myShopifyDomain: 'hardcoded_domain.myshopify.com',
});
```

### 2. Debug Mode

Enable debug mode in development:

```typescript theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: process.env.SHOPIFY_DOMAIN!,
  debug: process.env.NODE_ENV === 'development',
});
```

### 3. Error Handling

Wrap client creation in try-catch for production:

```typescript theme={null}
try {
  const glood = createGlood({
    apiKey: process.env.GLOOD_API_KEY!,
    myShopifyDomain: process.env.SHOPIFY_DOMAIN!,
  });
} catch (error) {
  console.error('Failed to initialize Glood client:', error);
  // Handle gracefully or use fallback
}
```

### 4. Method Chaining

Use method chaining for cleaner code:

```typescript theme={null}
const glood = createGlood(config)
  .use(recommendations());
```

## See Also

* [React Components](/for-developers/glood-hydrogen-sdk/api-reference/components) - GloodProvider and hooks
* [App Modules](/for-developers/glood-hydrogen-sdk/api-reference/app-modules) - recommendations()
* [Configuration Guide](/for-developers/glood-hydrogen-sdk/configuration) - Detailed configuration options
* [Types Reference](/for-developers/glood-hydrogen-sdk/api-reference/types) - TypeScript interface definitions
