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

# Authentication

> How to authenticate with the UserBoost API using API keys for server-side integration

## Overview

UserBoost uses API keys for server-side authentication. All API requests must include a valid API key in the Authorization header.

## Event Format for Authentication

UserBoost accepts events in a simple, flexible format:

### Required Fields

* **Event name**: `"event": "your_event_name"`
* **User object**: `"user": {"id": "user_id", ...}` (must be object with id field)

### User Object Format

UserBoost requires user data to be provided as an object:

**Minimal user object (required):**

```json theme={null}
{
  "event": "user_signed_up",
  "user": {
    "id": "user_123"
  }
}
```

**User object with additional data:**

```json theme={null}
{
  "event": "user_signed_up",
  "user": {
    "id": "user_123",
    "email": "john@example.com",
    "traits": {
      "plan": "free",
      "created_at": "2025-01-15"
    }
  }
}
```

<Warning>
  **Important:** String format like `"user": "user_123"` is no longer supported
  and will result in validation errors.
</Warning>

### Optional Fields

* **Properties**: `"properties": {...}` - Event-specific data
* **Timestamp**: Server generates automatically if not provided
* **Context**: IP, User-Agent automatically extracted from HTTP headers

## API Key Format

API keys use specific prefixes to indicate their environment:

<Tabs>
  <Tab title="Live Keys">
    **Format:** `ub_live_*` `ub_live_xyz789uvw012345678901234567890abcdef`

    * Used for production traffic - Trigger real email sends - Count towards
      billing limits - Should only be used in production
  </Tab>
</Tabs>

## Authentication Header

Include your API key in the Authorization header using Bearer authentication:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.userboo.st/v1/event \
    -H "Authorization: Bearer $USERBOOST_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "event": "user_signed_up",
      "user": {
        id: "xxx"
      },
      "properties": {
        "email": "john@example.com",
        "plan": "free"
      }
    }'
  ```

  ```javascript Node.js SDK theme={null}
  import { UserBoost } from "@userboost/sdk";

  UserBoost.init({ apiKey: process.env.USERBOOST_API_KEY });

  UserBoost.event("user_signed_up", {
    user: "user_123",
    properties: {
      email: "john@example.com",
      plan: "free",
    },
  });
  ```

  ```javascript Browser SDK theme={null}
  <script src="https://cdn.userboo.st/js/latest/userboost.min.js"></script>
  <script>
    ub.init({ apiKey: process.env.USERBOOST_API_KEY });
    ub.event("user_signed_up", {
      user: "user_123",
      properties: {
        email: "john@example.com"
      }
    });
  </script>
  ```
</CodeGroup>

## Creating API Keys

<Steps>
  <Step title="Sign Up">
    Create your account at [userboo.st](https://userboo.st)
  </Step>

  <Step title="Navigate to API Keys">
    Go to **Settings** → **API Keys** in your dashboard
  </Step>

  <Step title="Create New Key">
    Click **"Create New API Key"** and choose: - **Name**: Descriptive name
    (e.g., "Production Website") - **Type**: Test or Live environment
  </Step>

  <Step title="Copy and Store">
    Copy the API key immediately - it won't be shown again!
  </Step>
</Steps>

<Warning>
  **API keys are only shown once during creation.** Make sure to copy and
  securely store your key immediately.
</Warning>

## Security Best Practices

### Environment Management

<AccordionGroup>
  <Accordion title="✅ DO" icon="check">
    * Store API keys in environment variables
    * Use test keys in development/staging
    * Use live keys only in production
    * Rotate keys every 90 days
    * Use different keys for different projects
    * Monitor key usage in your dashboard
  </Accordion>

  <Accordion title="❌ DON'T" icon="x">
    * Commit API keys to version control
    * Share keys via email or chat
    * Use live keys in development
    * Hardcode keys in source code
    * Use the same key across multiple environments
    * Log API keys in application logs
  </Accordion>
</AccordionGroup>

### Key Rotation

To rotate an API key safely:

<Steps>
  <Step title="Create New Key">Generate a new API key in your dashboard</Step>

  <Step title="Update Environment">
    Update your environment variables with the new key
  </Step>

  <Step title="Deploy Changes">Deploy your application with the new key</Step>

  <Step title="Test Integration">
    Verify events are being received correctly
  </Step>

  <Step title="Delete Old Key">Remove the old key from your dashboard</Step>
</Steps>

## Error Responses

### Invalid API Key

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INVALID_API_KEY",
    "message": "Invalid or inactive API key"
  }
}
```

