# Webhooks (/webhooks)

Plunk can send real-time HTTP requests to your application when specific events occur, such as email bounces, spam complaints, or custom events. This is done by creating a [workflow](/workflows) that uses the **Webhook** step to forward event data to your own endpoint.

## How it works [#how-it-works]

Webhooks in Plunk are powered by the workflow system. The basic flow is:

1. An event occurs in Plunk (e.g. an email bounces, a contact subscribes, or a custom event is tracked)
2. A workflow is triggered by that event
3. The workflow executes a **Webhook** step, sending an HTTP request to your URL with relevant data

This means you can receive notifications for any event Plunk tracks, including both system events and your own custom events.

Plunk emits its own events for email delivery, subscriptions and segment membership, and forwards any custom event you track. The full list, with the payload each one sends, is in [Webhook events](/webhook-events).

## Setting up a webhook [#setting-up-a-webhook]

<Component>
<Component>
### Create the workflow [#create-the-workflow]

Navigate to the **Workflows** section in the dashboard and create a new workflow. Choose the event you want to listen for as the trigger. For example, to receive notifications when an email bounces, use `email.bounce` as the trigger event.
</Component>

<Component>
### Add a Webhook step [#add-a-webhook-step]

After the trigger, add a **Webhook** step and configure it:

- **URL**: The endpoint on your server that will receive the webhook (e.g. `https://api.example.com/webhooks/plunk`)
- **Method**: The HTTP method to use. Defaults to `POST`, which is recommended for most use cases.
- **Headers** (optional): Custom headers to include in the request, provided as JSON. This is useful for authentication.

```json
{
  "Authorization": "Bearer your-secret-token"
}
```

- **Body** (optional): Custom request body. When omitted, Plunk sends the [default payload](/webhook-events#webhook-payload). When provided, the value replaces the default payload entirely and is JSON-encoded before being sent.
</Component>

<Component>
### Use variables in the request (optional) [#use-variables-in-the-request-optional]

The `url`, header values, and `body` all support `{{variable}}` interpolation. The available scope is the same as `SEND_EMAIL` templates, plus a webhook-only `event` namespace exposing the trigger event payload:

| Variable                                                  | Value                                                                       |
| --------------------------------------------------------- | --------------------------------------------------------------------------- |
| `{{id}}`, `{{email}}`                                     | The contact's ID and email.                                                 |
| `{{<key>}}` (top-level)                                   | Any key from the contact's `data` JSON (e.g. `{{firstName}}`, `{{plan}}`).  |
| `{{data.<key>}}`                                          | The same contact data, addressed via the `data` namespace.                  |
| `{{event.<key>}}`                                         | Webhook-only. Fields from the trigger event payload (e.g. `{{event.subject}}`). |
| `{{<key>}}` (from execution context)                      | Keys passed in as `context` when starting a `MANUAL` execution.             |
| `{{unsubscribeUrl}}`, `{{subscribeUrl}}`, `{{manageUrl}}` | Per-contact subscription management URLs.                                   |

The HTTP `method` is **not** templated — it must be a literal verb (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`). The `url` must include a static scheme (`http://` or `https://`); placeholders are supported inside the URL but cannot replace the scheme.

Example — forward a contact event to your own API, parameterised by contact data:

**URL**

```text
https://api.example.com/users/{{id}}/events
```

**Headers**

```json
{
  "Authorization": "Bearer your-secret-token"
}
```

**Body**

```json
{
  "email": "{{email}}",
  "plan": "{{plan}}",
  "referrer": "{{event.referrer}}"
}
```
</Component>

<Component>
### Enable the workflow [#enable-the-workflow]

Once configured, enable the workflow. It will start sending webhook requests whenever the trigger event occurs.
</Component>
</Component>

## Correlating webhooks with send requests [#correlating-webhooks-with-send-requests]

All email events include an `emailId` field that matches the Plunk email record ID returned when you send an email via `POST /v1/send`. This allows you to directly correlate webhook events with your API requests.

**Example workflow:**

1. Send email via API:

```json
POST /v1/send
{
  "to": "user@example.com",
  "subject": "Welcome",
  "body": "Hello!"
}

Response:
{
  "success": true,
  "data": {
    "emails": [
      {
        "contact": {"id": "cnt_abc", "email": "user@example.com"},
        "email": "ac32f08e-c6b9-45d3-9824-a73dff1e3bbf"
      }
    ]
  }
}
```

2. Store the `email` ID (`ac32f08e-c6b9-45d3-9824-a73dff1e3bbf`) in your database

3. When webhook events fire (e.g., `email.open`, `email.bounce`), match them using `event.emailId`:

```json
{
  "event": {
    "emailId": "ac32f08e-c6b9-45d3-9824-a73dff1e3bbf",
    "messageId": "ses-message-id",
    "openedAt": "2025-01-15T11:00:00.000Z"
  }
}
```

This eliminates the need to match by contact email + timestamp or to listen for `email.sent` webhooks just to get the provider `messageId`.

## Common use cases [#common-use-cases]

### Bounce and complaint monitoring [#bounce-and-complaint-monitoring]

Create a workflow triggered by `email.bounce` or `email.complaint` to forward these events to your application. This allows you to keep your own database in sync with Plunk's contact statuses.

You can use additional workflow steps before the webhook to add logic:

- **Condition**: Only send the webhook for hard bounces by checking the `bounceType` field
- **Delay**: Add a short delay to batch-process related events
- **Update Contact**: Mark the contact with metadata before sending the webhook

### Syncing unsubscribes [#syncing-unsubscribes]

Trigger a workflow on `contact.unsubscribed` to notify your application when a contact opts out. This is useful for keeping subscription status synchronized across multiple systems.

### Custom event forwarding [#custom-event-forwarding]

If you track custom events in Plunk (e.g. `user.signup`, `order.completed`), you can forward those same events to other services via webhooks. This turns Plunk into an event router — track once, distribute to multiple endpoints.

## Receiving webhooks safely [#receiving-webhooks-safely]

Plunk's webhook step has a few characteristics worth knowing when you build the receiving endpoint:

- **Method**: defaults to `POST` with `Content-Type: application/json`. You can override the method per step.
- **Timeout**: each request times out after **10 seconds**. Long-running endpoints should accept the request, queue the work, and return `2xx` quickly.
- **Redirects**: up to 5 redirects are followed. Each hop is re-validated against the SSRF rules below.
- **Public URL required**: your webhook endpoint must be reachable on the public internet. Webhooks pointed at private or internal addresses (loopback, RFC 1918 ranges, etc.) won't be delivered.
- **Schemes**: only `http://` and `https://` are accepted. Prefer HTTPS.
- **No automatic retries**: a non-2xx response or timeout fails the workflow step. Build idempotency into your handler and use workflow logic (a `WAIT_FOR_EVENT` step, a fallback branch) if you need retry semantics.
- **Verify authenticity with a shared secret**: configure a secret header on the webhook step and check it on your endpoint:

  ```json
  // Webhook step → Headers
  {
    "Authorization": "Bearer your-shared-secret"
  }
  ```

  The secret travels with every request from that step. Rotate it like any other shared secret. Prefer this over IP allowlisting — egress IPs can change.

## Adding conditions and delays [#adding-conditions-and-delays]

Since webhooks are part of the workflow system, you can combine them with other step types for more advanced setups:

- Use a **Condition** step to only fire the webhook when certain criteria are met (e.g. only notify for contacts on a specific plan)
- Use a **Wait for Event** step to wait for a follow-up event before sending the webhook (e.g. wait to see if a bounced contact re-subscribes)
- Use a **Delay** step to add a time buffer before the webhook fires