> ## 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 } from '@glood/hydrogen';

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

### Advanced Usage

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

const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  apps: {
    recommendations: {
      endpoint: 'https://storefront.glood.ai',
      pixel: {
        enabled: true,
        endpoint: 'https://events.glood.ai',
        consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING],
      },
    },
    search: {
      endpoint: 'https://s-s.glood.ai',
      pixel: {
        enabled: true,
        endpoint: 'https://s-pixel.glood.ai',
        consent: [CONSENT_TYPES.ANALYTICS],
      },
    },
    wishlist: {
      endpoint: 'https://w-s.glood.ai',
      pixel: {
        enabled: false,
        endpoint: 'https://w-pixel.glood.ai',
        consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.PREFERENCES],
      },
    },
  },
  debug: process.env.NODE_ENV === 'development',
  settings: {
    customKey: 'customValue',
  },
});
```

### 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' });

// 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') |
| `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;
    search?: SearchAppConfig;
    wishlist?: WishlistAppConfig;
  };
}
```

Each app config has the same structure:

```typescript theme={null}
interface AppConfig {
  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 Configurations

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

```typescript theme={null}
{
  recommendations: {
    endpoint: 'https://storefront.glood.ai',
    pixel: {
      enabled: true,
      endpoint: 'https://events.glood.ai',
      consent: ['analytics', 'marketing'],
    },
  },
  search: {
    endpoint: 'https://s-s.glood.ai',
    pixel: {
      enabled: true,
      endpoint: 'https://s-pixel.glood.ai',
      consent: ['analytics'],
    },
  },
  wishlist: {
    endpoint: 'https://w-s.glood.ai',
    pixel: {
      enabled: true,
      endpoint: 'https://w-pixel.glood.ai',
      consent: ['analytics', 'preferences'],
    },
  },
}
```

## 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, search, wishlist } from '@glood/hydrogen';

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

#### 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', 'search', or 'wishlist')

**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);
}
```

## 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())
  .use(search())
  .use(wishlist());
```

### 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://events.glood.ai',
        consent: ['analytics', 'marketing'],
      },
    },
  },
  debug: isDevelopment,
})
  .use(recommendations())
  .use(search())
  .use(wishlist());
```

### Selective App Usage

Enable only specific apps:

```typescript theme={null}
// Only recommendations and search, no wishlist
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
})
  .use(recommendations())
  .use(search());
  // .use(wishlist()); // Commented out
```

### Custom Pixel Settings

Granular control over pixel tracking:

```typescript theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  apps: {
    recommendations: {
      endpoint: 'https://storefront.glood.ai',
      pixel: {
        enabled: true,
        endpoint: 'https://events.glood.ai',
        consent: ['analytics'], // Only analytics, no marketing
      },
    },
    search: {
      endpoint: 'https://s-s.glood.ai',
      pixel: {
        enabled: true,
        endpoint: 'https://s-pixel.glood.ai',
        consent: ['analytics'],
      },
    },
    wishlist: {
      endpoint: 'https://w-s.glood.ai',
      pixel: {
        enabled: false, // Disable wishlist pixel tracking
        endpoint: 'https://w-pixel.glood.ai',
        consent: ['analytics', 'preferences'],
      },
    },
  },
})
  .use(recommendations())
  .use(search())
  .use(wishlist());
```

## 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())
  .use(search())
  .use(wishlist());
```

## 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(), search(), wishlist()
* [Configuration Guide](/for-developers/glood-hydrogen-sdk/configuration) - Detailed configuration options
* [Types Reference](/for-developers/glood-hydrogen-sdk/api-reference/types) - TypeScript interface definitions
