npm package: @glood/hydrogen
Description: Glood SDK for Shopify Hydrogen - React components and hooks for seamless e-commerce integration
Author: Glood Team
Latest version: 0.1.0

# @glood/hydrogen

[![npm version](https://img.shields.io/npm/v/@glood/hydrogen.svg)](https://www.npmjs.com/package/@glood/hydrogen)
[![Build Status](https://github.com/LoopClub/glood-hydrogen/workflows/CI/badge.svg)](https://github.com/LoopClub/glood-hydrogen/actions)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Glood SDK for Shopify Hydrogen - React components and hooks for seamless e-commerce integration.

## Features

🚀 **Hydrogen-Optimized** - Built specifically for Shopify Hydrogen framework
🎯 **TypeScript First** - Full type safety with excellent developer experience
⚡ **Performance Focused** - Tree-shakeable exports and optimized for SSR
🔧 **Developer Friendly** - Minimal configuration with sensible defaults
📦 **Lightweight** - Small bundle size with no unnecessary dependencies

## Installation

```bash
npm install @glood/hydrogen
# or
yarn add @glood/hydrogen
# or
pnpm add @glood/hydrogen
```

## Quick Start

### 1. Install Environment Variables

Add your Glood API key to your environment variables:

```bash
# .env
GLOOD_API_KEY=your_glood_api_key_here
```

### 2. Configure the Glood Client

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

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

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:
- ✅ Tracks user interactions via Shopify Analytics
- ✅ Sends pixel events to Glood endpoints
- ✅ Respects customer privacy settings
- ✅ Provides debug logging in development

## Configuration Fields

### Required Fields

| Field | Type | Description |
|-------|------|-------------|
| `apiKey` | `string` | Your Glood API key for authentication |
| `myShopifyDomain` | `string` | Your Shopify store domain (e.g., 'my-store.myshopify.com') |

### Basic Configuration

For most use cases, you only need these two fields:

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

The SDK will automatically use default endpoints and enable pixel tracking for all apps.

## Advanced Configuration

For advanced use cases, you can customize endpoints and pixel settings:

### Advanced Fields

| Field | Type | Description |
|-------|------|-------------|
| `apps` | `object` | Custom configuration for each app module |
| `debug` | `boolean` | Enable debug logging in development |

### App Configuration

Each app in the `apps` object can be configured with:

| Field | Type | Description |
|-------|------|-------------|
| `endpoint` | `string` | Main endpoint for app features and API calls |
| `pixel.enabled` | `boolean` | Enable/disable pixel tracking for this app |
| `pixel.endpoint` | `string` | Endpoint for sending pixel tracking events |
| `pixel.consent` | `ConsentType[]` | Required consent types for sending pixel events |

### Advanced Usage Example

```tsx
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', '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 pixel tracking for wishlist
        endpoint: 'https://w-pixel.glood.ai',
        consent: ['analytics', 'preferences'],
      },
    },
  },
  debug: process.env.NODE_ENV === 'development',
})
  .use(recommendations())
  .use(search())
  .use(wishlist());
```

### Default Endpoints

When using basic configuration, these endpoints are used automatically:

#### Recommendations
- **Main**: `https://storefront.glood.ai` - Product recommendations and storefront features
- **Pixel**: `https://events.glood.ai` - Analytics events tracking

#### Search
- **Main**: `https://s-s.glood.ai` - Search functionality and API
- **Pixel**: `https://s-pixel.glood.ai` - Search analytics tracking

#### Wishlist
- **Main**: `https://w-s.glood.ai` - Wishlist management features
- **Pixel**: `https://w-pixel.glood.ai` - Wishlist analytics tracking

## Where to Add the Provider

The `GloodProvider` must be added to your **root layout file** (`app/root.tsx`) and should:

1. **Be wrapped inside Shopify's `<Analytics>` component** - This ensures proper integration with Hydrogen's analytics system
2. **Wrap your entire application routes** - Usually around `<Outlet />`
3. **Be placed at the root level** - So all routes have access to Glood functionality
4. **Receive loaderData prop** - This provides apps access to Hydrogen's loader data for enhanced functionality

### Why loaderData is Required

The `loaderData` prop is **mandatory** and enables Glood apps to:
- Access route-specific data from Hydrogen loaders
- Enhance analytics events with additional context
- Provide personalized recommendations based on current page data
- Optimize search results using page context

Always pass the result of `useLoaderData()` to the `GloodProvider`:

### ❌ Incorrect Placement
```tsx
// DON'T do this - missing Analytics wrapper and loaderData
export default function App() {
  return (
    <GloodProvider client={glood}>
      <Outlet />
    </GloodProvider>
  );
}
```

### ✅ Correct Placement
```tsx
// DO this - properly wrapped in Analytics with loaderData
import { Analytics } from '@shopify/hydrogen';
import { useLoaderData } from 'react-router';

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

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

## Pixel Events

The SDK automatically tracks user interactions through Shopify's Analytics system and sends pixel events to Glood endpoints. **No manual event tracking is required.**

### How Pixel Tracking Works

1. **Automatic Subscription**: `GloodProvider` subscribes to Shopify Analytics events
2. **Event Filtering**: Events are filtered based on your app configuration
3. **Pixel Transmission**: Relevant events are sent to enabled pixel endpoints
4. **Consent Handling**: Respects Shopify's Customer Privacy API automatically

### Tracked Events

| Event | Triggered When | Sent To |
|-------|---------------|---------|
| `page_viewed` | User navigates to any page | All enabled pixel endpoints |
| `product_viewed` | User views a product page | Recommendations pixel (if enabled) |
| `search_viewed` | User performs a search | Search pixel (if enabled) |
| `collection_viewed` | User views a collection | Recommendations pixel (if enabled) |
| `cart_viewed` | User views their cart | All enabled pixel endpoints |

### Controlling Pixel Tracking

You can enable or disable pixel tracking per app:

```tsx
// Basic configuration - pixel tracking enabled by default
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
})
  .use(recommendations())
  .use(search())
  .use(wishlist());

// Advanced configuration - custom pixel settings
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  apps: {
    recommendations: {
      endpoint: 'https://storefront.glood.ai',
      pixel: {
        enabled: true,  // ✅ Pixel events will be sent
        endpoint: 'https://events.glood.ai',
      },
    },
    wishlist: {
      endpoint: 'https://w-s.glood.ai',
      pixel: {
        enabled: false, // ❌ No pixel events sent
        endpoint: 'https://w-pixel.glood.ai',
      },
    },
  },
})
  .use(recommendations())
  .use(wishlist()); // Note: search not included
