> ## Documentation Index
> Fetch the complete documentation index at: https://composio-preview.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Receiving events

> Get trigger events locally with an SDK subscription or in production over your webhook URL

Once a trigger is active, its events come to you as the same payload, whether you're testing locally or running in production. Develop against your local handler first, then point Composio at your production URL when you ship.

## Receive events locally

While developing, you want trigger events on your machine. The best option forwards them to the real webhook handler you'll run in production, so you test the exact path (including `parse()` and signature verification) before you ship.

### Quick look with `subscribe()`

`subscribe()` streams events straight to your process over a WebSocket, with no webhook URL, no tunnel, and no signing. It's the fastest way to eyeball what a trigger sends, but it bypasses your real webhook handler. Use it only for basic prototyping; for anything you intend to ship, forward events to your handler with one of the options below.

> [!NOTE]
>
> Under the hood `subscribe()` opens the WebSocket via [Pusher](https://pusher.com/). This is an implementation detail, but worth knowing if your runtime restricts WebSocket clients — prefer the webhook/forwarding options below for anything you ship.

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio()
>
> subscription = composio.triggers.subscribe()
>
> @subscription.handle(trigger_id="your_trigger_id")
> def handle_event(data):
>     print(f"Event received: {data}")
>
> subscription.wait_forever()
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
>
> const composio = new Composio();
>
> await composio.triggers.subscribe(
>   data => {
>     console.log('Event received:', data);
>   },
>   { triggerId: 'your_trigger_id' }
> );
> ```

Filter the stream by `triggerId`, `triggerSlug`, `connectedAccountId`, `toolkits`, or `userId`, or pass no filters to receive every trigger event in the project.

Subscription failures (for example a rejected auth request) do not reject the `subscribe()` promise in TypeScript — Pusher reports them asynchronously after it resolves. Pass an error callback to react to them programmatically: the `on_subscription_error` keyword in Python, or an optional third argument in TypeScript. In Python, failures raised while establishing the subscription (such as an auth rejection) invoke the callback and then re-raise from `subscribe()` instead of timing out.

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio()
>
> subscription = composio.triggers.subscribe(
>     on_subscription_error=lambda error: print("Trigger subscription failed:", error)
> )
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
>
> const composio = new Composio();
> await composio.triggers.subscribe(
>   data => {
>     console.log('Event received:', data);
>   },
>   {},
>   error => {
>     console.error('Trigger subscription failed:', error);
>   }
> );
> ```

### Forward to your local handler with the CLI (recommended)

The Composio CLI streams realtime events and forwards each one to your local URL, signed exactly like production. No public URL, no tunnel, and it runs your real handler (and [`parse()`](#handling-events)) end to end.

```bash theme={null}
composio dev triggers listen --forward "http://localhost:8000/webhooks/composio"
```

Events are signed with `COMPOSIO_WEBHOOK_SECRET` if it's set, otherwise the CLI prints a generated secret to verify against. Filter the stream with `--toolkits`, `--trigger-slug`, or `--trigger-id`, and tee events to a file with `--out events.jsonl`.

### Cloudflare Tunnel

Expose your local server with [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/), no account needed for quick runs:

```bash theme={null}
cloudflared tunnel --url http://localhost:8000
```

Register the printed `trycloudflare.com` URL as your [webhook URL](#receive-events-in-production), then events reach your handler at `http://localhost:8000/webhooks/composio`.

### ngrok

Expose your local server with [ngrok](https://ngrok.com):

```bash theme={null}
ngrok http 8000
```

Register the printed `ngrok-free.app` URL as your [webhook URL](#receive-events-in-production) the same way.

## Receive events in production

Register your webhook URL once per project. Composio then `POST`s every trigger event to it. Set it from the SDK:

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio()
>
> subscription = composio.triggers.set_webhook_subscription(
>     webhook_url="https://your-app.com/webhooks/composio",
> )
> print(f"Delivering events to {subscription['webhook_url']}")
> # Store subscription['secret'] to verify signatures
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
>
> const composio = new Composio();
>
> const subscription = await composio.triggers.setWebhookSubscription({
>   webhookUrl: 'https://your-app.com/webhooks/composio',
> });
> console.log(`Delivering events to ${subscription.webhookUrl}`);
> // Store subscription.secret to verify signatures
> ```

> [tab] API
>
> ```bash theme={null}
> # Creates the project subscription. If one already exists (409), update it with
> # PATCH /api/v3.1/webhook_subscriptions/{id} instead, as the SDK does.
> curl -s -X POST https://backend.composio.dev/api/v3.1/webhook_subscriptions \
>   -H "x-api-key: $COMPOSIO_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{"webhook_url": "https://your-app.com/webhooks/composio", "enabled_events": ["composio.trigger.message"], "version": "V3"}' \
>   | jq '{webhook_url, secret}'
> # Store the secret to verify signatures
> ```

Your webhook endpoint must be publicly reachable. Composio's outbound IPs are dynamic, so IP allowlists and VPN-only endpoints won't work. Authenticate payloads with [signature verification](#verifying-signatures) instead.

### Manage project subscriptions

Use `composio.webhooks.subscriptions` to manage outbound delivery from your project. Both SDKs provide `list()`, `get()`, `set()`, `update()`, and `delete()`. Rotate signing secrets with `rotate_secret()` in Python or `rotateSecret()` in TypeScript, and discover supported events with `list_event_types()` or `listEventTypes()`.

For inbound events from a provider's OAuth app, use [webhook endpoints](https://composio-preview.mintlify.site/docs/setting-up-triggers/custom-oauth-webhooks.md).

## Handling events

In your handler, pass the incoming request to `parse()`. It returns the typed, normalized payload. Pass `verifySecret` and it verifies the signature first, so one call both authenticates and parses.

> [tab] Python
>
> ```python theme={null}
> import os
> from composio import Composio
>
> composio = Composio()
>
> @app.post("/webhooks/composio")
> async def webhook_handler(request: Request):
>     # On async frameworks (FastAPI) read the raw body and pass body=/headers=.
>     # On sync frameworks (Flask, Django) you can pass the request directly.
>     # Use the raw body so the signature verifies. Omit verify_secret to skip it.
>     result = composio.triggers.parse(
>         body=await request.body(),
>         headers=request.headers,
>         verify_secret=os.environ["COMPOSIO_WEBHOOK_SECRET"],
>     )
>
>     if result["raw_payload"].get("type") == "composio.trigger.message":
>         event = result["payload"]
>         if event["trigger_slug"] == "GITHUB_COMMIT_EVENT":
>             data = event["payload"]
>             print(f"New commit by {data['author']}: {data['message']}")
>
>     return {"status": "ok"}
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
>
> const composio = new Composio();
>
> // Next.js App Router, Hono, or any Fetch-style handler
> export async function POST(request: Request) {
>   // parse() takes a Fetch Request (shown) or an Express-style { body, headers }.
>   // Pass the raw body so the signature verifies; omit verifySecret to skip it.
>   const result = await composio.triggers.parse(request, {
>     verifySecret: process.env.COMPOSIO_WEBHOOK_SECRET,
>   });
>
>   if (result.rawPayload.type === 'composio.trigger.message') {
>     const event = result.payload;
>     if (event.triggerSlug === 'GITHUB_COMMIT_EVENT') {
>       const data = event.payload;
>       console.log(`New commit by ${data.author}: ${data.message}`);
>     }
>   }
>
>   return Response.json({ status: 'ok' });
> }
> ```

> [!NOTE]
>
> Composio delivers other project events (like [connection expiry](https://composio-preview.mintlify.site/docs/authentication#connection-lifecycle)) to this same URL. `parse()` returns those too. Route on `result.payload.triggerSlug` and ignore what you don't handle.

### Inspecting trigger payload schemas

Each trigger type declares the shape of the `data` it sends. Inspect it before you write your handler:

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio()
>
> trigger_type = composio.triggers.get_type("GITHUB_COMMIT_EVENT")
> print(trigger_type.payload)
> # {"properties": {"author": {...}, "id": {...}, "message": {...}, "timestamp": {...}, "url": {...}}}
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
>
> const composio = new Composio();
>
> const triggerType = await composio.triggers.getType('GITHUB_COMMIT_EVENT');
> console.log(triggerType.payload);
> // {"properties": {"author": {...}, "id": {...}, "message": {...}, "timestamp": {...}, "url": {...}}}
> ```

> [tab] API
>
> ```bash theme={null}
> curl -s -X GET https://backend.composio.dev/api/v3.1/triggers_types/GITHUB_COMMIT_EVENT \
>   -H "x-api-key: $COMPOSIO_API_KEY" | jq '.payload'
> # {"properties": {"author": {...}, "id": {...}, "message": {...}, "timestamp": {...}, "url": {...}}}
> ```

From the CLI, inspect a single trigger type's config and payload schema:

```bash theme={null}
composio triggers info "GITHUB_COMMIT_EVENT"
```

Or generate typed stubs for your project (scope to the toolkits you use with `--toolkits`), so your handler is type-checked against the trigger's payload:

```bash theme={null}
composio generate --toolkits github   # auto-detects TypeScript or Python
```

### Webhook payload shape

Every trigger event arrives in the same envelope. `metadata` tells you where the event came from; `data` holds the event itself, in the shape the trigger type declares.

```json theme={null}
{
  "id": "msg_abc123",
  "type": "composio.trigger.message",
  "metadata": {
    "log_id": "log_abc123",
    "trigger_slug": "GITHUB_COMMIT_EVENT",
    "trigger_id": "ti_xyz789",
    "connected_account_id": "ca_def456",
    "auth_config_id": "ac_xyz789",
    "user_id": "user-id-123435"
  },
  "data": {
    "commit_sha": "a1b2c3d",
    "message": "fix: resolve null pointer",
    "author": "jane"
  },
  "timestamp": "2026-01-15T10:30:00Z"
}
```

| `metadata` field | What it tells you |
| - | - |
| `trigger_id` | Which trigger instance fired this event |
| `trigger_slug` | The trigger type (for example `GITHUB_COMMIT_EVENT`) |
| `connected_account_id` | Which connected account it belongs to |
| `user_id` | Which user it's for |
| `auth_config_id` | Which auth config was used |

> [!NOTE]
>
> This is the V3 payload, the default for new organizations. See [webhook payload versions](#webhook-payload-versions) for V2 and V1.

## Verifying signatures

Composio signs every webhook request. `parse({ verifySecret })` verifies the signature for you (and `verifyWebhook()` does the same at a lower level), so most handlers need nothing more. You only need this section if you're **not** using the Composio SDK.

> [!NOTE]
>
> Store the webhook secret securely as `COMPOSIO_WEBHOOK_SECRET`. Fetch it from the [webhook subscription](https://composio-preview.mintlify.site/reference/api-reference/webhook-subscriptions/getWebhookSubscriptionsById.md) any time, or [rotate it](https://composio-preview.mintlify.site/reference/api-reference/webhook-subscriptions/postWebhookSubscriptionsByIdRotateSecret.md) if it leaks.

Every request includes `webhook-signature`, `webhook-id`, and `webhook-timestamp` headers. Compute `HMAC-SHA256` over `{webhook-id}.{webhook-timestamp}.{rawBody}` with your secret and compare it against the signature:

> [tab] Python
>
> ```python theme={null}
> import hmac
> import hashlib
> import base64
> import json
> import os
>
> def verify_webhook(webhook_id: str, webhook_timestamp: str, body: str, signature: str) -> dict:
>     secret = os.getenv("COMPOSIO_WEBHOOK_SECRET", "")
>     signing_string = f"{webhook_id}.{webhook_timestamp}.{body}"
>     expected = base64.b64encode(
>         hmac.new(secret.encode(), signing_string.encode(), hashlib.sha256).digest()
>     ).decode()
>     received = signature.split(",", 1)[1] if "," in signature else signature
>     if not hmac.compare_digest(expected, received):
>         raise ValueError("Invalid webhook signature")
>
>     payload = json.loads(body)
>     # V3 payload
>     return {
>         "trigger_slug": payload["metadata"]["trigger_slug"],
>         "data": payload["data"],
>     }
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import crypto from 'crypto';
> function verifyWebhook(
>   webhookId: string,
>   webhookTimestamp: string,
>   body: string,
>   signature: string
> ) {
>   const secret = process.env.COMPOSIO_WEBHOOK_SECRET ?? '';
>   const signingString = `${webhookId}.${webhookTimestamp}.${body}`;
>   const expected = crypto
>     .createHmac('sha256', secret)
>     .update(signingString)
>     .digest('base64');
>   const received = signature.split(',')[1] ?? signature;
>   if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received))) {
>     throw new Error('Invalid webhook signature');
>   }
>
>   const payload = JSON.parse(body);
>   // V3 payload
>   return {
>     triggerSlug: payload.metadata.trigger_slug,
>     data: payload.data,
>   };
> }
> ```

> [!NOTE]
>
> Reject requests whose `webhook-timestamp` is too old to block replays. The SDK's `parse()` and `verifyWebhook()` enforce a 300-second tolerance by default; pass `tolerance` to change it, or `0` to disable the check.

## Webhook payload versions

`parse()` and `verifyWebhook()` auto-detect the version. If you process payloads manually, here are the formats:

> [tab] V3 (default)
>
> Metadata is separated from event data. New organizations receive V3 payloads by default.
>
> ```json theme={null}
> {
>   "id": "msg_abc123",
>   "type": "composio.trigger.message",
>   "metadata": {
>     "log_id": "log_abc123",
>     "trigger_slug": "GITHUB_COMMIT_EVENT",
>     "trigger_id": "ti_xyz789",
>     "connected_account_id": "ca_def456",
>     "auth_config_id": "ac_xyz789",
>     "user_id": "user-id-123435"
>   },
>   "data": {
>     "commit_sha": "a1b2c3d",
>     "message": "fix: resolve null pointer",
>     "author": "jane"
>   },
>   "timestamp": "2026-01-15T10:30:00Z"
> }
> ```

> [tab] V2 (legacy)
>
> Metadata fields are mixed into the `data` object alongside event data.
>
> ```json theme={null}
> {
>   "type": "github_commit_event",
>   "data": {
>     "commit_sha": "a1b2c3d",
>     "message": "fix: resolve null pointer",
>     "author": "jane",
>     "connection_id": "ca_def456",
>     "connection_nano_id": "cn_abc123",
>     "trigger_nano_id": "tn_xyz789",
>     "trigger_id": "ti_xyz789",
>     "user_id": "user-id-123435"
>   },
>   "timestamp": "2026-01-15T10:30:00Z",
>   "log_id": "log_abc123"
> }
> ```

> [tab] V1 (legacy)
>
> ```json theme={null}
> {
>   "trigger_name": "github_commit_event",
>   "trigger_id": "ti_xyz789",
>   "connection_id": "ca_def456",
>   "payload": {
>     "commit_sha": "a1b2c3d",
>     "message": "fix: resolve null pointer",
>     "author": "jane"
>   },
>   "log_id": "log_abc123"
> }
> ```

## Next

> [card] [Managing triggers](https://composio-preview.mintlify.site/docs/setting-up-triggers/managing-triggers.md)
>
> List, enable, disable, and delete trigger instances
