# Webhooks

Every Stream product can deliver events to your server using webhooks, SQS or SNS.
When setting up a hook you can specify the exact events you want to receive, or select to receive all events.

To ensure that a webhook is triggered by Stream you can verify its signature.
Webhook retries are in place. If you want to ensure an outage in your API never loses an event, it's better to use SQS or SNS for reliability.

The configuration can be done using the API or from the Dashboard. Some important points to consider:

- The selection of events you want to receive applies to all the endpoints you have configured.
- You can configure multiple endpoints for the same app (eg. AWS SNS and HTTP Webhook).
- If your app is configured to receive all events, you can still filter the events you want to receive in your webhook handler.
- If your app is configured to receive all events, newly introduced event types will be sent to your webhook handler by default.
- If you pick specific events, newly introduced event types will not be sent to your webhook handler by default (you can still manually add them later on).

<Admonition type="info">

Event types and payloads are documented per product: [Chat events](https://getstream.io/chat/docs/node/webhook-events/), [Video events](https://getstream.io/video/docs/api/webhooks/events/) and [Moderation events](https://getstream.io/moderation/docs/node/content-moderation/webhooks/).

</Admonition>

## Configuring Hooks

Here's how to quickly set up webhooks using the `event_hooks` configuration:

### Subscribe to Specific Events

<Tabs>

```js label="JavaScript"
// Subscribe to message.new and message.updated events only
await client.updateAppSettings({
  event_hooks: [
    {
      enabled: true,
      hook_type: "webhook",
      webhook_url: "https://example.com/webhooks/stream/messages",
      event_types: ["message.new", "message.updated"],
    },
  ],
});
```

```python label="Python"
from getstream.models import EventHook

# Subscribe to message.new and message.updated events only
client.update_app(
    event_hooks=[
        EventHook(
            enabled=True,
            hook_type="webhook",
            webhook_url="https://example.com/webhooks/stream/messages",
            event_types=["message.new", "message.updated"],
        )
    ]
)
```

```ruby label="Ruby"
require 'getstream_ruby'
Models = GetStream::Generated::Models

# Subscribe to message.new and message.updated events only
client.common.update_app(Models::UpdateAppRequest.new(
  event_hooks: [
    {
      'enabled' => true,
      'hook_type' => 'webhook',
      'webhook_url' => 'https://example.com/webhooks/stream/messages',
      'event_types' => ['message.new', 'message.updated']
    }
  ]
))
```

```php label="PHP"
// Subscribe to message.new and message.updated events only
$client->updateApp(new Models\UpdateAppRequest(
    eventHooks: [
        new Models\EventHook(
            enabled: true,
            hookType: "webhook",
            webhookUrl: "https://example.com/webhooks/stream/messages",
            eventTypes: ["message.new", "message.updated"],
        ),
    ],
));
```

```go label="Go"
// Subscribe to message.new and message.updated events only
client.UpdateApp(ctx, &getstream.UpdateAppRequest{
  EventHooks: []getstream.EventHook{
    {
      HookType:   getstream.PtrTo("webhook"),
      Enabled:    getstream.PtrTo(true),
      EventTypes: []string{"message.new", "message.updated"},
      WebhookUrl: getstream.PtrTo("https://example.com/webhooks/stream/messages"),
    },
  },
})
```

```csharp label="C#"
// Subscribe to message.new and message.updated events only
var webhookHook = new EventHook
{
    HookType = "webhook",
    Enabled = true,
    EventTypes = new List<string> { "message.new", "message.updated" },
    WebhookUrl = "https://example.com/webhooks/stream/messages",
};

await client.UpdateAppAsync(new UpdateAppRequest
{
    EventHooks = new List<EventHook> { webhookHook },
});
```

```java label="Java"
// Subscribe to message.new and message.updated events only
var webhookHook = EventHook.builder()
    .hookType("webhook")
    .enabled(true)
    .eventTypes(List.of("message.new", "message.updated"))
    .webhookUrl("https://example.com/webhooks/stream/messages")
    .build();

client.updateApp(UpdateAppRequest.builder()
    .eventHooks(List.of(webhookHook))
    .build()).execute();
```

</Tabs>

### Subscribe to All Events

Use an empty `event_types` array to receive all existing and future events:

<Tabs>

```js label="JavaScript"
// Subscribe to all events (empty array = all events)
await client.updateAppSettings({
  event_hooks: [
    {
      enabled: true,
      hook_type: "webhook",
      webhook_url: "https://example.com/webhooks/stream/all",
      event_types: [], // empty array = all events
    },
  ],
});
```

```python label="Python"
from getstream.models import EventHook

# Subscribe to all events (empty list = all events)
client.update_app(
    event_hooks=[
        EventHook(
            enabled=True,
            hook_type="webhook",
            webhook_url="https://example.com/webhooks/stream/all",
            event_types=[],  # empty list = all events
        )
    ]
)
```

```ruby label="Ruby"
require 'getstream_ruby'
Models = GetStream::Generated::Models

# Subscribe to all events (empty array = all events)
client.common.update_app(Models::UpdateAppRequest.new(
  event_hooks: [
    {
      'enabled' => true,
      'hook_type' => 'webhook',
      'webhook_url' => 'https://example.com/webhooks/stream/all',
      'event_types' => [] # empty array = all events
    }
  ]
))
```

```php label="PHP"
// Subscribe to all events (empty array = all events)
$client->updateApp(new Models\UpdateAppRequest(
    eventHooks: [
        new Models\EventHook(
            enabled: true,
            hookType: "webhook",
            webhookUrl: "https://example.com/webhooks/stream/all",
            eventTypes: [], // empty array = all events
        ),
    ],
));
```

```go label="Go"
// Subscribe to all events (empty slice = all events)
client.UpdateApp(ctx, &getstream.UpdateAppRequest{
  EventHooks: []getstream.EventHook{
    {
      HookType:   getstream.PtrTo("webhook"),
      Enabled:    getstream.PtrTo(true),
      EventTypes: []string{}, // empty slice = all events
      WebhookUrl: getstream.PtrTo("https://example.com/webhooks/stream/all"),
    },
  },
})
```

```csharp label="C#"
// Subscribe to all events (empty list = all events)
var webhookHook = new EventHook
{
    HookType = "webhook",
    Enabled = true,
    EventTypes = new List<string>(), // empty list = all events
    WebhookUrl = "https://example.com/webhooks/stream/all",
};

await client.UpdateAppAsync(new UpdateAppRequest
{
    EventHooks = new List<EventHook> { webhookHook },
});
```

```java label="Java"
// Subscribe to all events (empty list = all events)
var webhookHook = EventHook.builder()
    .hookType("webhook")
    .enabled(true)
    .eventTypes(Collections.emptyList()) // empty list = all events
    .webhookUrl("https://example.com/webhooks/stream/all")
    .build();

client.updateApp(UpdateAppRequest.builder()
    .eventHooks(List.of(webhookHook))
    .build()).execute();
```

</Tabs>

<Admonition type="caution">

Updating `event_hooks` replaces the whole array. Any previously existing hooks not included in the update will be deleted, so get the current app settings first and send back the complete list including your new hook.

</Admonition>

<Admonition type="info">

For reliable event delivery, you can also configure [SQS](#sqs) or [SNS](#sns) instead of webhooks.

</Admonition>

### Debugging webhook requests with NGROK

The easiest way to debug webhooks is with NGROK.

1. Start NGROK

```bash
brew install ngrok
ngrok http 8000
```

2. Update your webhook URL to the NGROK url

3. Trigger a webhook

4. Open up the ngrok inspector

[http://127.0.0.1:4040/inspect/http](http://127.0.0.1:4040/inspect/http)

## Handling the Webhook

Your webhook handler needs to follow these rules:

- accept HTTP POST requests with JSON payload
- be reachable from the public internet. Tunneling services like Ngrok are supported
- respond with response codes from 200 to 299 as fast as possible
- be idempotent. Stream retries on network or 5xx errors, and retried calls carry the same `X-Webhook-Id` header
- run over HTTPS with Keep-Alive enabled

We highly recommend following common security guidelines to make your webhook integration safe and fast:

- Use HTTPS with a certificate from a trusted authority
- Verify the "X-Signature" header to ensure the request is coming from Stream
- Support HTTP Keep-Alive
- Use a highly available infrastructure such as AWS Elastic Load Balancer, Google Cloud Load Balancer, or similar
- Offload the processing of the message if possible (read, store, and forget)
- When decoding JSON into objects, ensure that your webhook can handle new fields being added to the JSON payload as well as new event types (eg. log unknown fields and event types instead of failing)

All webhook requests contain these headers:

| Name              | Description                                                                                                          | Example                                                          |
| ----------------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| X-Webhook-Id      | Unique ID of the webhook call. This value is consistent between retries and could be used to deduplicate retry calls | 123e4567-e89b-12d3-a456-426614174000                             |
| X-Webhook-Attempt | Number of webhook request attempt starting from 1                                                                    | 1                                                                |
| X-Api-Key         | Your application's API key. Should be used to validate request signature                                             | a1b23cdefgh4                                                     |
| X-Signature       | HMAC signature of the request body. See Signature section                                                            | ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb |

## Verifying and Parsing Events

To verify and parse the event, call `verifyAndParseWebhook` on your Stream client. It transparently decompresses the body when [Payload Compression](#payload-compression) is on (detected from the body bytes, so it works behind middleware that auto-decompresses the request) and verifies the HMAC `X-Signature` header using the API secret the client was constructed with. Every SDK returns a typed event object. Unknown event types fall back to an `UnknownEvent` shape so your handler keeps working when Stream introduces new ones.

Every failure mode (signature mismatch, gzip decompression failure, base64 decode failure, JSON parse failure) raises a single, language-idiomatic webhook error so you only need one `catch` arm. The message text identifies which mode fired, so callers that want to differentiate (security logging, retry policy) can filter on it:

| Language   | Error class                                | Failure-mode messages                                                                                |
| ---------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------- |
| JavaScript | `InvalidWebhookError`                      | `signature mismatch`, `invalid base64 encoding`, `gzip decompression failed`, `invalid JSON payload` |
| Python     | `InvalidWebhookError`                      | same                                                                                                 |
| Ruby       | `StreamChat::Webhook::InvalidWebhookError` | same                                                                                                 |
| PHP        | `InvalidWebhookException`                  | same (`InvalidWebhookException::SIGNATURE_MISMATCH` etc.)                                            |
| Go         | sentinel `getstream.ErrInvalidWebhook`     | same prefixes; use `errors.Is(err, getstream.ErrInvalidWebhook)` for the unified check               |
| Java       | `io.getstream.Webhook.InvalidWebhookError` | same (`Webhook.InvalidWebhookError.SIGNATURE_MISMATCH` etc.)                                         |
| .NET (C#)  | `StreamInvalidWebhookException`            | same (`StreamInvalidWebhookException.SignatureMismatch` etc.)                                        |

Pass the raw body bytes and the `X-Signature` header value. The client already knows your API secret, so the call stays a two-argument one-liner.

<Tabs>

```js label="JavaScript"
// rawBody is the request body as Buffer or string (NOT a parsed JSON object).
// signature is the value of the x-signature header.
// Returns the parsed event object. Throws InvalidWebhookError on any failure.
try {
  const event = client.verifyAndParseWebhook(
    req.rawBody,
    req.headers["x-signature"],
  );
  // event.type, event.user, ...
} catch (err) {
  // err instanceof InvalidWebhookError; err.message identifies the mode
}
```

```python label="Python"
# Django request
event = client.verify_and_parse_webhook(
    request.body,
    request.META["HTTP_X_SIGNATURE"],
)

# Flask request
event = client.verify_and_parse_webhook(
    request.data,
    request.headers["X-Signature"],
)

# event.type, event.user, ...
```

```ruby label="Ruby"
# request_body is the raw request body string/bytes.
# signature is the value of the x-signature header.
event = client.verify_and_parse_webhook(request_body, signature)
# event.type, event.user, ...
```

```php label="PHP"
// $requestBody is the raw request body string.
// $signature is the value of the x-signature header.
$event = $client->verifyAndParseWebhook($requestBody, $signature);
// $event['type'], $event['user'], ...
```

```go label="Go"
// body is the raw request body bytes.
// signature is the value of the x-signature header.
event, err := client.VerifyAndParseWebhookBytes(body, signature)
if err != nil {
    if errors.Is(err, getstream.ErrInvalidWebhook) {
        // err.Error() contains the failure mode (e.g. "signature mismatch", "invalid base64 encoding")
    }
    return
}
// event.Type, event.User, ...

// Or, for net/http handlers that already have an *http.Request, use the
// legacy convenience form that drains the body and reads X-Signature itself:
//   event, err := client.VerifyAndParseWebhook(r)
```

```csharp label="C#"
// requestBody is the raw request body bytes.
// signature is the value of the x-signature header.
var ev = client.VerifyAndParseWebhook(requestBody, signature);
// ev.Type, ev.User, ...
```

```java label="Java"
// body is the raw request body bytes.
// signature is the value of the x-signature header.
var event = client.verifyAndParseWebhook(body, signature);
// event.getType(), event.getUser(), ...
```

</Tabs>

### Where each argument comes from

| Argument           | Source                                                     | Example                                                           |
| ------------------ | ---------------------------------------------------------- | ----------------------------------------------------------------- |
| `body` / `rawBody` | Raw HTTP request body **bytes** (not a parsed JSON object) | `req.rawBody`, `request.body`, `request.data`, `r.Body` (drained) |
| `signature`        | `X-Signature` request header                               | `req.headers["x-signature"]`                                      |

The API secret comes from the client you constructed at startup, so it's never passed into the helper.

<Admonition type="caution">

Pass the **raw body bytes**, before any JSON parsing or string normalization. The helper hashes them as-is. In Express, enable `express.raw({ type: 'application/json' })`; in Django use `request.body`; in Flask use `request.data`; in Go drain `r.Body` once and reuse the bytes. If your framework hands you a parsed object, the signature check fails.

</Admonition>

<Admonition type="note">

**No client handy?** Every SDK also ships the same logic as a stateless static / module-level helper that takes the API secret as an explicit third argument. The instance method is a thin wrapper around it, so the two forms behave identically; pick whichever fits the call site (Lambdas, edge functions, queue consumers, tests).

```js
// JavaScript (getstream-node)
import { Webhook } from "@getstream/node";
const event = Webhook.verifyAndParseWebhook(rawBody, signature, secret);
```

```python
# Python (getstream)
from getstream import webhook
event = webhook.verify_and_parse_webhook(body, signature, secret)
```

```ruby
# Ruby (getstream_ruby): static helper exposed under the StreamChat::Webhook module
event = StreamChat::Webhook.verify_and_parse_webhook(body, signature, secret)
```

```php
// PHP (getstream-php)
$event = \GetStream\Webhook::verifyAndParseWebhook($body, $signature, $secret);
```

```go
// Go (getstream-go): bytes form
event, err := getstream.VerifyAndParseWebhookBytes(body, signature, secret)

// Or, for net/http handlers, the convenience form that takes the request
// (drains the body and reads X-Signature for you):
//   event, err := getstream.VerifyAndParseWebhook(r, secret)
```

```csharp
// C# (getstream-dotnet)
var ev = GetStream.Webhook.VerifyAndParseWebhook(body, signature, secret);
```

```java
// Java (getstream-java)
var event = io.getstream.Webhook.verifyAndParseWebhook(body, signature, secret);
```

</Admonition>

Building this without a Stream SDK? Expand the per-language reference implementation below. Language tabs cover JavaScript, Python, Ruby, PHP, Go, Java and C#.

<Disclosure label="Reference implementation (no SDK)">

The SDK helper is a thin wrapper around three primitives. Re-implement them in your runtime:

| Helper                                              | Purpose                                                                                                                                                            |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `gunzip_payload(body) -> bytes`                     | Detect the [RFC 1952](https://datatracker.ietf.org/doc/html/rfc1952) gzip magic (`1f 8b`) and decompress; pass through unchanged otherwise                         |
| `verify_signature(body, signature, secret) -> bool` | HMAC-SHA256 over the **uncompressed** body. Use constant-time comparison on **HTTP** webhooks; Stream does not attach this app-level signature to SQS/SNS payloads |
| `parse_event(payload) -> Event`                     | Parse JSON. Treat unknown event types as a generic event so handlers don't fail                                                                                    |

`verify_and_parse_webhook(body, signature, secret)` is `parse_event(verify_signature(gunzip_payload(body), …))`. The references below show that composite per language. Drop in your own JSON decoder for `parse_event`.

<Tabs>

```js label="JavaScript"
const crypto = require("crypto");
const zlib = require("zlib");

const GZIP_MAGIC = Buffer.from([0x1f, 0x8b]);

function gunzipPayload(rawBody) {
  const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody);
  if (body.length >= 2 && body.subarray(0, 2).equals(GZIP_MAGIC)) {
    return zlib.gunzipSync(body);
  }
  return body;
}

function verifySignature(body, signature, secret) {
  const expected = crypto
    .createHmac("sha256", secret)
    .update(body)
    .digest("hex");
  const sig = Buffer.from(signature, "utf8");
  const exp = Buffer.from(expected, "utf8");
  return sig.length === exp.length && crypto.timingSafeEqual(sig, exp);
}

function verifyAndParseWebhook(rawBody, signature, secret) {
  const body = gunzipPayload(rawBody);
  if (!verifySignature(body, signature, secret)) {
    throw new Error("invalid webhook signature");
  }
  return JSON.parse(body.toString("utf8"));
}
```

```python label="Python"
import gzip, hmac, hashlib, json

GZIP_MAGIC = b"\x1f\x8b"

def gunzip_payload(body: bytes) -> bytes:
    if isinstance(body, str):
        body = body.encode("utf-8")
    return gzip.decompress(body) if body[:2] == GZIP_MAGIC else body

def verify_signature(body: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)

def verify_and_parse_webhook(body, signature, secret):
    body = gunzip_payload(body)
    if not verify_signature(body, signature, secret):
        raise ValueError("invalid webhook signature")
    return json.loads(body)
```

```ruby label="Ruby"
require 'json'
require 'openssl'
require 'zlib'
require 'stringio'

GZIP_MAGIC = "\x1f\x8b".b.freeze

def gunzip_payload(body)
  body = body.b
  body.start_with?(GZIP_MAGIC) ? Zlib::GzipReader.new(StringIO.new(body)).read : body
end

def verify_signature(body, signature, secret)
  expected = OpenSSL::HMAC.hexdigest('SHA256', secret, body)
  OpenSSL.fixed_length_secure_compare(expected, signature)
end

def verify_and_parse_webhook(body, signature, secret)
  body = gunzip_payload(body)
  raise 'invalid webhook signature' unless verify_signature(body, signature, secret)
  JSON.parse(body)
end
```

```php label="PHP"
function gunzipPayload(string $body): string {
    if (substr($body, 0, 2) === "\x1f\x8b") {
        $decoded = gzdecode($body);
        if ($decoded === false) {
            throw new RuntimeException('gzip decode failed');
        }
        return $decoded;
    }
    return $body;
}

function verifySignature(string $body, string $signature, string $secret): bool {
    return hash_equals(hash_hmac('sha256', $body, $secret), $signature);
}

function verifyAndParseWebhook(string $body, string $signature, string $secret): array {
    $body = gunzipPayload($body);
    if (!verifySignature($body, $signature, $secret)) {
        throw new RuntimeException('invalid webhook signature');
    }
    return json_decode($body, true, flags: JSON_THROW_ON_ERROR);
}
```

```go label="Go"
package webhook

import (
    "bytes"
    "compress/gzip"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "errors"
    "io"
)

var gzipMagic = []byte{0x1f, 0x8b}

func GunzipPayload(body []byte) ([]byte, error) {
    if len(body) < 2 || !bytes.Equal(body[:2], gzipMagic) {
        return body, nil
    }
    gz, err := gzip.NewReader(bytes.NewReader(body))
    if err != nil {
        return nil, err
    }
    defer gz.Close()
    return io.ReadAll(gz)
}

func VerifySignature(body []byte, signature, secret string) bool {
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write(body)
    expected := []byte(hex.EncodeToString(mac.Sum(nil)))
    return hmac.Equal(expected, []byte(signature))
}

func VerifyAndParseWebhook(body []byte, signature, secret string) (map[string]any, error) {
    body, err := GunzipPayload(body)
    if err != nil {
        return nil, err
    }
    if !VerifySignature(body, signature, secret) {
        return nil, errors.New("invalid webhook signature")
    }
    var event map[string]any
    if err := json.Unmarshal(body, &event); err != nil {
        return nil, err
    }
    return event, nil
}
```

```csharp label="C#"
using System;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

public static byte[] GunzipPayload(byte[] body)
{
    if (body.Length >= 2 && body[0] == 0x1f && body[1] == 0x8b)
    {
        using var gz = new GZipStream(new MemoryStream(body), CompressionMode.Decompress);
        using var ms = new MemoryStream();
        gz.CopyTo(ms);
        return ms.ToArray();
    }
    return body;
}

public static bool VerifySignature(byte[] body, string signature, string secret)
{
    using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
    var expected = Encoding.UTF8.GetBytes(Convert.ToHexString(hmac.ComputeHash(body)).ToLowerInvariant());
    return CryptographicOperations.FixedTimeEquals(expected, Encoding.UTF8.GetBytes(signature));
}

public static JsonElement VerifyAndParseWebhook(byte[] body, string signature, string secret)
{
    var payload = GunzipPayload(body);
    if (!VerifySignature(payload, signature, secret))
    {
        throw new InvalidOperationException("invalid webhook signature");
    }
    return JsonSerializer.Deserialize<JsonElement>(payload);
}
```

```java label="Java"
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.zip.GZIPInputStream;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public static byte[] gunzipPayload(byte[] body) throws Exception {
    if (body.length >= 2 && body[0] == 0x1f && (body[1] & 0xff) == 0x8b) {
        try (var gz = new GZIPInputStream(new ByteArrayInputStream(body));
             var out = new ByteArrayOutputStream()) {
            gz.transferTo(out);
            return out.toByteArray();
        }
    }
    return body;
}

public static boolean verifySignature(byte[] body, String signature, String secret) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    byte[] expected = HexFormat.of().formatHex(mac.doFinal(body)).getBytes(StandardCharsets.UTF_8);
    return MessageDigest.isEqual(expected, signature.getBytes(StandardCharsets.UTF_8));
}

public static JsonNode verifyAndParseWebhook(byte[] body, String signature, String secret) throws Exception {
    byte[] payload = gunzipPayload(body);
    if (!verifySignature(payload, signature, secret)) {
        throw new SecurityException("invalid webhook signature");
    }
    return new ObjectMapper().readTree(payload);
}
```

</Tabs>

</Disclosure>

## Retries

In case of the request failure Stream attempts to retry a request. The amount of maximum attempts depends on the kind of the error it receives:

- Response code is 408, 429 or >=500: 3 attempts
- Network error: 2 attempts
- Request timeout: 3 attempts

The timeout of one request is 6 seconds, and the request with all retries cannot exceed the duration of 15 seconds.

When delivery fails after all retry attempts, [event failover](#event-failover) can persist the failed event to a storage backend you control.

## Payload Compression

Enable gzip compression for hook payloads with `enable_hook_payload_compression`. Compressed payloads are typically 70-90% smaller and the decompression cost is negligible. HTTP webhooks get a `Content-Encoding: gzip` header; SQS and SNS messages are gzipped and base64-wrapped (because both transports are UTF-8 only). The `verifyAndParseWebhook` helper (HTTP) and `parseSqs` / `parseSns` (SQS/SNS, no app-level HMAC) detect the encoding from the body bytes, so the same handler code works whether or not compression is on, and stays correct even when middleware (Rails, Django, Laravel, Phoenix) auto-decompresses the request.

<Admonition type="info">

Apps created after **May 7, 2026** have `enable_hook_payload_compression` set to `true` by default. Your handlers will receive compressed payloads out of the box, so make sure they call `verifyAndParseWebhook` on HTTP traffic and `parse_sqs` / `parse_sns` on queue/topic deliveries (or equivalent decode + `parse_event` primitives) before going live. Apps created before that date stay opt-in; run the snippet below to turn compression on.

</Admonition>

### Enabling compression

<Tabs>

```js label="JavaScript"
await client.updateAppSettings({
  enable_hook_payload_compression: true,
});
```

```python label="Python"
client.update_app(enable_hook_payload_compression=True)
```

```ruby label="Ruby"
require 'getstream_ruby'
Models = GetStream::Generated::Models

client.common.update_app(Models::UpdateAppRequest.new(
  enable_hook_payload_compression: true,
))
```

```php label="PHP"
$client->updateApp(new Models\UpdateAppRequest(
    enableHookPayloadCompression: true,
));
```

```go label="Go"
client.UpdateApp(ctx, &getstream.UpdateAppRequest{
  EnableHookPayloadCompression: getstream.PtrTo(true),
})
```

```csharp label="C#"
await client.UpdateAppAsync(new UpdateAppRequest
{
    EnableHookPayloadCompression = true,
});
```

```java label="Java"
client.updateApp(UpdateAppRequest.builder()
    .enableHookPayloadCompression(true)
    .build()).execute();
```

</Tabs>

The flag applies to every transport: HTTP webhooks, SQS and SNS. It also covers the [event failover](#event-failover) hook and chat's [Before Message Send hook](https://getstream.io/chat/docs/node/before-message-send-webhook/).

### Before enabling compression in production

- **Use a current SDK**: `verifyAndParseWebhook` for HTTP (decompress + `verify_signature` + typed event) and `parse_sqs` / `parse_sns` for SQS/SNS (decode + typed event, no app-level HMAC). All three handle uncompressed, gzipped, and base64+gzipped payloads without caller-side branching.
- **Without an SDK**, your handler must accept `Content-Encoding: gzip` and gzip-decompress the body; for SQS/SNS, base64-decode then gzip-decompress (or detect via the gzip magic bytes `1f 8b`, per [RFC 1952](https://datatracker.ietf.org/doc/html/rfc1952)).
- **Verify HMAC on the uncompressed bytes**, never on the gzipped or base64-wrapped envelope.
- **Small payloads stay uncompressed** to avoid envelope overhead, even with the flag on. The composite helpers handle both cases transparently.

## SQS

Stream can send payloads of all events from your application to an [Amazon SQS](https://aws.amazon.com/sqs/) queue you own.

An application with a lot of users generates a lot of events. With a standard webhook configuration, events are posted to your server and can overwhelm unprepared servers during high-use periods. While the server is out, it will not be able to receive webhooks and will fail to process them. One way to avoid this issue is to use Stream's support for sending webhooks to Amazon SQS.

SQS removes the chance of losing data by providing a large, scalable bucket that holds events generated by Stream in a queue for your server. The complete list of supported events is identical to those sent through webhooks.

### Authentication

There are 2 ways to configure authentication on your SQS queue:

1. By providing a key and secret

2. Or by having Stream's AWS account assume a role on your SQS queue. With this option you omit the key and secret, but instead you set up a resource-based policy to grant Stream SendMessage permission on your SQS queue. The following policy needs to be attached to your queue (replace the value of Resource with the fully qualified ARN of your queue):

<Tabs>

```json label="JSON"
{
  "Sid": "AllowStreamProdAccount",
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:iam::185583345998:root"
  },
  "Action": "SQS:SendMessage",
  "Resource": "arn:aws:sqs:us-west-2:1111111111:customer-sqs-for-stream"
}
```

</Tabs>

To configure the queue, add a hook with `hook_type: "sqs"` to the `event_hooks` array, the same way as the [webhook examples above](#configuring-hooks). The full walkthrough lives on the [Chat SQS page](https://getstream.io/chat/docs/node/sqs/); the same calls work for every product.

### Configuration Options

The following options are available when configuring an SQS event hook:

| Option        | Type    | Description                                                                             | Required                                                                           |
| ------------- | ------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| id            | string  | Unique identifier for the event hook                                                    | No. If empty, it will generate an ID.                                              |
| enabled       | boolean | Boolean flag to enable/disable the hook                                                 | Yes                                                                                |
| hook_type     | string  | Must be set to `"sqs"`                                                                  | Yes                                                                                |
| sqs_queue_url | string  | The AWS SQS queue URL                                                                   | Yes                                                                                |
| sqs_region    | string  | The AWS region where the SQS queue is located (e.g., "us-east-1")                       | Yes                                                                                |
| sqs_auth_type | string  | Authentication type: `"keys"` for access key/secret or `"resource"` for role-based auth | Yes                                                                                |
| sqs_key       | string  | AWS access key ID (required if auth_type is "keys")                                     | Yes if using key auth                                                              |
| sqs_secret    | string  | AWS secret access key (required if auth_type is "keys")                                 | Yes if using key auth                                                              |
| event_types   | array   | Array of event types this hook should handle                                            | No. Not provided or empty array means subscribe to all existing and future events. |

### SQS Permissions

Stream needs the right permissions on your SQS queue to be able to send events to it. If updates are not showing up in your queue add the following permission policy to the queue:

<Tabs>

```json label="JSON"
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1459523779000",
      "Effect": "Allow",
      "Action": [
        "sqs:GetQueueUrl",
        "sqs:SendMessage",
        "sqs:SendMessageBatch",
        "sqs:GetQueueAttributes"
      ],
      "Resource": ["arn:aws:sqs:region:acc_id:queue_name"]
    }
  ]
}
```

</Tabs>

### Reading messages from SQS

SQS honours the same `enable_hook_payload_compression` flag (see [Payload Compression](#payload-compression)). When compression is on, the message body is gzipped + base64-encoded (SQS only accepts UTF-8) and the producer sets these message attributes:

```json
{
  "content_encoding": "gzip",
  "content_type": "application/json",
  "payload_encoding": "base64"
}
```

Call `parseSqs` on your Stream client with the SQS `Body` string. It reverses the base64 + gzip envelope and returns a typed event (with an `UnknownEvent` fallback), the same shape `verifyAndParseWebhook` returns for HTTP. The same call works whether or not compression is on (encoding is detected from the body bytes, so the `content_encoding` / `payload_encoding` attributes are only a hint).

<Admonition type="note">

**No `X-Signature` on SQS.** Stream does not ship an HMAC signature on SQS deliveries. The transport is authenticated end-to-end: the queue is gated by IAM, so only your account can read it, and only Stream's account can write to it.

</Admonition>

<Tabs>

```js label="JavaScript"
// message is the SQS Message object you received from ReceiveMessageCommand
const event = client.parseSqs(message.Body);
// event.type, event.user, ...
```

```python label="Python"
# message is an SQS message dict from boto3 receive_message
event = client.parse_sqs(message["Body"])
# event.type, event.user, ...
```

```ruby label="Ruby"
event = client.parse_sqs(message.body)
```

```php label="PHP"
$event = $client->parseSqs($message['Body']);
```

```go label="Go"
event, err := client.ParseSqs(*message.Body)
```

```csharp label="C#"
var ev = client.ParseSqs(message.Body);
```

```java label="Java"
var event = client.parseSqs(message.body());
```

</Tabs>

`parse_sqs` takes only the message body. No HMAC is involved; use your API secret only for other Stream API calls, not for parsing SQS payloads. The same decode + parse logic is exposed as a static / module-level `parse_sqs` (see [Verifying and Parsing Events](#verifying-and-parsing-events) for per-language imports); use it in workers that don't keep a Stream client around. A per-language reference implementation for SDK-less consumers lives on the [Chat SQS page](https://getstream.io/chat/docs/node/sqs/).

### SQS Best practices and Assumptions

- Set the maximum message size set to 256 KB.

Messages bigger than the maximum message size will be dropped.

- Set up a dead-letter queue for your main queue.

This queue will hold the messages that couldn't be processed successfully and is useful for debugging your application.

## SNS

Stream can send payloads of all events from your application to an [Amazon SNS](https://aws.amazon.com/sns/) topic you own. SNS provides a large, scalable message exchange that delivers events generated by Stream to as many consumers as you like. The complete list of supported events is identical to those sent through webhooks.

### Authentication

There are 2 ways to configure authentication on your SNS topic:

1. By providing a key and secret

2. Or by having Stream's AWS account assume a role on your SNS topic. With this option you omit the key and secret, but instead you set up a resource-based policy to grant Stream Publish permission on your SNS topic. The following policy needs to be attached to your topic (replace the value of Resource with the fully qualified ARN of your topic):

<Tabs>

```json label="JSON"
{
  "Sid": "AllowStreamProdAccount",
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:iam::185583345998:root"
  },
  "Action": "SNS:Publish",
  "Resource": "arn:aws:sns:us-west-2:1111111111:customer-sns-topic"
}
```

</Tabs>

To configure the topic, add a hook with `hook_type: "sns"` to the `event_hooks` array, the same way as the [webhook examples above](#configuring-hooks). The full walkthrough lives on the [Chat SNS page](https://getstream.io/chat/docs/node/sns/); the same calls work for every product.

### Configuration Options

The following options are available when configuring an SNS event hook:

| Option        | Type    | Description                                                                             | Required                                                                           |
| ------------- | ------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| id            | string  | Unique identifier for the event hook                                                    | No. If empty, it will generate an ID.                                              |
| enabled       | boolean | Boolean flag to enable/disable the hook                                                 | Yes                                                                                |
| hook_type     | string  | Must be set to `"sns"`                                                                  | Yes                                                                                |
| sns_topic_arn | string  | The AWS SNS topic ARN                                                                   | Yes                                                                                |
| sns_region    | string  | The AWS region where the SNS topic is located (e.g., "us-east-1")                       | Yes                                                                                |
| sns_auth_type | string  | Authentication type: `"keys"` for access key/secret or `"resource"` for role-based auth | Yes                                                                                |
| sns_key       | string  | AWS access key ID (required if auth_type is "keys")                                     | Yes if using key auth                                                              |
| sns_secret    | string  | AWS secret access key (required if auth_type is "keys")                                 | Yes if using key auth                                                              |
| event_types   | array   | Array of event types this hook should handle                                            | No. Not provided or empty array means subscribe to all existing and future events. |

### Reading notifications from SNS

SNS honours the same `enable_hook_payload_compression` flag (see [Payload Compression](#payload-compression)). When compression is on, the notification `Message` is gzipped + base64-encoded (SNS only accepts UTF-8) and the producer sets the same message attributes as SQS.

Call `parseSns` on your Stream client with the notification body (either the raw envelope JSON string or the pre-extracted `Message` field). It unwraps the SNS envelope when needed, reverses the base64 + gzip payload, and returns a typed event. The return shape matches `verifyAndParseWebhook` sans verification. The same call works whether or not compression is on, and whether the topic is delivered over HTTP or via an SQS subscription.

<Admonition type="note">

**No Stream `X-Signature` on SNS.** Stream does not ship an app-level HMAC on SNS payloads. SNS itself is authenticated with AWS signatures (`SigningCertURL` / `Signature`) when you subscribe over HTTPS.

</Admonition>

<Tabs>

```js label="JavaScript"
const event = client.parseSns(notification.Message);
// event.type, event.user, ...
```

```python label="Python"
event = client.parse_sns(notification["Message"])
# event.type, event.user, ...
```

```ruby label="Ruby"
event = client.parse_sns(notification['Message'])
```

```php label="PHP"
$event = $client->parseSns($notification['Message']);
```

```go label="Go"
event, err := client.ParseSns(notification.Message)
```

```csharp label="C#"
var ev = client.ParseSns(notification.Message);
```

```java label="Java"
var event = client.parseSns(notification.getMessage());
```

</Tabs>

`parse_sns` takes only the notification body string. No HMAC is involved; use your API secret only for other Stream API calls. The same unwrap + decode + parse logic is exposed as a static / module-level `parse_sns` (see [Verifying and Parsing Events](#verifying-and-parsing-events) for per-language imports). A per-language reference implementation for SDK-less consumers lives on the [Chat SNS page](https://getstream.io/chat/docs/node/sns/).

## Event Failover

When event delivery fails after all retry attempts, Stream can automatically persist the failed event to a storage backend you control. This ensures no events are lost during outages in your endpoint.

Currently, Google Cloud Storage (GCS) is supported as a failover storage backend.

### How it Works

1. Stream attempts to deliver an event to your endpoint
2. If all delivery retries are exhausted, the event is written to your configured GCS bucket
3. The event is stored as a JSON file containing the full event payload, metadata about the failure, and the original endpoint URL

You can then process these failed events at your own pace by reading them from GCS.

### Configuration

To enable failover, add a `failover_config` to your event hook:

<Tabs>

```js label="JavaScript"
await client.updateAppSettings({
  event_hooks: [
    {
      enabled: true,
      hook_type: "webhook",
      webhook_url: "https://example.com/webhooks/stream",
      event_types: ["message.new"],
      failover_config: {
        type: "gcs",
        gcs_bucket: "my-failover-bucket",
        gcs_path: "stream/failed-events",
        gcs_credentials: '{"type":"service_account","project_id":"..."}',
      },
    },
  ],
});
```

</Tabs>

<Admonition type="caution">

GCS credentials are validated when you save the configuration. Make sure the service account JSON key is valid and has write access to the specified bucket before updating your app settings.

</Admonition>

<Admonition type="info">

Failover is currently supported for webhook hooks. Support for SQS and SNS hooks is planned.

</Admonition>

### Configuration Options

| Option          | Type   | Description                                               | Required |
| --------------- | ------ | --------------------------------------------------------- | -------- |
| type            | string | Storage backend type. Currently only `"gcs"` is supported | Yes      |
| gcs_bucket      | string | The name of your GCS bucket                               | Yes      |
| gcs_credentials | string | GCS service account JSON key as a string                  | Yes      |
| gcs_path        | string | Optional prefix for the object path inside the bucket     | No       |

### GCS Permissions

The service account used in `gcs_credentials` needs the following permissions on the target bucket:

- `storage.objects.create`
- `storage.objects.get`

The simplest way is to grant the **Storage Object Creator** (`roles/storage.objectCreator`) role to the service account on the bucket.

### Storage Format

Failed events are stored as JSON files in your GCS bucket with the following path structure:

```text
{gcs_path}/{yyyy}/{mm}/{dd}/{timestamp}-{event_type}-{hook_id}.json
```

Each file contains a JSON envelope with the following fields:

| Field                | Description                                           |
| -------------------- | ----------------------------------------------------- |
| original_hook_id     | The ID of the event hook that failed                  |
| original_webhook_url | The endpoint URL that was unreachable                 |
| event_type           | The type of event that failed to deliver              |
| error_message        | The error returned by the last delivery attempt       |
| failed_at            | ISO 8601 timestamp of when the failure was recorded   |
| payload              | The full event payload that would have been delivered |

Event failover honours the same app-level `enable_hook_payload_compression` flag described under [Payload Compression](#payload-compression). If you build a consumer that reads failed events from your GCS bucket, feed the `payload` field through the same `verifyAndParseWebhook` helper you use for live webhooks (or the manual `gunzip_payload` + `parse_event` primitives from the [reference implementation](#verifying-and-parsing-events)) so your code transparently handles both the plain-JSON and the compressed cases.

### Disabling Failover

To remove the failover configuration, update the hook without the `failover_config` field:

<Tabs>

```js label="JavaScript"
await client.updateAppSettings({
  event_hooks: [
    {
      enabled: true,
      hook_type: "webhook",
      webhook_url: "https://example.com/webhooks/stream",
      event_types: [],
      // no failover_config = failover disabled
    },
  ],
});
```

</Tabs>

## Restricting Access to Webhook

If necessary, you can only expose your webhook service to Stream. This is possible by configuring your network (eg. iptables rules) to drop all incoming traffic that is not coming from our API infrastructure.

Below you can find the complete list of egress IP addresses that our webhook infrastructure uses. Such list is static and is not changing over time.

| Region                           | IP addresses                                                                                                              |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| us-east4 (US-East)               | 34.225.10.29/32<br/>34.198.125.61/32<br/>52.22.78.160/32<br/>3.215.161.238/32<br/>34.181.149.154/32<br/>34.145.214.228/32 |
| us-east5 (Ohio)                  | 3.14.163.216/32<br/>3.15.245.3/32<br/>3.141.116.179/32<br/>34.186.254.218/32<br/>34.186.255.37/32                         |
| us-west1 (Oregon)                | 52.25.165.25/32<br/>44.237.58.11/32<br/>52.10.213.81/32<br/>8.229.163.173/32<br/>136.117.241.8/32                         |
| northamerica-northeast1 (Canada) | 35.183.141.98/32<br/>52.60.71.231/32<br/>3.97.253.35/32<br/>34.19.168.136/32<br/>34.19.229.75/32                          |
| europe-west4 (EU-West)           | 52.212.14.212/32<br/>52.17.43.232/32<br/>34.241.110.177/32<br/>35.204.6.219/32<br/>34.158.68.88/32                        |
| europe-west2 (London)            | 34.153.181.194/32<br/>34.142.62.7/32                                                                                      |
| europe-west3                     | 34.179.201.229/32<br/>35.242.238.42/32                                                                                    |
| asia-south1 (Mumbai)             | 65.1.48.87/32<br/>15.206.221.25/32<br/>13.233.48.78/32<br/>34.93.113.218/32<br/>34.47.139.79/32                           |
| asia-southeast1 (Singapore)      | 13.229.11.158/32<br/>52.74.225.150/32<br/>52.76.180.70/32<br/>35.187.232.235/32<br/>35.185.180.233/32                     |
| australia-southeast1 (Sydney)    | 54.252.193.245/32<br/>13.55.254.141/32<br/>3.24.48.104/32<br/>34.151.136.126/32<br/>34.116.110.249/32                     |
| europe-north2                    | 34.51.202.72/32<br/>34.51.213.37/32                                                                                       |

## Product-Specific Hooks

Chat has additional hook types that are configured outside the `event_hooks` system: [Before Message Send](https://getstream.io/chat/docs/node/before-message-send-webhook/) for modifying or moderating messages before delivery, [Custom Commands](https://getstream.io/chat/docs/node/custom-commands-webhook/) for reacting to /slash commands, and [pending messages](https://getstream.io/chat/docs/node/pending-messages/) for approval flows. Push delivery to user devices is covered under [push notifications](https://getstream.io/docs/platform/push-notifications/).


---

This page was last updated at 2026-08-07T13:10:45.431Z.

For the most recent version of this documentation, visit [https://getstream.io/docs/platform/webhooks/](https://getstream.io/docs/platform/webhooks/).