# Set up tracking

Send product events and identity updates to Altertable with SDKs or direct HTTP requests. The same payload model writes to the built-in `product_analytics` catalog, so client, server, mobile, and batch sources can be analyzed together.

## Set up with your coding agent

Open this prompt in your coding agent from your application repository. It will inspect your stack and guide the implementation.

```text
Set up Altertable Product Analytics in this repository. Read https://altertable.ai/docs/product-analytics/setup.md and the linked official SDK documentation first.

Inspect my framework, runtime, package manager, authentication, and existing analytics. Choose the matching SDK. Ask which user journey I want to measure and propose a small event plan before changing code.

Guide me through enabling Product Analytics and configuring its environment-specific API key without committing secrets. MCP and lakehouse credentials do not replace this key.

Reuse or initialize one shared client. Track completed actions, identify signed-in users, reset identity at sign-out, and respect consent. Check which helpers the SDK supports and avoid sensitive properties.

Run checks. Send one named verification event with a unique test identity in the chosen environment. Query product_analytics.main.events by that event name and identity, and confirm the properties and timestamp. Do not use the newest row as proof. Use my Altertable connection if available. Summarize changed files, verification results, and remaining setup.
```

Prefer to configure it yourself? Follow the steps below.

## Goal

Choose an SDK, connect it with a Product Analytics API key, and send events and identity updates to the built-in `product_analytics` catalog.

## Prerequisites

- Enable [Product Analytics](/docs/product-analytics.md) for the target environment.
- Copy a Product Analytics [API key](/docs/product-analytics/authentication.md).
- Choose a client-side or server-side SDK based on where your application sends events.

## Steps

### 1. Install an SDK

Choose the SDK for your application language:

