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

# Backend APIs

> Server-side event tracking for Node.js, Python, Go, PHP, Ruby and any language that can make HTTP requests

## When to Use Backend APIs

**Perfect for server-side tracking:**

* User registration and authentication events
* Subscription and payment processing
* Admin actions and system events
* Webhook processing
* Background job events
* Any event that doesn't depend on the user's browser

**Key benefits:**

* ✅ Most reliable - no client-side dependencies
* ✅ Secure - API keys never exposed to browsers
* ✅ Server context - automatic IP, user agent detection
* ✅ Works with any backend language

***

## Quick Setup (5 minutes)

<Steps>
  <Step title="Get your API key">
    1. Sign up at [userboo.st](https://userboo.st)
    2. Go to **Settings** → **API Keys**
    3. Copy your **Server-side API key** (starts with `ub_live_`)
  </Step>

  <Step title="Choose your integration method">
    Pick the approach that fits your stack:

    <Tabs>
      <Tab title="Node.js SDK">
        **Recommended for Node.js applications**

        ```bash theme={null}
        npm install @userboost/sdk
        ```

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

        UserBoost.init({
          apiKey: process.env.USERBOOST_API_KEY,
          debug: process.env.NODE_ENV === "development",
        });
        ```
      </Tab>

      <Tab title="REST API">
        **Universal approach for any language**

        ```bash theme={null}
        curl -X POST https://api.userboo.st/v1/event \
          -H "Authorization: Bearer ub_live_your_api_key_here" \
          -H "Content-Type: application/json" \
          -d '{
            "event": "user_signed_up",
            "user": {
              "id": "user_123",
              "email": "john@example.com"
            }
          }'
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Track your first event">
    <Tabs>
      <Tab title="Node.js SDK">
        ```javascript theme={null}
        // Track user registration
        UserBoost.event("user_signed_up", {
          user: {
            id: "user_123",
            email: "john@example.com",
            traits: {
              plan: "free",
              signup_method: "email"
            }
          }
        });

        // Track feature usage
        UserBoost.event("feature_used", {
          user: { id: "user_123" },
          properties: {
            feature: "dashboard",
            usage_count: 1
          }
        });
        ```
      </Tab>

      <Tab title="REST API">
        ```bash theme={null}
        # User registration event
        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": "user_123",
              "email": "john@example.com",
              "traits": {
                "plan": "free",
                "signup_method": "email"
              }
            }
          }'

        # Feature usage event
        curl -X POST https://api.userboo.st/v1/event \
          -H "Authorization: Bearer $USERBOOST_API_KEY" \
          -H "Content-Type: application/json" \
          -d '{
            "event": "feature_used",
            "user": { "id": "user_123" },
            "properties": {
              "feature": "dashboard",
              "usage_count": 1
            }
          }'
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Verify it's working">
    1. Go to your [UserBoost dashboard](https://userboo.st/dashboard)
    2. Navigate to **Events** → **Live Stream**
    3. Your test event should appear within 30 seconds

    <Note>
      Enable debug mode during development to see detailed logs in your console.
    </Note>
  </Step>
</Steps>

***

## Language Examples

UserBoost works with any language that can make HTTP requests. Here are quick examples:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    // Using the official SDK (recommended)
    import { UserBoost } from "@userboost/sdk";

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

    // Track events anywhere in your app
    UserBoost.event("user_signed_up", {
      user: {
        id: user.id,
        email: user.email,
        traits: { plan: user.plan }
      }
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests
    import os

    def track_event(event, user_id, **properties):
        url = "https://api.userboo.st/v1/event"
        headers = {
            "Authorization": f"Bearer {os.environ['USERBOOST_API_KEY']}",
            "Content-Type": "application/json"
        }
        data = {
            "event": event,
            "user": {"id": user_id},
            "properties": properties
        }

        response = requests.post(url, json=data, headers=headers)
        return response.status_code == 200

    # Usage
    track_event("user_signed_up", "user_123", plan="free")
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    package main

    import (
        "bytes"
        "encoding/json"
        "net/http"
        "os"
    )

    type Event struct {
        Event      string                 `json:"event"`
        User       map[string]interface{} `json:"user"`
        Properties map[string]interface{} `json:"properties,omitempty"`
    }

    func TrackEvent(event string, userID string, properties map[string]interface{}) error {
        eventData := Event{
            Event: event,
            User:  map[string]interface{}{"id": userID},
            Properties: properties,
        }

        jsonData, _ := json.Marshal(eventData)

        req, _ := http.NewRequest("POST", "https://api.userboo.st/v1/event", bytes.NewBuffer(jsonData))
        req.Header.Set("Authorization", "Bearer "+os.Getenv("USERBOOST_API_KEY"))
        req.Header.Set("Content-Type", "application/json")

        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        defer resp.Body.Close()

        return nil
    }

    // Usage
    TrackEvent("user_signed_up", "user_123", map[string]interface{}{
        "plan": "free",
    })
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php

    function trackEvent($event, $userId, $properties = []) {
        $url = 'https://api.userboo.st/v1/event';
        $apiKey = $_ENV['USERBOOST_API_KEY'];

        $data = [
            'event' => $event,
            'user' => ['id' => $userId],
            'properties' => $properties
        ];

        $options = [
            'http' => [
                'header'  => [
                    "Authorization: Bearer $apiKey",
                    "Content-Type: application/json"
                ],
                'method'  => 'POST',
                'content' => json_encode($data)
            ]
        ];

        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result !== false;
    }

    // Usage
    trackEvent('user_signed_up', 'user_123', ['plan' => 'free']);
    ?>
    ```
  </Tab>

  <Tab title="Ruby">
    ```ruby theme={null}
    require 'net/http'
    require 'json'

    def track_event(event, user_id, properties = {})
      uri = URI('https://api.userboo.st/v1/event')

      data = {
        event: event,
        user: { id: user_id },
        properties: properties
      }

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true

      request = Net::HTTP::Post.new(uri)
      request['Authorization'] = "Bearer #{ENV['USERBOOST_API_KEY']}"
      request['Content-Type'] = 'application/json'
      request.body = data.to_json

      response = http.request(request)
      response.code == '200'
    end

    # Usage
    track_event('user_signed_up', 'user_123', { plan: 'free' })
    ```
  </Tab>
