> ## Documentation Index
> Fetch the complete documentation index at: https://docs.grainql.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Overview

> Complete API reference for the Grain SDKs

Grain provides two SDKs for different use cases:

* **Grain Tag** (`@grainql/tag`) — The primary SDK for browser-side analytics. Cookieless by default, auto-tracks page views, clicks, scroll, sessions, and more.
* **Analytics Web** (`@grainql/analytics-web`) — For remote configuration, React hooks, template events, and server-side tracking.

***

## Grain Tag

The default SDK for browser analytics. Lightweight, privacy-first, and SSR safe.

### Import Paths

```typescript theme={null}
// Core SDK
import { init, track, identify, getInstance, isInitialized, destroy } from '@grainql/tag';

// Types
import type { GrainTagConfig, GrainTagInstance, ConsentState } from '@grainql/tag';
```

### Lifecycle

```
init(config) → track/identify → flush → destroy
```

1. **`init(config?)`** — Creates the singleton instance and starts auto-tracking
2. **`track(name, props?)`** / **`identify(userId)`** — Send events (works before init via pre-init queue)
3. **`flush()`** — Force-send all pending events
4. **`destroy()`** — Tear down the SDK and clear the singleton

### Quick Reference

| Method                          | Description                                  |
| ------------------------------- | -------------------------------------------- |
| `init(config?)`                 | Create singleton, returns `GrainTagInstance` |
| `track(eventName, properties?)` | Track a custom event                         |
| `identify(userId)`              | Set user identity                            |
| `getInstance()`                 | Get existing instance or `null`              |
| `isInitialized()`               | Check if SDK is initialized                  |
| `destroy()`                     | Tear down SDK, clear singleton               |

#### Instance Methods

| Method                                | Description                 |
| ------------------------------------- | --------------------------- |
| `grain.track(eventName, properties?)` | Track a custom event        |
| `grain.identify(userId)`              | Set user identity           |
| `grain.consent.grant(categories?)`    | Grant consent               |
| `grain.consent.revoke(categories?)`   | Revoke consent              |
| `grain.consent.status()`              | Get current consent state   |
| `grain.flush()`                       | Flush pending events        |
| `grain.destroy()`                     | Tear down instance          |
| `grain.isReady()`                     | Check if running in browser |

***

## Analytics Web

For remote configuration, React hooks, template events, and server-side tracking.

### Import Paths

```typescript theme={null}
// Core SDK
import { createGrainAnalytics } from '@grainql/analytics-web';

// React Hooks
import { GrainProvider, useConfig, useAllConfigs, useTrack, useGrainAnalytics } from '@grainql/analytics-web/react';

// Types
import type { GrainConfig, GrainEvent, AuthProvider } from '@grainql/analytics-web';
```

### Quick Reference

| Method                                          | Description            |
| ----------------------------------------------- | ---------------------- |
| `createGrainAnalytics(config)`                  | Create client instance |
| `grain.track(eventName, properties?, options?)` | Track an event         |
| `grain.flush()`                                 | Flush pending events   |
| `grain.setUserId(userId)`                       | Set user ID            |
| `grain.identify(userId)`                        | Alias for setUserId    |
| `grain.getUserId()`                             | Get current user ID    |
| `grain.setProperty(properties, options?)`       | Set user properties    |
| `grain.destroy()`                               | Clean up resources     |

#### Remote Configuration

| Method                                       | Description                    |
| -------------------------------------------- | ------------------------------ |
| `grain.getConfig(key)`                       | Get config value (sync)        |
| `grain.getAllConfigs()`                      | Get all configs (sync)         |
| `grain.getConfigAsync(key, options?)`        | Get config value (async)       |
| `grain.getAllConfigsAsync(options?)`         | Get all configs (async)        |
| `grain.fetchConfig(options?)`                | Fetch fresh config from server |
| `grain.preloadConfig(keys?, properties?)`    | Preload config values          |
| `grain.addConfigChangeListener(listener)`    | Listen for config changes      |
| `grain.removeConfigChangeListener(listener)` | Remove config listener         |

#### Template Events

| Method                                             | Description            |
| -------------------------------------------------- | ---------------------- |
| `grain.trackLogin(properties?, options?)`          | Track login            |
| `grain.trackSignup(properties?, options?)`         | Track signup           |
| `grain.trackCheckout(properties?, options?)`       | Track checkout         |
| `grain.trackPurchase(properties?, options?)`       | Track purchase         |
| `grain.trackAddToCart(properties?, options?)`      | Track add to cart      |
| `grain.trackRemoveFromCart(properties?, options?)` | Track remove from cart |
| `grain.trackPageView(properties?, options?)`       | Track page view        |
| `grain.trackSearch(properties?, options?)`         | Track search           |

#### React Hooks

| Hook                           | Description               |
| ------------------------------ | ------------------------- |
| `<GrainProvider config={...}>` | Context provider          |
| `useConfig(key, options?)`     | Get a single config value |
| `useAllConfigs(options?)`      | Get all config values     |
| `useTrack()`                   | Get track function        |
| `useGrainAnalytics()`          | Get client instance       |

***

## Return Values

* **Synchronous methods**: Direct values or `undefined`
* **Async methods**: `Promise<T>` that resolves to the result
* **Hooks**: Objects with data, loading states, and errors

## Error Handling

Methods handle errors gracefully:

* **track()**: Fire-and-forget, errors logged if debug enabled
* **Config methods**: Return cached/default on failure
* **Async methods**: Throw errors, catch with try/catch
* **Hooks**: Provide `error` property

Learn more in [Error Handling](/advanced/error-handling).

***

## Explore the API

<CardGroup cols={2}>
  <Card title="Core Methods" icon="code" href="/api-reference/core-methods">
    Event tracking and user management
  </Card>

  <Card title="Config Methods" icon="sliders" href="/api-reference/config-methods">
    Remote configuration access
  </Card>

  <Card title="Template Methods" icon="sparkles" href="/api-reference/template-methods">
    Pre-built event methods
  </Card>

  <Card title="React Hooks" icon="react" href="/api-reference/react-hooks">
    React integration hooks
  </Card>

  <Card title="Types" icon="code-simple" href="/api-reference/types">
    TypeScript type definitions
  </Card>
</CardGroup>
