# Events Reference

> One page of the LogDuck documentation. Every page is listed in https://logduck.com/llms.txt, and https://logduck.com/llms-full.txt is all of them in one file.

Events are the core of LogDuck. When something happens in your application—a user signs up, a payment is processed, an error occurs—you send an event to LogDuck.

## Endpoint

```text
POST https://api.logduck.com/v1/events
```

## Required Headers

`X-API-Key` — Your project API key (starts with `ld_`). Used to authenticate the request.

`Idempotency-Key` — A unique string (16–36 characters, alphanumeric, hyphens, or underscores). Can be any string as long as it is unique between requests — UUID4 and ULID are good options. If you retry a failed request, reuse the same key so the server can deduplicate and prevent duplicate events.

## Request Body

```typescript
interface EventPayload {
  // Required fields
  type: string;           // Event type (e.g., "user.signup")
  source: string;         // Origin identifier (e.g., "web-backend")

  // Optional fields
  subject?: string;       // Resource identifier (e.g., "user-123")
  sessionid?: string;     // Groups related events (max 256 chars)
  message?: string;       // Human-readable summary (max 500 chars)
  time?: string;          // ISO 8601 timestamp (defaults to server time)
  data?: object;          // Custom event payload - any JSON
  emoji?: string;         // Visual indicator (max 10 chars)
}
```

## Required Fields

`type` — The event type identifier. Must start with a letter and contain only letters, numbers, underscores and dots: `user.signup` and `payment_failed` are valid; a hyphen is rejected with a 400. Capitals are not — the server lowercases the type before storing it, so `User.Signup` is accepted and stored as `user.signup`. Dots are the convention for grouping events into categories.

**`source`** — Identifies where the event originated. This helps distinguish events from different parts of your system (e.g., `mobile-app`, `web-backend`, `payment-service`).

## Optional Fields

**`subject`** — A resource identifier that the event relates to. Use this to link events to specific entities (e.g., `user-123`, `order-456`).

`sessionid` — Groups related events that happened in the same session, so a whole user journey can be followed rather than isolated events. Max 256 characters. Lowercase: a CloudEvents extension attribute name must be.

`message` — A human-readable summary of what happened, max 500 characters. This is what a push notification shows; without it the body falls back to listing the first few `data` keys, which reads like `total: 4999, currency: NOK`.

**`time`** — ISO 8601 timestamp of when the event occurred. If omitted, the server will use the current time. Use this when you need to backfill events or when the event time differs from the submission time.

**`data`** — A flexible JSON object for custom event data. Use this for any event-specific information like user details, transaction amounts, feature names, error details, or categorization tags.

Anything outside the fields listed above is discarded rather than stored, so put custom values inside `data` rather than at the top level. For a human-readable summary, use `message` — a push notification shows it verbatim, and falls back to listing `data` keys without it.

**`emoji`** — A visual indicator for the event. Must be a single emoji character. If omitted, the default emoji for the event type will be used.

## Request context

LogDuck records where each event came from and stores it on the event as flat fields. You do not send these, and _cannot_ — they are derived from the connection, so an event can never claim an origin that is not its own.

`requestip` — The IP address the request came from.

`requestagent` — The User-Agent header of the request. Server keys only.

`requestdevice`, `requestbrowser` — Client keys only, in place of the address and the user agent: the device class (phone, tablet, desktop, tv, bot, other; mobile for a native app's hits) and the browser family (chrome, safari, firefox, edge, samsung, opera, in-app, other; app for a native app's hits). `requestuaversion` names the version of the rules that decided them.

`requestcountry`, `requestcontinent`, `requestregion` and `requestcity` — Coarse location derived from the IP. Country is an ISO 3166-1 alpha-2 code and continent one of AF, AN, AS, EU, NA, OC or SA. Region is the first-level subdivision — a state, province or region — by name. A country resolves for nearly every routable address; a city for rather fewer. Region and city are independent — an address can resolve to a region with no city, or the reverse — so do not guard one on the other.

`requestlat`, `requestlon`, `requesttimezone` and `requestcityid` — Present only when a city was identified, and absent otherwise rather than guessed. The coordinates are the approximate centre of the city as decimal-degree strings; they locate a city, not a device, and the underlying accuracy radius is typically 5–200 km. The time zone is an IANA name such as Europe/Brussels. The city id is the city's numeric GeoNames identifier, which distinguishes places that share a name — Portland, Oregon from Portland, Maine.

These are stored on the event and available in analytics. If you need location at a finer grain than city, resolve it yourself and put it in `data`.

