> ## 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.

# Glood Hydrogen SDK

> Complete guide to integrating Glood with Shopify Hydrogen for e-commerce analytics and personalization

# Glood Hydrogen SDK

The **Glood Hydrogen SDK** is a TypeScript-first library designed specifically for integrating Glood's product recommendations into Shopify Hydrogen storefronts. It provides React components, hooks, and utilities optimized for the Hydrogen framework.

The SDK is **recommendations-focused**: it loads recommendation sections, powers the headless recommendation endpoints, and streams analytics and attribution events back to Glood.

## Key Features

🚀 **Hydrogen-Optimized** - Built specifically for Shopify Hydrogen with SSR support
🛍️ **Recommendations** - Load recommendation sections with full product data via a React hook or SSR loader
📡 **Zero-Config Analytics** - Standard events (page views, add to cart, ...) sent out of the box
🎯 **TypeScript First** - Complete type safety with excellent developer experience
⚡ **Performance Focused** - Tree-shakeable exports and optimized pixel tracking
🔧 **Zero Configuration** - Works out of the box with sensible defaults
🛡️ **Privacy Compliant** - GDPR/CCPA compliant with automatic consent handling
📦 **Lightweight** - Minimal bundle impact with selective imports

## Quick Start

### 1. Installation

```bash theme={null}
npm install @glood/hydrogen
```

### 2. Basic Setup

Add your Glood API key to environment variables:

```bash theme={null}
# .env
GLOOD_API_KEY=your_glood_api_key_here
```

Configure the SDK in your root layout:

```tsx theme={null}
// app/root.tsx
import { Analytics } from '@shopify/hydrogen';
import { GloodProvider, createGlood } from '@glood/hydrogen';
import { recommendations } from '@glood/hydrogen';
import { useLoaderData } from 'react-router';

const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  version: 3, // Headless API version (2 | 3), 3 is the default
})
  .use(recommendations());

export default function App() {
  const loaderData = useLoaderData();

  return (
    <Analytics>
      <GloodProvider client={glood} loaderData={loaderData}>
        <Outlet />
      </GloodProvider>
    </Analytics>
  );
}
```

### 3. That's It! 🎉

No additional setup required. The SDK automatically:

* ✅ Bootstraps a session on load (v3 clients call `POST /api/storefront/v3/headless/init`)
* ✅ Tracks user interactions via Shopify Analytics
* ✅ Sends analytics and attribution events to the versioned events API
* ✅ Respects customer privacy settings
* ✅ Provides debug logging in development

### 4. Load Recommendations

Display the recommendation sections configured in your Glood dashboard:

```tsx theme={null}
import { useRecommendations } from '@glood/hydrogen';

function ProductRecommendations({ productId }) {
  const { sections, loading } = useRecommendations({
    pageType: 'product_page',
    productId,
  });

  if (loading) return null;

  return sections.map((section) => (
    <section key={section.section_serve_id}>
      <h2>{section.title}</h2>
      {section.products.map((product) => (
        <a key={product.product_id} href={`/products/${product.handle}`}>
          {product.title} — {product.price}
        </a>
      ))}
    </section>
  ));
}
```

See [Loading Recommendations](/for-developers/glood-hydrogen-sdk/recommendations) for SSR loaders and attribution tracking.

### Why loaderData is Required

The `loaderData` prop is **mandatory** and enables the Glood recommendations app to:

* **Access route-specific data** from Hydrogen loaders for enhanced context
* **Enhance analytics events** with additional page-specific information
* **Provide personalized recommendations** based on current page data

Always pass the result of `useLoaderData()` to the `GloodProvider` component.

## Architecture Overview

### React Context Integration

The SDK uses React Context to provide the Glood client throughout your application:

```tsx theme={null}
// GloodProvider creates a context with the client
function App() {
  const loaderData = useLoaderData();
  return (
    <GloodProvider client={glood} loaderData={loaderData}>
      <YourApp />
    </GloodProvider>
  );
}

// Access the client anywhere in your component tree
function MyComponent() {
  const client = useGloodAnalytics();
  // Use client for custom integrations
}
```

### Session Init

On mount, `GloodProvider` bootstraps a session for **v3** clients by calling `POST /api/storefront/v3/headless/init`. It replays the persisted visitor id (`_glood_user_id` cookie), creates a per-visit id (`_glood_visit_id`), and returns the visitor's history, shop config, and storefront token. For **v2** clients init is a no-op. The response is exposed via the `useGloodInit()` hook.

### Event Flow