```

### Privacy and Consent

The SDK provides granular consent control per app to ensure privacy compliance:

#### Default Consent Requirements

In basic configuration, these consent requirements are used automatically:

- **Recommendations**: `['analytics', 'marketing']` - Analytics processing and marketing consent
- **Search**: `['analytics']` - Only analytics consent required
- **Wishlist**: `['analytics', 'preferences']` - Analytics and preferences consent

#### Custom Consent Configuration

You can customize consent requirements for each app:

```tsx
import { 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',
        // Only analytics consent required (minimal privacy impact)
        consent: [CONSENT_TYPES.ANALYTICS],
      },
    },
    search: {
      endpoint: 'https://s-s.glood.ai',
      pixel: {
        enabled: true,
        endpoint: 'https://s-pixel.glood.ai',
        // Analytics + preferences (for search personalization)
        consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.PREFERENCES],
      },
    },
    wishlist: {
      endpoint: 'https://w-s.glood.ai',
      pixel: {
        enabled: true,
        endpoint: 'https://w-pixel.glood.ai',
        // Strictest privacy requirements
        consent: [
          CONSENT_TYPES.ANALYTICS,
          CONSENT_TYPES.MARKETING,
          CONSENT_TYPES.PREFERENCES,
          CONSENT_TYPES.SALE_OF_DATA,
        ],
      },
    },
  },
})
  .use(recommendations())
  .use(search())
  .use(wishlist());
```

#### Available Consent Types

```tsx
import { CONSENT_TYPES } from '@glood/hydrogen';

// Available consent constants:
CONSENT_TYPES.ANALYTICS        // 'analytics' - Basic analytics processing
CONSENT_TYPES.MARKETING        // 'marketing' - Marketing and advertising
CONSENT_TYPES.PREFERENCES      // 'preferences' - User preferences and personalization
CONSENT_TYPES.SALE_OF_DATA     // 'sale_of_data' - Data selling to third parties
```

#### How Consent Works

1. **User visits site** and sees Shopify cookie 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

#### Example Consent Scenarios

| User Consents | Recommendations Events | Search Events | Wishlist Events |
|---------------|----------------------|---------------|-----------------|
| None | ❌ Not sent | ❌ Not sent | ❌ Not sent |
| Analytics only | ✅ Sent (needs analytics) | ❌ Not sent (needs preferences) | ❌ Not sent (needs marketing+) |
| Analytics + Preferences | ✅ Sent | ✅ Sent | ❌ Not sent (needs marketing+) |
| All consents | ✅ Sent | ✅ Sent | ✅ Sent |

#### Privacy Benefits

- **Privacy-conscious users** can still use basic features without full tracking
- **Different apps** can have different privacy requirements based on their functionality
- **Compliant** with GDPR, CCPA, and other privacy laws
- **Automatic consent checking** - no manual implementation needed
- **GDPR Compliant**: Works seamlessly with Shopify's privacy framework

### Debug Mode

Enable debug mode to see pixel events in the console during development:

```tsx
// Basic configuration with debug
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  debug: process.env.NODE_ENV === 'development', // Enable in development
});

