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

# Webhooks Overview

> Send real-time notifications to external services when API requests are made through your routes. React to successes, failures, and other events.

# Webhooks Overview

Webhooks let you send real-time notifications to external services whenever requests pass through your KnoxCall routes. Use them to trigger workflows, update databases, send alerts, or integrate with third-party services.

## What Are Webhooks?

**Webhooks** are outbound HTTP requests that KnoxCall sends to your specified endpoint when certain events occur.

**How it works:**

```text theme={"dark"}
Client Request → KnoxCall Route → Backend API
                      ↓
              Webhook Triggered
                      ↓
         Your Webhook Endpoint (Slack, Zapier, custom server, etc.)
```

**Example use case:**

```text theme={"dark"}
Route: payment-api
Event: request.server_error (5xx)
Webhook URL: https://hooks.slack.com/services/...
Result: Slack notification when payment API fails
```

## Event Types

KnoxCall supports 8 event types that follow a Stripe-like naming convention:

| Event Type             | Triggers When               | Example Use Case              |
| ---------------------- | --------------------------- | ----------------------------- |
| `request.received`     | Request arrives at KnoxCall | Logging, real-time dashboards |
| `request.success`      | 2xx response received       | Analytics, success tracking   |
| `request.redirect`     | 3xx response received       | Redirect monitoring           |
| `request.client_error` | 4xx response received       | Invalid request tracking      |
| `request.server_error` | 5xx response received       | Error alerting                |
| `request.timeout`      | Request times out           | Timeout monitoring            |
| `request.error`        | Any non-2xx response        | General error handling        |
| `request.completed`    | Any response completed      | Comprehensive logging         |

<Info>
  **Combine event types**: You can subscribe a single webhook to multiple event types. For example, subscribe to both `request.success` and `request.server_error` to track all outcomes.
</Info>

## Webhook Payload

When an event occurs, KnoxCall sends a JSON payload to your endpoint:

```json theme={"dark"}
{
  "event": "request.success",
  "timestamp": "2025-01-15T10:30:45.123Z",
  "webhook_id": "wh_abc123",
  "webhook_name": "Slack Notifications",
  "data": {
    "route_id": "route_xyz789",
    "route_name": "payment-api",
    "environment": "production",
    "request": {
      "method": "POST",
      "path": "/v1/charges",
      "ip": "52.123.45.67",
      "headers": { "content-type": "application/json" },
      "body": { "amount": 1000, "currency": "usd" }
    },
    "response": {
      "status": 200,
      "headers": { "content-type": "application/json" },
      "body": { "id": "ch_abc123", "status": "succeeded" },
      "latency_ms": 342
    }
  }
}
```

### Payload Configuration

Control what's included in your webhook payload:

| Option                | Default | Description                       |
| --------------------- | ------- | --------------------------------- |
| Include Request Body  | Yes     | Include the original request body |
| Include Response Body | Yes     | Include the backend response body |
| Include Headers       | No      | Include request/response headers  |
| Include Status Code   | Yes     | Include HTTP status code          |

<Warning>
  **Sensitive data**: When including headers, sensitive headers like `Authorization`, `X-API-Key`, and `Cookie` are automatically redacted for security.
</Warning>

## Authentication Methods

Secure your webhook endpoints with multiple authentication options:

### Bearer Token

```text theme={"dark"}
Authorization: Bearer your-secret-token
```

### Basic Auth

```text theme={"dark"}
Authorization: Basic base64(username:password)
```

### Custom Header

```text theme={"dark"}
X-Custom-Auth: your-secret-value
```

### HMAC Signature

Every webhook includes an HMAC-SHA256 signature for verification:

```text theme={"dark"}
X-Webhook-Signature: sha256=abc123...
```

Verify the signature on your server:

```javascript theme={"dark"}
const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(JSON.stringify(payload))
    .digest('hex');

  return `sha256=${expectedSignature}` === signature;
}
```

## Headers Sent

KnoxCall includes these headers with every webhook request:

