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

# Basic Setup Example

> Complete example of basic Glood Hydrogen SDK setup with minimal configuration

# Basic Setup Example

This example shows how to set up the Glood Hydrogen SDK with minimal configuration for a typical e-commerce store.

## Complete Implementation

### 1. Environment Variables

```bash theme={null}
# .env
GLOOD_API_KEY=your_glood_api_key_here
PUBLIC_STORE_DOMAIN=your-store.myshopify.com
PUBLIC_CHECKOUT_DOMAIN=your-store.myshopify.com
PUBLIC_STOREFRONT_ID=your_storefront_id_here
```

### 2. Create the Glood Client (app/lib/glood.ts)

Create the client once and register the recommendations app. The `apiKey` is a
public storefront token (`gl_sf_*`), so it is safe to ship to the browser.

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

export const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!,
  // Headless API version (2 | 3). 3 is the default and the full suite
  // (init, sections, events, recommendations variants); set explicitly here
  // for clarity. v2 is legacy and only supports recommendations.
  version: 3,
  debug: process.env.NODE_ENV === 'development',
}).use(recommendations());
```

### 3. Root Layout (app/root.tsx)

Wrap your app with `GloodProvider` inside Shopify's `Analytics.Provider` and
pass the root loader data. `GloodProvider` subscribes to Shopify's analytics
events and, on a **v3** client, automatically fires `POST /v3/headless/init`
on mount to bootstrap the session (see below).

```typescript theme={null}
import {
  Outlet,
  Links,
  Meta,
  Scripts,
  ScrollRestoration,
  useRouteLoaderData,
} from 'react-router';
import {
  Analytics,
  getShopAnalytics,
  useNonce,
} from '@shopify/hydrogen';
import { GloodProvider } from '@glood/hydrogen';
import { glood } from '~/lib/glood';

export async function loader({ context }) {
  const { storefront, env, cart } = context;

  return {
    cart: cart.get(),
    shop: getShopAnalytics({
      storefront,
      publicStorefrontId: env.PUBLIC_STOREFRONT_ID,
    }),
    consent: {
      checkoutDomain: env.PUBLIC_CHECKOUT_DOMAIN,
      storefrontAccessToken: env.PUBLIC_STOREFRONT_API_TOKEN,
      withPrivacyBanner: true,
    },
  };
}

export function Layout({ children }) {
  const nonce = useNonce();

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        {children}
        <ScrollRestoration nonce={nonce} />
        <Scripts nonce={nonce} />
      </body>
    </html>
  );
}

export default function App() {
  const data = useRouteLoaderData('root');

  if (!data) {
    return <Outlet />;
  }

  return (
    <Analytics.Provider cart={data.cart} shop={data.shop} consent={data.consent}>
      <GloodProvider client={glood} loaderData={data}>
        <Outlet />
      </GloodProvider>
    </Analytics.Provider>
  );
}
```

<Note>
  `GloodProvider` must render inside Shopify's `Analytics.Provider` so it can
  subscribe to the storefront's analytics events.
</Note>

## What This Setup Provides

### ✅ Automatic Session Init (v3)

On page load, a **v3** client automatically calls
`POST /api/storefront/v3/headless/init` via `GloodProvider`. This bootstrap:

* replays a persisted visitor id and returns/echoes `user_id` (stored in the
  `_glood_user_id` cookie so returning visitors are recognized),
* creates a per-visit `visit_id` (`_glood_visit_id`, a session cookie),
* returns the visitor's `browsed` / `cart` / `purchased` history, shop `config`
  (currency, money format, GraphQL version, integrations, analytics flag) and a
  storefront `token`.

The init response is available anywhere via the `useGloodInit()` hook. For a
**v2** client, init is a no-op (the endpoint is v3-only) and `useGloodInit()`
returns `null`.

### ✅ Automatic Event Tracking

Once wrapped, `GloodProvider` automatically tracks Shopify analytics events
(page views, product views, collection views, cart views, add/remove from
cart) and forwards them to the recommendations app.

### ✅ Default Endpoint

* **Recommendations**: `https://storefront.glood.ai` — the v3 headless suite
  (init, sections, events, recommendations) lives under this endpoint.

### ✅ Debug Logging

In development mode (`debug: true`), you'll see console logs like:

```
[Glood Debug] Registered recommendations app
[Glood Debug] Running headless init: https://storefront.glood.ai/api/storefront/v3/headless/init
[Glood Debug] Setting up centralized subscription for page_viewed
[Glood Debug] Received product_viewed event, distributing to interested apps
[Glood Debug] Consent granted for recommendations, processing event
```

## Testing the Setup

### 1. Verify Installation

Check that the SDK is working by looking for debug logs in the browser console.

### 2. Verify Session Init

On first load, confirm a `POST /api/storefront/v3/headless/init` request
succeeds, and that the `_glood_user_id` and `_glood_visit_id` cookies are set.

### 3. Test Event Tracking

1. **Navigate to a product page** – should see `product_viewed` events
2. **Add item to cart** – should see `product_added_to_cart` events
3. **View cart** – should see `cart_viewed` events

## Customizing the Basic Setup

### Add Custom Settings

```typescript theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!,
  version: 3,
  debug: process.env.NODE_ENV === 'development',
  settings: {
    storeVersion: '2.0',
    customTrackingId: 'custom-123',
  },
}).use(recommendations());
```

### Environment-Specific Debug

```typescript theme={null}
const glood = createGlood({
  apiKey: process.env.GLOOD_API_KEY!,
  myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!,
  debug: process.env.NODE_ENV !== 'production', // Debug in dev and staging
}).use(recommendations());
```

## Using the Glood Client

### Access the Init Response

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

function VisitorHistory() {
  const init = useGloodInit();

  if (!init) return null; // null until init resolves (always null for v2)

  return (
    <div>
      <p>User id: {init.user_id}</p>
      <p>Visit id: {init.visit_id}</p>
      <p>Recently browsed: {init.visitor.browsed_products.length} products</p>
    </div>
  );
}
```

### Access the Client in Components

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

function MyComponent() {
  const glood = useGloodAnalytics();

  if (!glood) {
    return <div>Glood not available</div>;
  }

  const recommendationsApp = glood.getApp('recommendations');

  return (
    <div>
      <p>Debug mode: {glood.debug ? 'On' : 'Off'}</p>
      <p>Recommendations endpoint: {recommendationsApp?.endpoint}</p>
    </div>
  );
}
```

## Common Issues and Solutions

### Issue: No Debug Logs

**Check:**

1. Debug mode is enabled: `debug: true`
2. Browser console is open
3. Events are being triggered (navigate to product pages)

### Issue: CSP Violations

**Check:**

1. `https://storefront.glood.ai` is in `connectSrc` (see
   [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy))
2. CSP headers are being applied correctly
3. No typos in domain names

### Issue: No Network Requests

**Check:**

1. Customer consent is granted (try allowing all cookies)
2. The recommendations app is registered with `.use(recommendations())`
3. `GloodProvider` renders inside `Analytics.Provider`

### Issue: TypeScript Errors

**Solution:**

```bash theme={null}
npm install --save-dev @types/react @types/node
```

## Next Steps

* [Recommendations Example](/for-developers/glood-hydrogen-sdk/examples/recommendations) - Render sections client-side and via SSR
* [Configuration](/for-developers/glood-hydrogen-sdk/configuration) - Version selection, consent, and endpoints
* [Signatures & Parameters](/for-developers/glood-hydrogen-sdk/api-reference/signatures) - Every hook and function at a glance
* [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client) - Complete documentation

## Support

If you need help with the basic setup:

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