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

# Utilities

> Utility functions for consent management, session bootstrap, the pixel queue, and constants

# Utilities

The SDK exports a small set of utilities for advanced usage: consent management, session bootstrap, the pixel queue, and shared constants.

## Consent Management

### checkConsent()

Checks if all required consent types have been granted by the customer.

```typescript theme={null}
function checkConsent(
  requiredConsents: ConsentType[],
  canTrack: any,
  analytics: any
): boolean
```

**Parameters:**

* `requiredConsents` - Array of consent types that must be granted
* `canTrack` - Hydrogen's canTrack function from analytics
* `analytics` - Hydrogen's analytics instance

**Returns:** `true` if all required consents are granted, `false` otherwise

**Usage:**

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

// Check if analytics consent is granted
const canSendAnalytics = checkConsent(
  [CONSENT_TYPES.ANALYTICS],
  canTrack,
  analytics
);

// Check multiple consent types
const canSendMarketing = checkConsent(
  [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING],
  canTrack,
  analytics
);

if (canSendAnalytics) {
  // Send analytics pixel
}
```

**Implementation Details:**

```typescript theme={null}
export function checkConsent(
  requiredConsents: ConsentType[],
  canTrack: any,
  analytics: any
): boolean {
  if (!requiredConsents || requiredConsents.length === 0) {
    return true; // No consent required
  }

  return requiredConsents.every(consentType => {
    switch (consentType) {
      case 'analytics':
        return analytics.customerPrivacy?.analyticsProcessingAllowed();
      case 'marketing':
        return analytics.customerPrivacy?.marketingAllowed();
      case 'preferences':
        return analytics.customerPrivacy?.preferencesProcessingAllowed();
      case 'sale_of_data':
        return analytics.customerPrivacy?.saleOfDataAllowed();
      default:
        return false;
    }
  });
}
```

## Session Bootstrap

### runHeadlessInit()

Bootstraps a session for a Glood client. Called automatically by `GloodProvider` on mount, but exposed for advanced use (e.g. running init yourself in a route loader).

```typescript theme={null}
function runHeadlessInit(client: GloodClient): Promise<InitResponse | null>
```

**Parameters:**

* `client` - The `GloodClient` created by `createGlood(...).use(recommendations())`

**Returns:** The `/v3/headless/init` response (`InitResponse`), or `null` for **v2** clients (init is a v3-only endpoint, so it is a no-op there).

For a **v3** client it calls `POST /api/storefront/v3/headless/init`, which:

* replays the persisted visitor id and returns/echoes `user_id` (persisted to the `_glood_user_id` cookie so returning visitors are recognized),
* creates a per-visit `visit_id` (`_glood_visit_id`, a session cookie),
* returns `visitor` history (browsed / cart / purchased), shop `config`, and the storefront `token`.

**Usage:**

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

const init = await runHeadlessInit(glood);

if (init) {
  console.log('Visit id:', init.visit_id);
  console.log('User id:', init.user_id);
  console.log('Browsed products:', init.visitor.browsed_products);
}
// init is null for a version: 2 client
```

It also saves the response on the client, so after it runs you can read it back synchronously with `client.getInitData()` (and reactively with `useGloodInit()`) — no need to hold the return value yourself.

<Note>
  Inside components, prefer the `useGloodInit()` hook, which returns the same `InitResponse` (or `null` until it resolves / for v2 clients) without re-running init. `GloodProvider` already calls `runHeadlessInit` for you on mount — call it directly only for manual/SSR bootstrap.
</Note>

## Constants

### DEFAULT\_ENDPOINTS

Default API and pixel endpoints for the recommendations app.

```typescript theme={null}
const DEFAULT_ENDPOINTS = {
  recommendations: {
    main: 'https://storefront.glood.ai',
    pixel: 'https://events.glood.ai/api/storefront/event',
  },
} as const;
```

<Note>
  `recommendations.pixel` is **legacy** and no longer used to route events.
  Events are sent off the `main` endpoint by the client's `version`
  (v3 → `/api/storefront/v3/headless/events`).
</Note>

**Usage:**

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

// Get recommendations endpoints
const recEndpoint = DEFAULT_ENDPOINTS.recommendations.main;
const recPixel = DEFAULT_ENDPOINTS.recommendations.pixel;

