Skip to main content

Webhooks

Receive real-time notifications when memories are created, updated, or deleted.

Overview

Webhooks allow you to receive HTTP callbacks when events occur in your Trix account. This enables real-time integrations, automated workflows, and synchronization with external systems.

Use Cases: Sync memories to external databases, trigger workflows when new information is stored, or build real-time dashboards.

Creating a Webhook

Configure webhooks using the API:

const webhook = await trix.webhooks.create({
  url: "https://your-server.com/webhooks/trix",
  events: ["memory.created", "memory.updated", "memory.deleted"],
  secret: "your_webhook_secret"
});

console.log(webhook.id); // whk_abc123

Response

Response
{
  "id": "whk_abc123",
  "url": "https://your-server.com/webhooks/trix",
  "events": ["memory.created", "memory.updated", "memory.deleted"],
  "status": "active",
  "created_at": "2024-01-15T10:30:00Z"
}

Available Events

Subscribe to one or more of these event types:

EventDescriptionPayload
memory.createdA new memory was storedFull memory object
memory.updatedA memory's content or metadata was modifiedUpdated memory object
memory.deletedA memory was deletedMemory ID only
memory.reinforcedA memory's priority was boostedMemory ID and new priority
space.createdA new space was createdSpace object
space.deletedA space was deletedSpace ID only
entity.extractedNew entities were extracted from a memoryEntity objects

Use * to subscribe to all events: "events": ["*"]

Webhook Payload

Each webhook delivery includes:

webhook-payload.json
{
  "id": "evt_xyz789",
  "type": "memory.created",
  "created_at": "2024-01-15T10:30:00Z",
  "webhook_id": "whk_abc123",
  "data": {
    "id": "mem_abc123",
    "content": "User prefers dark mode and compact layouts",
    "space": "default",
    "tags": ["preference", "ui"],
    "metadata": {
      "source": "conversation"
    },
    "created_at": "2024-01-15T10:30:00Z"
  }
}

Request Headers

Trix includes these headers with each webhook request:

HeaderDescription
X-Webhook-SignatureHMAC-SHA256 signature for verification
X-Trix-EventThe event type (e.g., memory.created)
X-Trix-DeliveryUnique ID for this delivery (for deduplication)
X-Trix-TimestampUnix timestamp when the event occurred

Verifying Signatures

Always verify webhook signatures to ensure requests are from Trix and haven't been tampered with. The signature is computed as HMAC-SHA256(timestamp.payload, secret).

import crypto from 'crypto';

function verifyWebhook(
  payload: string,
  signature: string,
  timestamp: string,
  secret: string
): boolean {
  // Prevent replay attacks
  const age = Date.now() / 1000 - parseInt(timestamp);
  if (age > 300) { // 5 minutes
    throw new Error('Webhook timestamp too old');
  }

  // Compute expected signature
  const signedPayload = `${timestamp}.${payload}`;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  // Constant-time comparison
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

// Express.js example
app.post('/webhooks/trix', (req, res) => {
  const signature = req.headers['x-trix-signature'];
  const timestamp = req.headers['x-trix-timestamp'];
  const payload = JSON.stringify(req.body);

  if (!verifyWebhook(payload, signature, timestamp, WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }

  // Process the event
  const event = req.body;
  console.log(`Received ${event.type}: ${event.data.id}`);

  res.status(200).send('OK');
});

Security: Always verify signatures and check timestamps to prevent replay attacks. Never trust unverified webhook payloads.

Retry Policy

If your endpoint returns a non-2xx status code or times out, Trix will retry the delivery:

  • Retry schedule: 1 minute, 5 minutes, 30 minutes, 2 hours, 24 hours
  • Timeout: 30 seconds per request
  • Max attempts: 6 total (1 initial + 5 retries)

After all retries are exhausted, the webhook is marked as failed. You can view failed deliveries in the dashboard or via the API.

Handling Duplicates

Use the X-Trix-Delivery header to deduplicate events. Store processed delivery IDs and skip duplicates:

idempotency.ts
const processedDeliveries = new Set();

function handleWebhook(req) {
  const deliveryId = req.headers['x-trix-delivery'];

  if (processedDeliveries.has(deliveryId)) {
    console.log('Duplicate delivery, skipping');
    return;
  }

  // Process the event
  processEvent(req.body);

  // Mark as processed
  processedDeliveries.add(deliveryId);
}

Managing Webhooks

List Webhooks

list-webhooks.sh
curl https://api.trixdb.com/v1/webhooks \
  -H "Authorization: Bearer YOUR_API_KEY"

Update a Webhook

update-webhook.sh
curl -X PATCH https://api.trixdb.com/v1/webhooks/whk_abc123 \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": ["memory.created"],
    "status": "paused"
  }'

Delete a Webhook

delete-webhook.sh
curl -X DELETE https://api.trixdb.com/v1/webhooks/whk_abc123 \
  -H "Authorization: Bearer YOUR_API_KEY"

Test a Webhook

Send a test event to verify your endpoint is working:

test-webhook.sh
curl -X POST https://api.trixdb.com/v1/webhooks/whk_abc123/test \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "memory.created"
  }'

Best Practices

  • Respond quickly: Return a 200 status immediately, then process the event asynchronously. Long-running handlers may cause timeouts.
  • Handle retries gracefully: Make your handler idempotent using the delivery ID to prevent duplicate processing.
  • Use a queue: For high-volume webhooks, push events to a queue (Redis, SQS, etc.) and process them with workers.
  • Monitor failures: Set up alerts for webhook failures and review the delivery logs regularly.
  • Rotate secrets: Periodically rotate your webhook secrets and update your verification code.