1. **Shopify Analytics** → Automatically tracks user interactions
2. **GloodProvider** → Subscribes to analytics events via `useAnalytics()`
3. **Event Transformation** → Converts Shopify events to the Glood event format
4. **Consent Checking** → Verifies customer privacy permissions
5. **Event Transmission** → Sends events to the versioned events API (v3 → `POST {endpoint}/api/storefront/v3/headless/events`; v2 → `POST {endpoint}/api/storefront/event`)

### App Module

The SDK exposes a single app module:

* **Recommendations** (`recommendations()`) - Product recommendations, personalization, sections, and event tracking

Register it via `.use(recommendations())`. It can be configured with a custom endpoint and pixel settings.

## Configuration Options

### Basic Configuration (Recommended)

```tsx theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  version: 3, // Headless API version (2 | 3), 3 is the default
  debug: process.env.NODE_ENV === 'development', // Optional debug mode
});
```

**Benefits:**

* Zero configuration beyond API key and domain
* Automatic default endpoint for recommendations
* Pixel tracking enabled by default with appropriate consent requirements
* Perfect for getting started quickly

### Advanced Configuration

```tsx theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  version: 3, // 2 | 3, default 3
  apps: {
    recommendations: {
      endpoint: 'https://storefront.glood.ai',
      pixel: {
        enabled: true,
        consent: ['analytics', 'marketing'],
      },
    },
  },
  debug: true,
});
```

<Note>
  Events route off the app's main `endpoint` and the client `version` (v3 → `POST {endpoint}/api/storefront/v3/headless/events`), not off `pixel.endpoint`. There is no separate events host to configure.
</Note>

**Benefits:**

* Custom endpoint URL for different environments
* Granular pixel tracking control
* Custom consent requirements for privacy compliance
* Environment-specific configurations

## Privacy & Compliance

The SDK provides automatic privacy compliance through Shopify's Customer Privacy API:

### Default Consent Requirements

* **Recommendations**: `['analytics', 'marketing']` - Analytics and marketing consent

### How Consent Works

1. User visits site and sees Shopify privacy banner
2. User grants specific consent types through the privacy interface
3. Events are tracked by Shopify Analytics as usual
4. For each event, Glood checks if user has granted **all required consents** for that app
5. Only if all consents are granted, pixel data is sent to Glood

This ensures full GDPR/CCPA compliance without any manual implementation.

## Default Endpoints

When using basic configuration, the recommendations endpoint is used automatically:

### Recommendations

* **Main**: `https://storefront.glood.ai` - Product recommendations API and the full v3 headless suite (init, sections, events, recommendations variants)

The versioned events API lives under this same host: v3 events go to `POST {endpoint}/api/storefront/v3/headless/events` and v2 events go to `POST {endpoint}/api/storefront/event`.

## Content Security Policy Setup

To enable recommendation fetches and event transmission, add the Glood domain to your Content Security Policy:

```javascript theme={null}
const {nonce, header, NonceProvider} = createContentSecurityPolicy({
  shop: {
    checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN,
    storeDomain: context.env.PUBLIC_STORE_DOMAIN,
  },
  connectSrc: [
    "'self'",
    'https://storefront.glood.ai', // v3 headless suite (init, sections, events, recommendations)
  ],
});
```

This whitelists Glood's endpoint so init, sections, recommendations, and event calls can go through. See the [CSP guide](/for-developers/glood-hydrogen-sdk/content-security-policy) for details.

## Debug Mode

Enable debug mode to see detailed logging during development:

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

Debug logs show:

* Event subscriptions setup
* Received analytics events
* Consent checking results
* Pixel transmission status
* Error details

## Next Steps

* [Installation Guide](/for-developers/glood-hydrogen-sdk/installation) - Detailed setup instructions
* [Configuration](/for-developers/glood-hydrogen-sdk/configuration) - Basic and advanced configuration options
* [Loading Recommendations](/for-developers/glood-hydrogen-sdk/recommendations) - Fetch and display recommendation sections
* [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client) - Complete API documentation
* [Examples](/for-developers/glood-hydrogen-sdk/examples/basic-setup) - Implementation examples and patterns
* [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) - CSP configuration guide

## Requirements

* Node.js 18+
* React 18+
* Shopify Hydrogen 2024.10.1+
* TypeScript 5.4+ (recommended)

## Support

* 📖 [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client)
* 💬 [GitHub Discussions](https://github.com/LoopClub/glood-hydrogen/discussions)
* 🐛 [Issues](https://github.com/LoopClub/glood-hydrogen/issues)