Location is resolved from the IP using the GeoLite2 database created by [MaxMind](https://www.maxmind.com). It is an approximation: a country is almost always right, a city often is not.

## Data Payload Patterns

The `data` field accepts any JSON object. Here are suggested patterns for common event types:

```typescript
// User events
data: { userId: "u_123", email: "user@example.com", name: "John", sessionId: "sess_abc" }

// Payment events
data: { amount: 99.00, currency: "USD", transactionId: "txn_xyz" }

// Subscription events
data: { plan: "pro", tier: "annual", previousPlan: "free" }

// Error events
data: { error: "ConnectionTimeout", message: "Database unreachable", code: 500 }

// Feature usage
data: { feature: "export", action: "pdf_download", duration: 1250 }

// Categorization
data: { tags: ["mobile", "ios", "premium"] }
```

## Minimal example

Only type and source are required. Every variable used below is defined in the example itself.

**curl**

```bash
curl -X POST https://api.logduck.com/v1/events \
  -H "X-API-Key: ld_your_api_key" \
  -H "Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000" \
  -H "Content-Type: application/json" \
  -d '{"type": "order.placed", "source": "checkout-api"}'
```

**JavaScript**

```javascript
const apiKey = process.env.LOGDUCK_API_KEY;   // your key, starts with `ld_`

await fetch('https://api.logduck.com/v1/events', {
  method: 'POST',
  headers: {
    'X-API-Key': apiKey,
    'Idempotency-Key': crypto.randomUUID(),   // unique per event, reused only on retry
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    type: 'order.placed',
    source: 'checkout-api',
  }),
});
```

**Python**

```python
import os
import uuid

import requests

api_key = os.environ["LOGDUCK_API_KEY"]   # your key, starts with `ld_`

requests.post(
    "https://api.logduck.com/v1/events",
    headers={
        "X-API-Key": api_key,
        "Idempotency-Key": str(uuid.uuid4()),   # unique per event, reused only on retry
    },
    json={
        "type": "order.placed",
        "source": "checkout-api",
    },
)
```

**Swift**

```swift
import Foundation

let apiKey = ProcessInfo.processInfo.environment["LOGDUCK_API_KEY"]!  // starts with `ld_`

var request = URLRequest(url: URL(string: "https://api.logduck.com/v1/events")!)
request.httpMethod = "POST"
request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
request.setValue(UUID().uuidString, forHTTPHeaderField: "Idempotency-Key")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: [
    "type": "order.placed",
    "source": "checkout-api"
])
URLSession.shared.dataTask(with: request).resume()
```

**Kotlin**

```kotlin
import java.util.UUID
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody

val apiKey = System.getenv("LOGDUCK_API_KEY")     // starts with `ld_`

val client = OkHttpClient()
val body = """{"type": "order.placed", "source": "checkout-api"}"""
    .toRequestBody("application/json".toMediaType())
val request = Request.Builder()
    .url("https://api.logduck.com/v1/events")
    .post(body)
    .addHeader("X-API-Key", apiKey)
    .addHeader("Idempotency-Key", UUID.randomUUID().toString())
    .build()
client.newCall(request).execute()
```

**C#**

```csharp
using System.Net.Http.Json;

var apiKey = Environment.GetEnvironmentVariable("LOGDUCK_API_KEY");  // starts with ld_

using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
client.DefaultRequestHeaders.Add("Idempotency-Key", Guid.NewGuid().ToString());

await client.PostAsJsonAsync(
    "https://api.logduck.com/v1/events",
    new { type = "order.placed", source = "checkout-api" }
);
```

## Complete example

Every field the API accepts, in one payload. The language tabs annotate each one; JSON has no comments, so the curl tab relies on the field reference above.

**curl**

```bash
curl -X POST https://api.logduck.com/v1/events \
  -H "X-API-Key: ld_your_api_key" \
  -H "Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "order.placed",
    "source": "checkout-api",
    "subject": "order_9127",
    "sessionid": "sess_8f21c",
    "message": "Order placed on the Pro plan",
    "time": "2026-08-04T14:32:11.000Z",
    "emoji": "🛒",
    "data": {
      "total": 4999,
      "currency": "NOK"
    }
  }'
```

**JavaScript**

```javascript
const apiKey = process.env.LOGDUCK_API_KEY;   // your key, starts with `ld_`
const orderId = 'order_9127';                 // your own identifiers
const sessionId = 'sess_8f21c';

const response = await fetch('https://api.logduck.com/v1/events', {
  method: 'POST',
  headers: {
    'X-API-Key': apiKey,
    'Idempotency-Key': crypto.randomUUID(),   // unique per event, reused only on retry
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    type: 'order.placed',                     // required - max 100 chars
    source: 'checkout-api',                   // required - max 200 chars
    subject: orderId,                         // optional - max 500 chars
    sessionid: sessionId,                     // optional - max 256 chars, lowercase on the wire
    message: 'Order placed on the Pro plan',  // optional - the notification body, max 500
    time: new Date().toISOString(),           // optional - defaults to server receipt time
    emoji: '🛒',                               // optional - max 10 chars
    data: {                                   // optional - any JSON object
      total: 4999,
      currency: 'NOK',
    },
  }),
});

console.log(response.status);                 // 200 on success
```

**Python**

```python
import os
import uuid
from datetime import datetime, timezone

import requests

api_key = os.environ["LOGDUCK_API_KEY"]   # your key, starts with `ld_`
order_id = "order_9127"                   # your own identifiers
session_id = "sess_8f21c"

response = requests.post(
    "https://api.logduck.com/v1/events",
    headers={
        "X-API-Key": api_key,
        "Idempotency-Key": str(uuid.uuid4()),   # unique per event, reused only on retry
        "Content-Type": "application/json",
    },
    json={
        "type": "order.placed",                     # required - max 100 chars
        "source": "checkout-api",                   # required - max 200 chars
        "subject": order_id,                        # optional - max 500 chars
        "sessionid": session_id,                    # optional - max 256, lowercase on the wire
        "message": "Order placed on the Pro plan",  # optional - notification body, max 500
        "time": datetime.now(timezone.utc).isoformat(),  # optional - defaults to server time
        "emoji": "🛒",                               # optional - max 10 chars
        "data": {                                   # optional - any JSON object
            "total": 4999,
            "currency": "NOK",
        },
    },
)

print(response.status_code)                         # 200 on success
```

**Swift**

```swift
import Foundation

let apiKey = ProcessInfo.processInfo.environment["LOGDUCK_API_KEY"]!  // starts with `ld_`
let orderId = "order_9127"                        // your own identifiers
let sessionId = "sess_8f21c"

var request = URLRequest(url: URL(string: "https://api.logduck.com/v1/events")!)
request.httpMethod = "POST"
request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
request.setValue(UUID().uuidString, forHTTPHeaderField: "Idempotency-Key")  // unique per event
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let payload: [String: Any] = [
    "type": "order.placed",                       // required - max 100 chars
    "source": "checkout-api",                     // required - max 200 chars
    "subject": orderId,                           // optional - max 500 chars
    "sessionid": sessionId,                       // optional - lowercase on the wire
    "message": "Order placed on the Pro plan",    // optional - notification body
    "time": ISO8601DateFormatter().string(from: Date()),  // optional
    "emoji": "🛒",                                 // optional - max 10 chars
    "data": [                                     // optional - any JSON object
        "total": 4999,
        "currency": "NOK"
    ]
]
request.httpBody = try JSONSerialization.data(withJSONObject: payload)
URLSession.shared.dataTask(with: request).resume()
```

**Kotlin**

```kotlin
import java.util.UUID
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

val apiKey = System.getenv("LOGDUCK_API_KEY")     // starts with `ld_`
val orderId = "order_9127"                        // your own identifiers
val sessionId = "sess_8f21c"

val client = OkHttpClient()
val json = JSONObject().apply {
    put("type", "order.placed")                   // required - max 100 chars
    put("source", "checkout-api")                 // required - max 200 chars
    put("subject", orderId)                       // optional - max 500 chars
    put("sessionid", sessionId)                   // optional - lowercase on the wire
    put("message", "Order placed on the Pro plan") // optional - notification body
    put("time", java.time.Instant.now().toString())  // optional
    put("emoji", "🛒")                             // optional - max 10 chars
    put("data", JSONObject().apply {              // optional - any JSON object
        put("total", 4999)
        put("currency", "NOK")
    })
}
val request = Request.Builder()
    .url("https://api.logduck.com/v1/events")
    .post(json.toString().toRequestBody("application/json".toMediaType()))
    .addHeader("X-API-Key", apiKey)
    .addHeader("Idempotency-Key", UUID.randomUUID().toString())  // unique per event
    .build()
client.newCall(request).execute()
```

**C#**

```csharp
using System.Net.Http.Json;

var apiKey = Environment.GetEnvironmentVariable("LOGDUCK_API_KEY");  // starts with ld_
var orderId = "order_9127";                       // your own identifiers
var sessionId = "sess_8f21c";

using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
client.DefaultRequestHeaders.Add("Idempotency-Key", Guid.NewGuid().ToString());  // unique per event

var response = await client.PostAsJsonAsync(
    "https://api.logduck.com/v1/events",
    new {
        type = "order.placed",                    // required - max 100 chars
        source = "checkout-api",                  // required - max 200 chars
        subject = orderId,                        // optional - max 500 chars
        sessionid = sessionId,                    // optional - lowercase on the wire
        message = "Order placed on the Pro plan", // optional - notification body
        time = DateTimeOffset.UtcNow,             // optional
        emoji = "🛒",                              // optional - max 10 chars
        data = new {                              // optional - any JSON object
            total = 4999,
            currency = "NOK"
        }
    }
);

Console.WriteLine((int)response.StatusCode);      // 200 on success
```

> **Tip: Event Types**
> Use dot notation for event types (e.g., `user.signup`, `payment.completed`) to organize events into categories. LogDuck will auto-create event types when you send events.

> **Note: Sent from your backend?**
> Request context describes whoever called LogDuck. If your server posts events on behalf of users, that is your server — not them.