| Header                | Description                                     |
| --------------------- | ----------------------------------------------- |
| `Content-Type`        | Always `application/json`                       |
| `X-Webhook-Signature` | HMAC-SHA256 signature for verification          |
| `X-Webhook-ID`        | Unique identifier for the webhook configuration |
| `X-Webhook-Event`     | Event type (e.g., `request.success`)            |
| `User-Agent`          | `KnoxCall-Webhook/1.0`                          |

Plus any custom headers you configure.

## Route Filtering

Limit webhooks to specific routes:

**All routes (default):**

```text theme={"dark"}
Route Filter: (empty)
→ Triggers for all routes in your tenant
```

**Specific routes:**

```text theme={"dark"}
Route Filter: ["route_abc123", "route_def456"]
→ Only triggers for these two routes
```

**Use case:** Create separate webhooks for different integrations:

* `payment-webhook`: Only payment-related routes → Slack #payments
* `auth-webhook`: Only authentication routes → Security monitoring tool

## Retry Logic

When a webhook delivery fails, KnoxCall can automatically retry:

**Configuration:**

* **Retry on Failure**: Enable/disable retries
* **Max Retries**: 0-5 attempts (default: 3)

**Backoff schedule:**

```text theme={"dark"}
Attempt 1: Immediate
Attempt 2: 1 second delay
Attempt 3: 2 seconds delay
Attempt 4: 4 seconds delay
Attempt 5: 8 seconds delay
```

**Success criteria:** HTTP 2xx response

<Note>
  Webhooks are dispatched **asynchronously** (fire-and-forget). They don't block or slow down the proxied request.
</Note>

## Webhook Logs

Track all webhook executions in the webhook logs:

**What's logged:**

* Execution timestamp
* Event type
* HTTP method and URL
* Sent headers and body
* Response status and body
* Response time (ms)
* Success/failure status
* Error messages (if failed)
* Retry count
* Linked request ID

**Filter logs by:**

* Webhook ID
* Success/failure status
* Event type
* Date range
* Request ID (to correlate with API logs)

## Common Use Cases

### 1. Error Alerting (Slack)

```text theme={"dark"}
Event: request.server_error
URL: https://hooks.slack.com/services/...
Include: Status code, route name, error message
```

### 2. Analytics/Logging

```text theme={"dark"}
Event: request.completed
URL: https://your-analytics.com/ingest
Include: All data (full request/response)
```

### 3. Workflow Automation (Zapier)

```text theme={"dark"}
Event: request.success
URL: https://hooks.zapier.com/hooks/catch/...
Include: Request body, response body
```

### 4. Security Monitoring

```text theme={"dark"}
Event: request.client_error (401, 403)
URL: https://your-security-tool.com/api
Include: Request headers, IP address
```

### 5. Real-time Dashboards

```text theme={"dark"}
Event: request.received
URL: wss://your-dashboard.com/ws
Include: Route name, timestamp
```

## Performance Considerations

* **Non-blocking**: Webhooks are dispatched asynchronously
* **Parallel dispatch**: Multiple webhooks for the same event run in parallel
* **Timeout**: Configurable timeout (1-60 seconds, default: 30)
* **No impact on latency**: Webhook failures don't affect the proxied request

## Next Steps

<CardGroup cols={2}>
  <Card title="Creating Webhooks" icon="plus" href="/webhooks/creating-webhooks">
    Step-by-step webhook setup guide
  </Card>

  <Card title="Testing Webhooks" icon="flask" href="/webhooks/testing-webhooks">
    How to test your webhook configuration
  </Card>

  <Card title="Webhook Logs" icon="list" href="/webhooks/webhook-logs">
    Viewing and debugging webhook executions
  </Card>

  <Card title="API Logs" icon="file-lines" href="/monitoring/api-logs">
    Correlate webhooks with API requests
  </Card>
</CardGroup>

***

<CardGroup cols={2}>
  <Card title="Statistics" icon="chart-line">
    * **Level**: intermediate
    * **Time**: 8 minutes
  </Card>

  <Card title="Tags" icon="tags">
    `webhooks`, `notifications`, `events`, `integrations`, `slack`, `zapier`
  </Card>
</CardGroup>