// Advanced configuration with debug
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com',
  apps: { /* ... */ },
  debug: true, // Always enabled
});
```

When debug mode is enabled, you'll see console logs like:
```
[Glood Debug] Product viewed: { productId: '123', productTitle: 'Cool T-Shirt', ... }
[Glood Debug] Sending pixel event to: https://events.glood.ai
```

## API Reference

### Core Functions

- `createGlood(config)` - Create and configure the Glood client
- `GloodProvider` - React context provider component

### App Modules

- `recommendations()` - Enable product recommendations functionality
- `search()` - Enable search functionality
- `wishlist()` - Enable wishlist functionality

### TypeScript Types

```tsx
// Basic configuration interface
interface GloodConfig {
  apiKey: string;
  myShopifyDomain: string;
  debug?: boolean;
}

// Advanced configuration interface
interface GloodAdvancedConfig extends GloodConfig {
  apps?: {
    recommendations?: {
      endpoint: string;
      pixel: {
        enabled: boolean;
        endpoint: string;
        consent: ConsentType[];
      };
    };
    search?: {
      endpoint: string;
      pixel: {
        enabled: boolean;
        endpoint: string;
        consent: ConsentType[];
      };
    };
    wishlist?: {
      endpoint: string;
      pixel: {
        enabled: boolean;
        endpoint: string;
        consent: ConsentType[];
      };
    };
  };
}

// Consent types
type ConsentType = 'analytics' | 'marketing' | 'preferences' | 'sale_of_data';
```

## Complete Usage Example

Here's a full working example showing how to integrate Glood into your Hydrogen app:

### Environment Setup
```bash
# .env
GLOOD_API_KEY=your_actual_glood_api_key
```

### Root Layout (app/root.tsx)
```tsx
import {
  Links,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from '@remix-run/react';
import { Analytics } from '@shopify/hydrogen';
import { GloodProvider, createGlood } from '@glood/hydrogen';
import { recommendations } from '@glood/hydrogen/recommendations';
import { search } from '@glood/hydrogen/search';
import { wishlist } from '@glood/hydrogen/wishlist';
import { useLoaderData } from 'react-router';

// Simple Glood configuration - uses default endpoints
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: 'your-store.myshopify.com', // Replace with your domain
})
  .use(recommendations())
  .use(search())
  .use(wishlist());

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

  return (
    <html>
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        <Analytics>
          <GloodProvider client={glood} loaderData={loaderData}>
            <Outlet />
          </GloodProvider>
        </Analytics>
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}
```

### What This Setup Provides

✅ **Automatic Event Tracking**: All user interactions are tracked automatically
✅ **Privacy Compliant**: Respects customer consent preferences
✅ **Debug Logging**: Console logs in development to verify events
✅ **Modular Apps**: Only enabled apps will receive and process events
✅ **TypeScript Support**: Full type safety and IntelliSense

### Verification

After setup, open your browser's developer console in development mode. You should see:

```
[Glood Debug] Page viewed: { url: '/products/cool-shirt', title: 'Cool Shirt', ... }
[Glood Debug] Product viewed: { productId: 'gid://shopify/Product/123', ... }
```

## Examples

Check out the [examples](./examples/) directory for implementation examples:

- [Basic Integration](./examples/basic/) - Simple setup with default configuration
- [Advanced Configuration](./examples/advanced/) - Custom endpoints, selective apps, environment-specific setups
- [Custom Consent](./examples/advanced/custom-consent.tsx) - Per-app consent requirements for privacy compliance
- [TypeScript Definitions](./examples/types/) - Full type definitions and usage

## Development

```bash
# Install dependencies
npm install

# Start development server
npm run dev

# Run tests
npm test

# Build for production
npm run build

# Type checking
npm run typecheck

# Linting
npm run lint
```

## Requirements

- Node.js 18+
- React 18+
- Shopify Hydrogen 2024.0.0+

## Contributing

We welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for details.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.

## Support

- 📖 [Documentation](./docs/)
- 💬 [GitHub Discussions](https://github.com/LoopClub/glood-hydrogen/discussions)
- 🐛 [Issues](https://github.com/LoopClub/glood-hydrogen/issues)

---

Built with ❤️ by the Glood Team