| Language                                                                                                            | Install                                                                                                                                       |
| ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| TypeScript / JavaScript[TypeScript / JavaScript GitHub repository](https://github.com/altertable-ai/altertable-js/) | `npm install @altertable/altertable-js`                                                                                                       |
| React[React GitHub repository](https://github.com/altertable-ai/altertable-js/)                                     | `npm install @altertable/altertable-js @altertable/altertable-react`                                                                          |
| Python[Python GitHub repository](https://github.com/altertable-ai/altertable-python)                                | `pip install altertable` or `poetry add altertable`                                                                                           |
| Ruby[Ruby GitHub repository](https://github.com/altertable-ai/altertable-ruby)                                      | `gem install altertable`                                                                                                                      |
| Swift[Swift GitHub repository](https://github.com/altertable-ai/altertable-swift)                                   | Swift Package Manager                                                                                                                         |
| Kotlin / Android[Kotlin / Android GitHub repository](https://github.com/altertable-ai/altertable-kotlin)            | Follow the [JVM or Android Gradle setup](https://github.com/altertable-ai/altertable-kotlin) for package coordinates and the current version. |

### 2. Initialize the client and send data

Use these examples as the starting point for your application code:

### TypeScript

```typescript
import { altertable } from '@altertable/altertable-js';

// Initialize with your API key
altertable.init('{{API_KEY}}');

// Track a user event
altertable.track('checkout_completed', {
  revenue: 49.99,
  plan: 'pro',
  currency: 'USD',
});

// Identify a user
altertable.identify('user_abc123', {
  email: 'alice@acme.com',
  plan: 'pro',
});
```

### React

```tsx
import { altertable } from '@altertable/altertable-js';
import {
  AltertableProvider,
  useAltertable,
} from '@altertable/altertable-react';

// Initialize the core SDK
altertable.init('{{API_KEY}}');

function App() {
  return (
    <AltertableProvider client={altertable}>
      <CheckoutPage />
    </AltertableProvider>
  );
}

function CheckoutPage() {
  const { track, identify } = useAltertable();

  function handleCheckout() {
    track('checkout_completed', {
      revenue: 49.99,
      plan: 'pro',
      currency: 'USD',
    });
  }

  function handleLogin(userId) {
    identify(userId, {
      email: 'alice@acme.com',
      plan: 'pro',
    });
  }

  return (
    <div>
      <button onClick={handleCheckout}>Complete Checkout</button>
      <button onClick={() => handleLogin('user_abc123')}>Login</button>
    </div>
  );
}
```

### Python

```python
from altertable import Altertable

client = Altertable("{{API_KEY}}")

# Track a user event
client.track(
    event="checkout_completed",
    distinct_id="user_abc123",
    options={
        "properties": {
            "revenue": 49.99,
            "plan": "pro",
            "currency": "USD",
        }
    }
)

# Identify a user
client.identify(
    distinct_id="user_abc123",
    options={
        "traits": {
            "email": "alice@acme.com",
            "plan": "pro",
        }
    }
)
```

### Ruby

```ruby
require 'altertable'

Altertable.init('{{API_KEY}}')

# Track a user event
Altertable.track('checkout_completed', 'user_abc123', properties: {
  revenue: 49.99,
  plan: 'pro',
  currency: 'USD'
})

# Identify a user
Altertable.identify('user_abc123', traits: {
  email: 'alice@acme.com',
  plan: 'pro'
})
```

### Swift

```swift
import Altertable

let client = Altertable(apiKey: "{{API_KEY}}")

// Track a user event
client.track(
    event: "checkout_completed",
    properties: [
        "revenue": 49.99,
        "plan": "pro",
        "currency": "USD"
    ]
)

// Identify a user
client.identify(
    userId: "user_abc123",
    traits: [
        "email": "alice@acme.com",
        "plan": "pro"
    ]
)
```

### Kotlin

```kotlin
import ai.altertable.sdk.Altertable

// Initialize with your API key
Altertable.setup {
    apiKey = "{{API_KEY}}"
}

// Track a user event
Altertable.shared?.track(
    event = "checkout_completed",
    properties = mapOf(
        "revenue" to 49.99,
        "plan" to "pro",
        "currency" to "USD"
    )
)

// Identify a user
Altertable.shared?.identify(
    userId = "user_abc123",
    traits = mapOf(
        "email" to "alice@acme.com",
        "plan" to "pro"
    )
)
```

After initialization:

1. Track events with event properties.
2. Identify users and attach traits.
3. Optionally alias related identities.

### 3. Choose client-side or server-side behavior

Use a client-side SDK for events from a browser or mobile application. Use a server-side SDK for events from backend services or jobs, and pass a stable `distinct_id` to associate each event with its user.

Automatic page capture, session management, consent helpers, and offline queuing vary by SDK. Check the repository for your SDK for the features available in your runtime.

### 4. Configure page, screen, and consent helpers

If your SDK provides page or screen helpers, configure them for the views you want to track:

### TypeScript

```typescript
// Disable auto-capture if you need manual control
altertable.init('{{API_KEY}}', { autoCapture: false });

// Then track page views manually
altertable.page('https://example.com/products');
```

### React

```tsx
import { altertable } from '@altertable/altertable-js';
import { useAltertable } from '@altertable/altertable-react';

altertable.init('{{API_KEY}}', { autoCapture: false });

function ProductPage() {
  const { page } = useAltertable();

  return (
    <button onClick={() => page('https://example.com/products')}>
      View products
    </button>
  );
}
```

### Python

```python
# Automatic page and screen tracking is not supported in the Python SDK.
# Track meaningful page or screen views as regular events with client.track().
```

### Ruby

```ruby
# Automatic page and screen tracking is not supported in the Ruby SDK.
# Track meaningful page or screen views as regular events with Altertable.track.
```

### Swift

```swift
Text("Welcome")
    .screenView(name: "Home")
```

### Kotlin

```kotlin
Column(modifier = Modifier.screenView(name = "Home")) {
    // Screen content
}
```

Where supported, use consent helpers to control whether the SDK sends data:

### TypeScript

```typescript
// JavaScript — initialize with consent pending
altertable.init('{{API_KEY}}', { trackingConsent: 'pending' });

// Later, when the user grants consent
altertable.configure({ trackingConsent: 'granted' });
```

### React

```tsx
import { altertable } from '@altertable/altertable-js';
import { useAltertable } from '@altertable/altertable-react';

altertable.init('{{API_KEY}}', { trackingConsent: 'pending' });

function ConsentButton() {
  const { configure } = useAltertable();

  return (
    <button onClick={() => configure({ trackingConsent: 'granted' })}>
      Allow analytics
    </button>
  );
}
```

### Python

```python
# The Python SDK has no built-in tracking consent state.
# Check consent in your application before calling client.track() or client.identify().
```

### Ruby

```ruby
# The Ruby SDK has no built-in tracking consent state.
# Check consent in your application before calling Altertable.track or Altertable.identify.
```

### Swift

```swift
// Swift — initialize with consent pending
let config = AltertableConfig(trackingConsent: .pending)
let client = Altertable(apiKey: "{{API_KEY}}", config: config)

// Later, when the user grants consent
client.configure { config in
    config.trackingConsent = .granted
}
```

### Kotlin

```kotlin
// Kotlin — initialize with consent pending
Altertable.setup {
    apiKey = "{{API_KEY}}"
    tracking { consent = TrackingConsent.PENDING }
}

// Later, when the user grants consent
Altertable.shared?.configure {
    tracking { consent = TrackingConsent.GRANTED }
}
```

## Verification

Send one event from your application, then query the raw events table:

```sql
SELECT *
FROM product_analytics.main.events
ORDER BY timestamp DESC
LIMIT 10;
```

Confirm that the event name, distinct ID, timestamp, and properties match the payload your application sent.

## Troubleshooting

- **No events appear:** confirm that Product Analytics is enabled in the same environment as the API key.
- **Requests are rejected:** check the [authentication methods](/docs/product-analytics/authentication.md) and replace an incorrect or expired API key.
- **Users remain anonymous:** call `identify` when a stable user ID becomes available, and pass `distinct_id` explicitly from server-side SDKs.
- **Automatic page or screen events are missing:** confirm that your SDK supports page or screen capture, then enable its helper.

**Continue in Altertable:** [Open Altertable](/app)

## Next steps

- [Authentication](/docs/product-analytics/authentication.md): Authenticate Product Analytics SDKs and API requests with public API keys for the target staging or production environment.
- [Track](/docs/product-analytics/track.md): Track product events from SDKs or API clients and make behavioral data queryable in your Altertable lakehouse.
- [Identify](/docs/product-analytics/identify.md): Identify users in Altertable Product Analytics so events connect to stable profiles, traits, and business context.
- [Alias](/docs/product-analytics/alias.md): Alias product analytics identifiers in Altertable to merge user profiles when identity systems or user IDs change.