# @solid-analytics/solidstart

SolidStart integration for [@solid-analytics](../../README.md) with **server-side tracking** support using server functions.

## Features

- 🚀 **Server-Side Tracking** - Track events on the server using SolidStart's server functions
- 🔄 **Automatic RPC** - Server functions handle client-server communication automatically
- 📊 **Request Context Enrichment** - Automatic IP, user agent, geo data, and session extraction
- 🎯 **Type-Safe** - Full TypeScript support
- 🔒 **Secure** - Server functions run securely on the backend
- ⚡ **Performance** - No API routes needed, uses Vinxi's built-in RPC
- 🤖 **Bot Detection** - Track server-side to catch bots and crawlers

## Installation

```bash
npm install @solid-analytics/solidstart
# or
pnpm add @solid-analytics/solidstart
# or
yarn add @solid-analytics/solidstart
```

You'll also need the Vite plugin:

```bash
npm install -D @solid-analytics/vite-plugin
```

## Quick Start

### 1. Configure Vite Plugin

```ts
// app.config.ts
import { defineConfig } from '@solidjs/start/config'
import solidAnalytics from '@solid-analytics/vite-plugin'

export default defineConfig({
  vite: {
    plugins: [
      solidAnalytics({
        debug: true,
      }),
    ],
  },
})
```

### 2. Set Up Provider

```tsx
// app.tsx
import { AnalyticsProvider } from '@solid-analytics/solidstart'
import Analytics from 'analytics'
import segmentPlugin from '@analytics/segment'

const client = Analytics({
  app: 'my-app',
  plugins: [
    segmentPlugin({
      writeKey: 'YOUR_WRITE_KEY'
    })
  ]
})

export default function App() {
  return (
    <AnalyticsProvider 
      client={client}
      options={{ 
        ssr: 'server-function', // Enable server-side tracking
        serverOptions: {
          enrichContext: true,   // Auto-enrich with IP, UA, etc.
          includeSession: true,  // Extract session from cookies
        }
      }}
    >
      <Router>
        <Routes>
          {/* Your routes */}
        </Routes>
      </Router>
    </AnalyticsProvider>
  )
}
```

### 3. Use Analytics Directives

```tsx
// Any component
export default function ProductPage() {
  return (
    <div>
      <h1>Product Details</h1>
      
      {/* Automatically tracked server-side! */}
      <button analytics:click="add_to_cart">
        Add to Cart
      </button>
      
      <button analytics:click={["purchase", { amount: 99.99, currency: "USD" }]}>
        Buy Now
      </button>
    </div>
  )
}
```

## SSR Modes

### `'server-function'` (Recommended)

Uses SolidStart server functions for automatic server-side tracking with RPC.

**Benefits:**
- ✅ Automatic request context (IP, user agent, geo)
- ✅ No API routes needed
- ✅ Type-safe client-server communication
- ✅ Built-in rate limiting via Vinxi
- ✅ Catches bot traffic

```tsx
<AnalyticsProvider 
  client={client}
  options={{ ssr: 'server-function' }}
>
```

**How it works:**
1. User clicks button with `analytics:click`
2. Client calls server function via RPC
3. Server function enriches event with request context
4. Event sent to analytics provider from server

### `'queue'`

Queue events during SSR, replay on client hydration.

```tsx
<AnalyticsProvider 
  client={client}
  options={{ ssr: 'queue' }}
>
```

### `'track'`

Track immediately on server (no client replay).

```tsx
<AnalyticsProvider 
  client={client}
  options={{ ssr: 'track' }}
>
```

### `'both'`

Track on both server and client (for validation/fraud detection).

```tsx
<AnalyticsProvider 
  client={client}
  options={{ ssr: 'both' }}
>
```

### `false`

Client-only tracking (default for vanilla Solid).

```tsx
<AnalyticsProvider 
  client={client}
  options={{ ssr: false }}
>
```

## Server Functions API

You can also use server functions directly for custom tracking logic:

### `serverTrack`

```tsx
"use server"

import { serverTrack } from '@solid-analytics/solidstart/server'

export async function handleCheckout(cart: Cart) {
  // Process checkout...
  
  // Track on server with automatic context enrichment
  await serverTrack('checkout_completed', {
    items: cart.items,
    total: cart.total,
    currency: 'USD',
  }, {
    client: analyticsClient,
    enrichContext: true,
  })
}
```

### `serverIdentify`

```tsx
"use server"

import { serverIdentify } from '@solid-analytics/solidstart/server'

export async function handleLogin(userId: string, email: string) {
  // Login logic...
  
  await serverIdentify(userId, {
    email,
    plan: 'premium',
    signupDate: new Date().toISOString(),
  }, {
    client: analyticsClient,
  })
}
```