**HTTP Status:** `401 Unauthorized`

**Common causes:**

* API key is incorrect or malformed
* API key has been revoked
* Wrong key type (test vs live)
* Missing `ub_live_` or `ub_live_` prefix

### Missing Authorization Header

```json theme={null}
{
  "success": false,
  "error": {
    "code": "MISSING_AUTH_HEADER",
    "message": "Missing or invalid authorization header"
  }
}
```

**HTTP Status:** `401 Unauthorized`

**Common causes:**

* No Authorization header provided
* Header doesn't start with "Bearer "
* Empty or whitespace-only header value

### Invalid Key Format

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INVALID_KEY_FORMAT",
    "message": "API key must start with ub_live_ or ub_live_"
  }
}
```

**HTTP Status:** `401 Unauthorized`

**Solution:** Ensure your API key uses the correct prefix format.

## Testing Authentication

### Verify Your Setup

Test authentication with a simple API call:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.userboo.st/v1/event \
    -H "Authorization: Bearer $USERBOOST_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "auth_test",
      "user": "test_user"
    }'
  ```

  ```javascript Browser Script Tag theme={null}
  // Using the SDK
  ub.init({
    apiKey: process.env.USERBOOST_API_KEY, // Use ub_live_* for development
    debug: true, // Shows auth status in console
  });

  ub.event("auth_test", {
    user: "test_user",
  });

  // Check console for success/error messages
  ```

  ```javascript NPM Package theme={null}
  import { UserBoost } from "@userboost/sdk";

  // Using the SDK
  UserBoost.init({
    apiKey: process.env.USERBOOST_API_KEY, // Use ub_live_* for development
    debug: true, // Shows auth status in console
  });

  UserBoost.event("auth_test", {
    user: "test_user",
  });

  // Check console for success/error messages
  ```
</CodeGroup>

### Expected Success Response

```json theme={null}
{
  "success": true,
  "data": {
    "processed_count": 1,
    "failed_count": 0,
    "results": [
      {
        "index": 0,
        "success": true,
        "event_id": "550e8400-e29b-41d4-a716-446655440000"
      }
    ]
  }
}
```

## Rate Limits

API key-based rate limiting is applied per minute based on your subscription plan:

| Plan       | Price      | API Requests/Minute | Event Limit/Month | Email Limit/Month |
| ---------- | ---------- | ------------------- | ----------------- | ----------------- |
| **Hobby**  | Free       | 100                 | 1,000             | 100               |
| **Launch** | \$25/month | 1,000               | 20,000            | 5,000             |
| **Orbit**  | \$79/month | 10,000              | 200,000           | 25,000            |

<Info>
  Rate limits are applied per account based on your active subscription. All API
  keys under your account share the same rate limit.
</Info>

### Rate Limit Headers

All API responses include rate limit information:

```http theme={null}
HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642694400
X-RateLimit-Window: 60
```

* **X-RateLimit-Limit**: Maximum requests allowed per minute
* **X-RateLimit-Remaining**: Requests remaining in current window
* **X-RateLimit-Reset**: Unix timestamp when the limit resets
* **X-RateLimit-Window**: Window duration in seconds (always 60)

### Rate Limit Exceeded

When you exceed your rate limit, you'll receive a `429 Too Many Requests` response:

```json theme={null}
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Try again in 45 seconds.",
    "details": {
      "limit": 100,
      "window_seconds": 60,
      "retry_after_seconds": 45,
      "requests_remaining": 0
    }
  }
}
```

**HTTP Status:** `429 Too Many Requests`

**Response Headers:**

```http theme={null}
Retry-After: 45
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1642694460
X-RateLimit-Window: 60
```