</Tabs>

***

## Common Event Patterns

Track these key events to build effective user journey funnels:

### Authentication Events

```javascript theme={null}
// User registration
UserBoost.event("user_signed_up", {
  user: {
    id: user.id,
    email: user.email,
    traits: {
      plan: "free",
      signup_method: "email",
      referral_source: req.headers.referer
    }
  }
});

// Login events
UserBoost.event("user_logged_in", {
  user: { id: user.id },
  properties: {
    login_method: "password",
    ip_address: req.ip
  }
});
```

### Onboarding Milestones

```javascript theme={null}
// Profile completion
UserBoost.event("profile_completed", {
  user: { id: user.id },
  properties: {
    completion_percentage: 100,
    time_to_complete: "2 minutes"
  }
});

// First key action
UserBoost.event("first_project_created", {
  user: { id: user.id },
  properties: {
    project_type: "web_app",
    days_since_signup: 1
  }
});
```

### Subscription Events

```javascript theme={null}
// Subscription changes
UserBoost.event("subscription_upgraded", {
  user: { id: user.id },
  properties: {
    from_plan: "free",
    to_plan: "pro",
    annual: true,
    amount: 99
  }
});
```

***

## Environment Setup

Store your API key securely using environment variables:

<CodeGroup>
  ```bash .env theme={null}
  USERBOOST_API_KEY=ub_live_your_api_key_here
  ```

  ```bash .env.local (Next.js) theme={null}
  USERBOOST_API_KEY=ub_live_your_api_key_here
  ```

  ```bash .env.production theme={null}
  USERBOOST_API_KEY=ub_live_your_production_key_here
  ```
</CodeGroup>

<Warning>
  **Never commit API keys to version control.** Always use environment variables and add `.env` files to your `.gitignore`.
</Warning>

***

## Testing & Debugging

### Enable Debug Mode (Node.js SDK)

```javascript theme={null}
UserBoost.init({
  apiKey: process.env.USERBOOST_API_KEY,
  debug: true, // Enables detailed console logging
});
```

### Test Event

```javascript theme={null}
// Send a test event to verify setup
UserBoost.event("integration_test", {
  user: { id: "test_user_" + Date.now() },
  properties: {
    test: true,
    timestamp: new Date().toISOString()
  }
});
```

### Common Issues

<AccordionGroup>
  <Accordion title="Events not appearing in dashboard" icon="exclamation-triangle">
    **Check these common causes:**

    * API key format (must start with `ub_live_`)
    * Required `user.id` field is missing
    * Network connectivity issues
    * Wrong environment (test vs live keys)

    **Enable debug mode to see detailed error messages.**
  </Accordion>

  <Accordion title="401 Unauthorized error" icon="shield">
    * Verify your API key is correct
    * Ensure you're using a **server-side** API key (not browser key)
    * Check that the key starts with `ub_live_`
  </Accordion>

  <Accordion title="Network timeout errors" icon="wifi">
    * Ensure your server can reach `api.userboo.st`
    * Check firewall settings
    * Verify SSL/TLS configuration
  </Accordion>
</AccordionGroup>

***

## What's Next?

<CardGroup cols={2}>
  <Card title="Track Events" icon="activity" href="/tracking/events">
    Learn how to track user actions and milestones effectively.
  </Card>

  <Card title="API Reference" icon="book" href="/api/rest-examples">
    Complete API documentation with all available endpoints.
  </Card>
</CardGroup>

Your backend integration is now ready! UserBoost will automatically start tracking your server-side events and building user journey funnels.