### `serverPage`

```tsx
"use server"

import { serverPage } from '@solid-analytics/solidstart/server'

export async function trackProductView(productId: string) {
  await serverPage('Product', {
    productId,
    category: 'electronics',
  }, {
    client: analyticsClient,
  })
}
```

### `createServerAnalytics`

Create a reusable server analytics instance:

```tsx
"use server"

import { createServerAnalytics } from '@solid-analytics/solidstart/server'
import { analyticsClient } from './analytics'

const analytics = createServerAnalytics(analyticsClient, {
  enrichContext: true,
  debug: true,
})

export async function trackPurchase(data: any) {
  await analytics.track('purchase', data)
}

export async function identifyUser(userId: string, traits: any) {
  await analytics.identify(userId, traits)
}
```

## Request Context Enrichment

When `enrichContext: true`, events are automatically enriched with:

```ts
{
  $context: {
    ip: "192.168.1.1",              // Client IP
    userAgent: "Mozilla/5.0...",    // User agent string
    referer: "https://google.com",  // HTTP referer
    country: "US",                  // Country code (from CDN headers)
    region: "CA",                   // Region/state
    city: "San Francisco",          // City
    sessionId: "abc123",            // Session ID (from cookies)
    userId: "user_456",             // User ID (from cookies)
  },
  $server: true,                    // Indicates server-side event
  $timestamp: "2026-02-07T...",     // ISO timestamp
}
```

### Supported Headers

- `x-forwarded-for` - Client IP
- `x-real-ip` - Real IP
- `cf-connecting-ip` - Cloudflare IP
- `cf-ipcountry` - Cloudflare country
- `x-vercel-ip-country` - Vercel country
- `x-vercel-ip-country-region` - Vercel region
- `x-vercel-ip-city` - Vercel city
- `user-agent` - Browser/bot user agent
- `referer` - HTTP referer

## Use Cases

### Bot Analytics

Track server-side to catch bots that don't execute JavaScript:

```tsx
<AnalyticsProvider options={{ ssr: 'server-function' }}>
  <a href="/download" analytics:click="file_downloaded">
    Download PDF
  </a>
</AnalyticsProvider>
```

### SEO Tracking

Track search engine crawlers and SEO performance:

```tsx
"use server"

import { serverPage } from '@solid-analytics/solidstart/server'
import { getRequestEvent } from 'solid-js/web'

export async function trackCrawler() {
  const event = getRequestEvent()
  const ua = event?.request.headers.get('user-agent') || ''
  
  if (ua.includes('bot') || ua.includes('crawler')) {
    await serverPage('Crawler Visit', {
      bot: ua,
      url: event?.request.url,
    })
  }
}
```

### Fraud Detection

Track on both server and client to detect discrepancies:

```tsx
<AnalyticsProvider options={{ ssr: 'both' }}>
  <button analytics:click={["high_value_action", { amount: 10000 }]}>
    Transfer $10,000
  </button>
</AnalyticsProvider>
```

Compare server and client events to detect:
- Script blockers/ad blockers
- Bot activity
- Fraudulent behavior
- Analytics evasion

## TypeScript

Full type support included:

```tsx
import type { 
  AnalyticsProviderProps,
  SolidStartAnalyticsOptions,
  ServerTrackOptions,
  RequestContext 
} from '@solid-analytics/solidstart'
```

## Performance

- **Server functions** use Vinxi's optimized RPC (no API routes needed)
- **Automatic batching** for multiple events
- **Non-blocking** - analytics failures won't crash your app
- **Minimal bundle size** - tree-shakeable exports

## Debugging

Enable debug mode to see what's being tracked:

```tsx
<AnalyticsProvider 
  client={client}
  options={{ 
    ssr: 'server-function',
    debug: true,  // Logs all events
    serverOptions: {
      debug: true,  // Logs server-side events
    }
  }}
>
```

## Examples

See the [examples directory](../../examples) for complete working examples:

- `examples/solidstart-basic` - Basic setup
- `examples/solidstart-auth` - User authentication tracking
- `examples/solidstart-ecommerce` - E-commerce tracking

## Related Packages

- [@solid-analytics/solid](../solid) - Vanilla Solid integration
- [@solid-analytics/vite-plugin](../vite-plugin) - Vite plugin (required)
- [@solid-analytics/babel-plugin](../babel-plugin) - Underlying Babel transformation

## License

MIT

## Contributing

See the [main repository](../../README.md) for contribution guidelines.
