npm package: @luminpdf/browser-ga4
Description: Simple Google Analytics 4 (GA4) client with TypeScript support
Latest version: 0.4.0

# @luminpdf/browser-ga4

Minimal Google Analytics 4 client with TypeScript support. Designed to work in both standalone applications and Module Federation environments.

## Features

- **Simple API**: One-step initialization with `await GA4Client.create()`
- **Module Federation Ready**: Works seamlessly as a remote component without conflicts
- **Multiple Measurement IDs**: Supports multiple GA4 properties on the same page
- **Type-Safe**: Full TypeScript support with proper type definitions
- **Auto-enrichment**: Automatically adds common browser attributes to events
- **Event Queueing**: Events are queued before initialization completes
- **No GTM Conflicts**: Uses gtag.js directly, avoiding conflicts with host app's GTM

## Installation

```bash
npm install @luminpdf/browser-ga4
# or
yarn add @luminpdf/browser-ga4
# or
pnpm add @luminpdf/browser-ga4
```

## Basic Usage

```typescript
import { GA4Client } from '@luminpdf/browser-ga4';

// Create and configure in one step (async)
const ga4 = await GA4Client.create({
  measurementId: 'G-XXXXXXXXXX',
});

// Ready to track events immediately
ga4.trackEvent('button_click', { button_name: 'signup' });
ga4.trackEvent('page_view', { page_path: '/dashboard' });
```

**Note:** Calling `GA4Client.create()` with the same measurement ID will return the existing instance, ensuring consistent tracking across your application.

## Module Federation Usage

This package is designed to work in Module Federation environments where the host application may already have its own Google Tag Manager (GTM) container.

```typescript
// Remote component (e.g., lumin-sign-mf)
const ga4 = await GA4Client.create({
  measurementId: 'G-REMOTE-ID', // Remote's GA4 property
  debug: process.env.NODE_ENV === 'development',
});

// Events are sent to the remote's GA4 property
// even if host has its own GTM/GA4 configured
ga4.trackEvent('document_signed', { document_id: '123' });
```

### How It Works

- Uses `gtag.js` directly instead of GTM to avoid container conflicts
- Reuses existing `gtag.js` script if already loaded by host
- Routes events explicitly using `send_to` parameter
- Multiple GA4 properties can coexist on the same page

## Advanced Usage

### Track Events

```typescript
// Page view
ga4.trackEvent('page_view', {
  page_path: '/home',
  page_title: 'Home',
});

// Custom event
ga4.trackEvent('button_click', {
  button_name: 'signup',
  location: 'header',
});

// E-commerce
ga4.trackEvent('purchase', {
  transaction_id: 'T_123',
  value: 99.99,
  currency: 'USD',
  items: [{ item_id: 'SKU_001', item_name: 'Product', price: 99.99 }],
});

// Document workflow
ga4.trackEvent('document_signed', {
  document_id: 'doc_123',
  signature_type: 'electronic',
});
```

### Multiple GA4 Properties

You can track to multiple GA4 properties simultaneously:

```typescript
// First property
const analytics = await GA4Client.create({
  measurementId: 'G-AAAAAAAA',
});

// Second property (different measurement ID = different instance)
const marketingAnalytics = await GA4Client.create({
  measurementId: 'G-BBBBBBBB',
});

// Track to specific property
analytics.trackEvent('user_action', { action: 'click' });
marketingAnalytics.trackEvent('campaign_view', { campaign: 'summer' });
```

### Resetting Instances (Testing)

```typescript
// Reset a specific instance
GA4Client.resetInstance('G-XXXXXXXXXX');

// Reset all instances
GA4Client.resetInstance();

// Now you can create new instances
const newClient = await GA4Client.create({
  measurementId: 'G-XXXXXXXXXX',
});
```

## API Reference

### Static Methods

#### `GA4Client.create(config: GA4ClientConfig): Promise<GA4Client>`

Creates and configures a GA4Client instance. Returns the existing instance if one already exists for the same measurement ID.

```typescript
const client = await GA4Client.create({
  measurementId: 'G-XXXXXXXXXX',
  debug: true,
});
```

#### `GA4Client.resetInstance(measurementId?: string): void`

Resets instance(s). If `measurementId` is provided, resets only that instance. Otherwise, resets all instances.

### Instance Methods

#### `trackEvent(eventName: string, params?: EventParams): void`

Track any GA4 event. Automatically includes common attributes from `@luminpdf/signing-miscellaneous`.

```typescript
ga4.trackEvent('custom_event', {
  custom_param: 'value',
});
```

#### `getConfig(): Readonly<GA4ClientConfig>`

Returns the current configuration.

#### `isClientConfigured(): boolean`

Returns whether the client has been configured.

## Configuration Options

### GA4ClientConfig

| Option           | Type      | Required | Description                                      |
| ---------------- | --------- | -------- | ------------------------------------------------ |
| `measurementId`  | `string`  | Yes      | Your GA4 measurement ID (e.g., `G-XXXXXXXXXX`)   |
| `debug`          | `boolean` | No       | Enable debug logging to console                  |
| `enableTracking` | `boolean` | No       | Enable/disable tracking                          |
| `appGTM`         | `string`  | No       | **Deprecated**: No longer used (gtag.js is used) |
| `dataLayerName`  | `string`  | No       | **Deprecated**: Uses global dataLayer            |

## Types

### `GA4ClientConfig`

```typescript
type GA4ClientConfig = {
  measurementId: string;
  debug?: boolean;
  enableTracking?: boolean;
  /** @deprecated No longer needed */
  appGTM?: string;
  /** @deprecated No longer used */
  dataLayerName?: string;
};
```

### `EventParams`

```typescript
type EventParams = Record<string, unknown>;
```

## Dependencies

- `@luminpdf/signing-miscellaneous` - Utility functions for common attributes

## License

MIT