// Use in custom configuration
const customConfig = {
  endpoint: DEFAULT_ENDPOINTS.recommendations.main,
  pixel: {
    enabled: true,
    endpoint: DEFAULT_ENDPOINTS.recommendations.pixel,
    consent: ['analytics', 'marketing'],
  },
};
```

### DEFAULT\_PIXEL\_CONFIG

Default pixel configuration settings.

```typescript theme={null}
const DEFAULT_PIXEL_CONFIG = {
  enabled: true,
} as const;
```

### CONSENT\_TYPES

Constants for all consent types.

```typescript theme={null}
const CONSENT_TYPES = {
  ANALYTICS: 'analytics',
  MARKETING: 'marketing',
  PREFERENCES: 'preferences',
  SALE_OF_DATA: 'sale_of_data',
} as const;
```

**Usage:**

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

// Use in configuration
const pixelConfig = {
  enabled: true,
  endpoint: 'https://storefront.glood.ai',
  consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING],
};

// Type-safe consent checking
const requiredConsents = [
  CONSENT_TYPES.ANALYTICS,
  CONSENT_TYPES.PREFERENCES,
];
```

### DEFAULT\_PIXEL\_CONSENT

Default consent requirements for the recommendations app.

```typescript theme={null}
const DEFAULT_PIXEL_CONSENT = {
  recommendations: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING],
} as const;
```

**Usage:**

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

// Get default consent for the recommendations app
const recConsent = DEFAULT_PIXEL_CONSENT.recommendations;
// ['analytics', 'marketing']

// Use in custom configuration
const customConfig = {
  endpoint: 'https://custom-storefront.glood.ai',
  pixel: {
    enabled: true,
    endpoint: 'https://custom-storefront.glood.ai',
    consent: DEFAULT_PIXEL_CONSENT.recommendations, // ['analytics', 'marketing']
  },
};
```

### API\_VERSIONS / DEFAULT\_API\_VERSION

Supported headless API versions and the default used when `version` is omitted from `createGlood`.

```typescript theme={null}
const API_VERSIONS = [2, 3] as const;
const DEFAULT_API_VERSION = 3 as const;
```

**Usage:**

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

// Validate a version before passing it to createGlood
function isValidVersion(v: number): boolean {
  return API_VERSIONS.includes(v as any);
}

console.log('Default version:', DEFAULT_API_VERSION); // 3
```

### PAGE\_TYPES

Page types accepted by the sections API (`getSections` / `useRecommendations`).

```typescript theme={null}
const PAGE_TYPES = [
  'product_page',
  'collection',
  'home',
  'cart',
  'order_confirm',
  'other',
  'blog',
  'ajax_cart',
  '404',
  'checkout',
  'returns',
] as const;
```

## Pixel Queue

### getPixelQueue()

Gets the global pixel queue instance for sending events.

```typescript theme={null}
function getPixelQueue(debug?: boolean): PixelQueue
```

**Parameters:**

* `debug` - Enable debug logging for pixel transmission

**Returns:** PixelQueue instance

**Usage:**

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

const pixelQueue = getPixelQueue(true); // Enable debug mode

// Send a pixel event
pixelQueue.add({
  endpoint: 'https://storefront.glood.ai/api/storefront/v3/headless/events',
  data: {
    event: {
      id: 'evt_123',
      name: 'product_viewed',
      // ... event data
    }
  }
});
```

### resetPixelQueue()

Resets the pixel queue (mainly for testing).

```typescript theme={null}
function resetPixelQueue(): void
```

**Usage:**

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

// Reset queue (typically used in tests)
resetPixelQueue();
```

## Advanced Usage Examples

### Consent Validation

Report exactly which required consents are missing, built on the exported `checkConsent`:

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

function validateConsent(
  requiredConsents: ConsentType[],
  canTrack: any,
  analytics: any
): { valid: boolean; missing: ConsentType[] } {
  const missing: ConsentType[] = [];

  for (const consentType of requiredConsents) {
    if (!checkConsent([consentType], canTrack, analytics)) {
      missing.push(consentType);
    }
  }

  return {
    valid: missing.length === 0,
    missing,
  };
}

// Usage
const validation = validateConsent(
  [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING],
  canTrack,
  analytics
);

if (!validation.valid) {
  console.log('Missing consents:', validation.missing);
}
```

## See Also

* [Event System](/for-developers/glood-hydrogen-sdk/api-reference/event-system) - How utilities are used in event processing
* [Types Reference](/for-developers/glood-hydrogen-sdk/api-reference/types) - TypeScript types for utilities
* [App Modules](/for-developers/glood-hydrogen-sdk/api-reference/app-modules) - How apps use these utilities
* [Components](/for-developers/glood-hydrogen-sdk/api-reference/components) - React components using utilities
