# Message Schema

A message schema lets your app decide what client-side writes may contain. You describe the allowed messages and reactions with a [JSON Schema](https://json-schema.org/draft/2020-12) and list the message fields that can't change once a message exists. Stream then checks the message and reaction writes made with a user token that carries the `stream_check_writes` claim, and rejects the ones that don't match.

Use it when some clients write to Stream directly and you don't fully trust them, for example a partner integration that holds user tokens for your users. You decide per token which callers are checked, so your own apps can keep writing freely.

What is checked, and what isn't:

- Only requests made with a user token carrying `stream_check_writes: true` are checked.
- Server-side requests (made with your API secret) are never checked.
- Tokens without the claim, anonymous users and unauthenticated requests are never checked.
- Message writes and reactions are checked. Other writes, such as channel and member updates, are not. See [Which writes are checked](#which-writes-are-checked).

## How it works

1. Your backend adds `stream_check_writes: true` to the user tokens of the callers you want checked.
2. You save a `message_schema` setting on your app, with `mode` set to `enforce`.
3. When a checked caller sends or edits a message (or adds a reaction), Stream builds a JSON document from the message or reaction as it will be stored and validates it against your schema. On an edit, it also compares your frozen fields with the stored message.
4. A write that doesn't match is rejected with a `400` error and is not stored.

The check runs after the permission checks on the request (a caller who can't write still gets a `403`). When a message is sent, it runs before moderation, URL enrichment, slash commands and the [before message send webhook](https://getstream.io/chat/docs/go-golang/before-message-send-webhook/). A few checks on the message's content run after it, such as the checks on mentions and quoted messages, so a write can pass the schema and still be rejected by them. A rejected message never reaches your webhook.

## Which writes are checked

| Write                                                                                                                                         | Checked against   | Frozen fields |
| --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | ------------- |
| Sending a message                                                                                                                             | `message.schema`  | No            |
| Updating or partially updating a message                                                                                                      | `message.schema`  | Yes           |
| Scheduling a [scheduled message](https://getstream.io/chat/docs/go-golang/scheduled-messages/), and editing its content                                          | `message.schema`  | No            |
| Updating a [live location](https://getstream.io/chat/docs/go-golang/location-sharing/)                                                                           | `message.schema`  | Yes           |
| The system message sent with a [channel update](https://getstream.io/chat/docs/go-golang/channel-update/) or [truncate](https://getstream.io/chat/docs/go-golang/truncate-channel/) | `message.schema`  | No            |
| Sending a [reaction](https://getstream.io/chat/docs/go-golang/send-reaction/)                                                                                    | `reaction.schema` | No            |

Each write is checked only when the setting has the matching part: `message` for message writes, `reaction` for reactions.

Not checked:

- Deleting a message or a reaction.
- An edit that only changes the pin fields. See [Pinning is not checked](#pinning-is-not-checked).
- A scheduled message when it is sent, and an edit that only changes when it is sent.
- Messages Stream generates itself, such as the results of message actions like giphy, and translations.
- Every other write, such as channel and member updates, and drafts.

### Scheduled messages

- The message is checked when it is scheduled and when its content is edited, not when it is sent. A message scheduled before you turned the schema on is sent unchecked.
- There are no frozen fields, because nothing is stored yet to compare with.
- `message.id` in the document is the scheduled message's ID. The message is sent with a different ID, so don't write rules on `message.id` for scheduled messages.
- `pinned_at` is in the document only if the client sent it. A normal send fills it in before the check, but scheduling doesn't, so a schema that requires `pinned_at` rejects a scheduled `pinned: true` without it. A `pinned_at` the client sends is not kept: the pin starts when the message is sent.

### Live location

- The document is the whole stored message, with the new location merged into `shared_location`.
- Frozen fields apply. Freezing `shared_location` (or a path under it) rejects every live location update.
- In `enforce` mode, a stored message that already breaks the schema rejects every live location update until the message is edited to match it.

### Channel system messages

- The document has `type: "system"`. If your schema restricts `message.type`, allow `"system"` or these messages will be rejected.
- A rejected system message fails the whole channel update or truncate, and nothing is changed.

## The `stream_check_writes` token claim

The claim marks a caller as checked. It doesn't select which writes are checked: that comes from your app's `message_schema` setting.

| Claim value               | Result                                   |
| ------------------------- | ---------------------------------------- |
| `true`                    | Checked                                  |
| `false`, `null` or absent | Not checked                              |
| Any other JSON type       | The token is rejected with a `401` error |

The claim must be a JSON boolean. A string such as `"true"`, a number such as `1`, an object or an array makes the token invalid. Stream rejects such a token wherever it is used: on every endpoint and when connecting the WebSocket, not only on message writes.

Tokens are signed with your API secret on your server, so a client can't remove the claim from a token you issued. See [Authentication and tokens](https://getstream.io/docs/platform/authentication/) for how tokens are created.

The payload of a checked user token:

```json
{
  "user_id": "john",
  "stream_check_writes": true,
  "iat": 1767222000,
  "exp": 1767225600
}
```

The Node.js, PHP and Go SDKs can add the claim when they create a user token:

```go label="Go"
token, err := client.CreateToken("john",
	getstream.WithExpiration(time.Hour),
	getstream.WithClaims(getstream.Claims{
		CustomClaims: map[string]interface{}{"stream_check_writes": true},
	}),
)
```

With other server SDKs, sign the token with a JWT library of your language, using your API secret and HS256, with the payload above.

>
> **Warning:** The check relies on signed tokens. If your app has auth checks disabled (`disable_auth_checks`, see [App settings](https://getstream.io/chat/docs/go-golang/app-setting-overview/)), token signatures are not verified and a client can connect with a token that leaves the claim out.
>

## The `message_schema` setting

The schema lives in the `message_schema` app setting. It is a server-side setting: save it with Update App Settings (`PATCH /app`) and read it back with Get App (`GET /app`). See [App settings](https://getstream.io/chat/docs/go-golang/app-setting-overview/) for how app settings are managed.

```json
{
  "message_schema": {
    "mode": "enforce",
    "document_version": 1,
    "message": {
      "schema": {
        "type": "object",
        "properties": {
          "message": {
            "type": "object",
            "properties": {
              "text": { "type": "string", "maxLength": 2000 }
            }
          }
        }
      },
      "frozen_fields": ["custom.order_id"]
    }
  }
}
```

| Field                   | Description                                                                                                                                                                                                           |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mode`                  | `enforce` rejects writes that don't match. `report` accepts every write and sends an [event](#report-mode-events) for each one that `enforce` would reject. `off` turns checking off. Defaults to `off` when omitted. |
| `document_version`      | The version of the [document](#the-document-the-schema-sees) your schema is written against. Omit it to use the latest (`1`).                                                                                         |
| `message`               | Message checks. When it is absent, messages are not checked.                                                                                                                                                          |
| `message.schema`        | A JSON Schema (draft 2020-12) object. The document of every checked write must match it. Optional.                                                                                                                    |
| `message.frozen_fields` | Paths of fields that can't change after the message is created. See [Frozen fields](#frozen-fields). Optional.                                                                                                        |
| `reaction`              | Reaction checks. When it is absent, reactions are not checked.                                                                                                                                                        |
| `reaction.schema`       | A JSON Schema (draft 2020-12) object. The [reaction document](#the-reaction-document) of every checked reaction must match it. Optional.                                                                              |

Use `report` to try a schema on real traffic before you enforce it: checked writes are always accepted, and each one that breaks the schema sends an event to your webhook. See [Report mode events](#report-mode-events).

When you omit `document_version`, Stream stores the latest version with your setting. Your schema stays on that version when a newer document version is released, so new fields never break an existing schema.

### Saving the setting

`message_schema` is saved as one object. Each update replaces the whole stored value, so always send the complete setting, schema and frozen fields included. An Update App Settings request that doesn't include `message_schema` leaves it unchanged.

```bash label="Bash"
curl --location --request PATCH 'https://chat.stream-io-api.com/app?api_key={api_key}' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR SERVER TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
  "message_schema": {
    "mode": "enforce",
    "message": {
      "schema": {
        "type": "object",
        "properties": {
          "message": {
            "type": "object",
            "properties": { "text": { "type": "string", "maxLength": 2000 } }
          }
        }
      }
    }
  }
}'
```

Get App returns the stored setting under `message_schema`, with `document_version` filled in. Keys may come back in a different order than you sent them. The field is omitted when the setting was never saved.

### Turning it off

Send `{"mode": "off"}`. This turns checking off and removes the stored schema and frozen fields. A `null` value is rejected.

```json
{
  "message_schema": { "mode": "off" }
}
```

### Validation on save

Stream validates the setting when you save it and rejects an invalid one with a `400` error that names the problem. The message usually starts with `message_schema:`. A value of the wrong JSON type, such as `"mode": 1`, is rejected when the request body is read, with the generic invalid request error. Nothing is stored when the setting is rejected.

The setting itself:

- It must be a JSON object. Unknown keys are rejected, so a misspelled key fails instead of being ignored.
- `mode` must be `off`, `report` or `enforce`.
- `document_version` must be a known version. Today that is `1`.
- The text must be valid UTF-8, with no `\u0000` escape and no unpaired surrogate escape (such as a lone `\ud800`).

Each schema (`message.schema` and `reaction.schema`):

- Must be a JSON object. The boolean schemas `true` and `false` are not accepted at the root, but are fine inside it.
- Is JSON Schema draft 2020-12. `$schema` may be omitted, otherwise it must be `https://json-schema.org/draft/2020-12/schema`.
- Is at most 64 KB (65,536 bytes), measured as compact JSON.
- Nests subschemas at most 32 levels deep, and has at most 2,000 subschemas once every `$ref` is expanded.
- Writes numbers with at most 64 characters and without an exponent (`0.00001`, not `1e-5`).

Keywords:

- Unknown keywords are rejected, including keywords from older drafts such as `definitions`, `dependencies` and `additionalItems`. Use `$defs`, `dependentRequired`, `dependentSchemas` and `prefixItems`/`items` instead.
- `propertyNames` is not supported, because its errors can't point at the offending property. Use `patternProperties` with `"additionalProperties": false` instead.
- `contentEncoding`, `contentMediaType` and `contentSchema` are not supported: they only annotate and would check nothing.
- `$ref` may only point to an entry of the root `$defs`, as `#/$defs/<name>`. The name can't contain `/` or `%`, and `$ref` cycles are rejected. Remote references are never loaded. `$id`, `$anchor`, `$dynamicRef` and `$dynamicAnchor` are not supported.
- `format` is asserted, not just annotated: a value that doesn't match the format fails validation. The supported formats are `date`, `time`, `date-time`, `duration`, `period`, `email`, `hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`, `uri-template`, `iri`, `iri-reference`, `uuid`, `json-pointer`, `relative-json-pointer`, `regex` and `semver`. Any other format name is rejected.

Frozen fields:

- At most 100 paths, each at most 256 characters, with no empty segment.
- The first segment must be a message field of the document version, such as `custom`, `text` or `attachments`.

## The document the schema sees

Your schema validates a JSON document, not the request body. For messages, Stream builds it from the message as it will be stored, before enrichment, and from the stored user making the request:

```json
{
  "message": {
    "id": "8f7a9c2e-1d4b-4a8e-9b0c-3e2f1a6d5c4b",
    "text": "Can you ship it today?",
    "mentioned_users": ["jane"],
    "custom": { "order_id": "ord_1234", "priority": "high" }
  },
  "user": {
    "id": "john",
    "role": "user",
    "teams": ["blue"]
  }
}
```

On a partial update, `message` is the message after your `set` and `unset` are applied.

### Message fields (version 1)

| Field                   | Description                                                                        |
| ----------------------- | ---------------------------------------------------------------------------------- |
| `id`                    | Message ID. Always present: Stream generates one when the client doesn't send it.  |
| `type`                  | Message type. Absent for a regular message. See [Thread replies](#thread-replies). |
| `text`                  | Message text.                                                                      |
| `mml`                   | Message Markup Language content.                                                   |
| `attachments`           | Attachments. See [Attachment fields](#attachment-fields-version-1).                |
| `parent_id`             | ID of the thread parent, for a reply.                                              |
| `show_in_channel`       | Whether a thread reply is also shown in the channel.                               |
| `quoted_message_id`     | ID of the quoted message.                                                          |
| `mentioned_users`       | IDs of the mentioned users, as an array of strings.                                |
| `mentioned_roles`       | Mentioned roles.                                                                   |
| `mentioned_group_ids`   | Mentioned user group IDs.                                                          |
| `mentioned_channel`     | Whether the message mentions the channel.                                          |
| `mentioned_here`        | Whether the message mentions the online members.                                   |
| `silent`                | Whether the message is silent.                                                     |
| `pinned`                | Whether the message is pinned.                                                     |
| `pinned_at`             | When the message was pinned, as an RFC 3339 timestamp.                             |
| `pin_expires`           | When the pin expires, as an RFC 3339 timestamp.                                    |
| `restricted_visibility` | IDs of the users the message is restricted to.                                     |
| `poll_id`               | ID of the attached poll.                                                           |
| `shared_location`       | Shared location: `latitude`, `longitude`, `created_by_device_id` and `end_at`.     |
| `custom`                | The message's custom data.                                                         |

### Attachment fields (version 1)

Each element of `message.attachments` can have: `type`, `fallback`, `color`, `pretext`, `author_name`, `author_link`, `author_icon`, `title`, `title_link`, `text`, `image_url`, `thumb_url`, `footer`, `footer_icon`, `actions`, `fields`, `asset_url`, `custom`, `giphy`, `og_scrape_url`, `original_width` and `original_height`.

`image_url`, `thumb_url`, `asset_url`, and the `url` and `file` values in the attachment's `custom`, are in the document without CDN signing parameters. A `pattern` or `const` on these fields sees the unsigned URL, not the exact string the client sent.

### User fields (version 1)

`user` is the stored user who makes the request: `id`, `role`, `teams` and `custom`. When a user edits someone else's message, `user` is the editor, not the author. A `user` object sent inside the message is never used.

Use it to apply different rules to different callers, for example to allow a field only for one role.

### Fields that are not in the document

Only the fields listed above are in the document. Anything else in the request is invisible to the schema, including:

- Request options such as `skip_push`, `skip_enrich_url`, `keep_channel_hidden` and `pending`.
- Fields Stream manages itself, such as `created_at`, `reply_count` or `html`.

A new document version is needed to add a field, so the list of a version never changes.

### Custom data is always under `custom`

On the wire, custom fields are sent flat, at the top level of the message or attachment. In the document they are always grouped under `custom`: `message.custom`, `message.attachments[].custom` and `user.custom`. Write your rules there:

```json
{
  "properties": {
    "message": {
      "properties": {
        "custom": {
          "properties": { "priority": { "enum": ["low", "normal", "high"] } }
        }
      }
    }
  }
}
```

If a client sends custom data nested under a `custom` key, it is merged into `message.custom` (or the attachment's `custom`), and the nested keys win.

Stream writes a few keys into message custom data itself, and these are removed from `message.custom`: `original_text` and `sanitized_text` (moderation), `args` and `command` (slash commands), and `stream_scheduled_at` and `stream_scheduled_message_id` (scheduled messages). If your own custom data uses one of these names, the schema can't see it.

### Default values are dropped

Built-in fields with a default value are left out of the document, so "absent" and "default" read the same. The default values are `null`, `false`, `""`, `[]` and `{}`, plus:

- `"regular"` for `message.type`.
- `0` for `original_width` and `original_height` of an attachment. Every other number is kept, so `latitude: 0` is in the document.

This applies inside nested built-in objects too (`shared_location`, attachments and their `actions`, `fields` and `giphy`). It never applies inside custom data: a `false` or `""` you store in `custom` stays in the document. An empty `custom` object is left out as a whole. Elements are never removed from arrays, so array positions don't shift.

In practice:

- To require a built-in field, use `required`: `"required": ["text"]` rejects a message with no text or an empty one.
- To forbid a built-in field, give it the `false` schema: `"poll_id": false` rejects any message with a poll.
- `message.id` and `user.id` are always present.

### Thread replies

A thread reply has `type: "reply"` in the document. If your schema restricts `message.type`, allow `"reply"` or replies will be rejected. A reply that is also shown in the channel (`show_in_channel: true`) is a regular message, so it has no `type`.

### URL previews

When a client edits a message, URL preview attachments that Stream generated for it are left out of the document: an attachment is left out when it is identical to a stored attachment that has an `og_scrape_url`. This also applies to a copy of a stored URL preview that the client added again, so a `maxItems` on `attachments` doesn't count these copies on an edit. Every other new or changed attachment is checked.

When a message is sent, every attachment in the request is in the document, including one that carries an `og_scrape_url`. Stream adds URL previews after the check, so they are never checked on send.

### The reaction document

`reaction.schema` validates a document with the reaction and the stored user making the request:

```json
{
  "reaction": {
    "type": "like",
    "score": 1,
    "custom": { "emoji_code": ":+1:" }
  },
  "user": {
    "id": "john",
    "role": "user"
  }
}
```

- `reaction` has `type`, `score` and `custom`. Custom fields are sent flat on the wire and grouped under `custom` in the document, as for messages. `emoji_code` is custom data, so it is under `custom`.
- `score` is the score as stored: a reaction sent with no score, or a score of `0`, has `score: 1`.
- Default values are dropped from built-in fields as for messages, never from `custom`.
- `user` has the same fields as in the message document.
- The message the reaction is on is not in the document.

## Frozen fields

`message.frozen_fields` lists the fields that must keep the state they had when the message was created. They are checked when a checked caller updates or partially updates a message, or updates its live location, against the stored message, whoever created it. A message created by your server can have frozen fields that a checked client can't change.

- Paths use the shape of the [document](#the-document-the-schema-sees), relative to `message`, with dots between segments: `custom.order_id`, `text`, `attachments`.
- A parent freezes everything under it: `custom` freezes all custom data.
- A number indexes an array: `attachments.0.title` is the title of the first attachment. Only the plain form of the number (`1`, not `01`) counts.
- Absent is a state. Changing a value, removing a field and adding a field that was absent are all violations.
- Values are compared after [default values are dropped](#default-values-are-dropped), so setting a frozen `text` that was absent to `""` is not a change.

A frozen field violation has the rule `frozen` and the path of the frozen field, for example `/message/custom/order_id`.

`frozen_fields` works with or without a `schema`. Frozen fields are not checked when a message is sent, since there is nothing stored to compare with.

## Pinning is not checked

An update or partial update that only changes `pinned`, `pinned_at` or `pin_expires` is not checked at all: no schema rule and no frozen field applies, including rules on the pin fields and on `user`. Pinning has its own permission, and users who have it can pin any message, including one that doesn't match the current schema.

An edit that changes the pin fields and anything else is checked as usual, and so is an edit that changes nothing.

## Errors

When a write doesn't match, the API returns a `400` with error code `141`:

```json
{
  "code": 141,
  "message": "SendMessage failed with error: \"message schema violation at /message/custom/discount: additionalProperties: property is not allowed (custom fields are sent flat on the wire, at the top level of the message, attachment or reaction)\"",
  "exception_fields": {
    "reason": "message_schema_violation",
    "path": "/message/custom/discount",
    "rule": "additionalProperties"
  },
  "StatusCode": 400,
  "duration": "3.42ms",
  "more_info": "https://getstream.io/chat/docs/api_errors_response",
  "details": []
}
```

`exception_fields` holds the first violation:

| Field    | Description                                                                                                                                                                        |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `reason` | Always `message_schema_violation`.                                                                                                                                                 |
| `path`   | A [JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901) into the [document](#the-document-the-schema-sees), such as `/message/custom/discount` or `/message/attachments/0/title`. |
| `rule`   | The schema keyword that failed (`type`, `enum`, `required`, `additionalProperties`, `not`, ...), `false` for a field given the `false` schema, or `frozen`.                        |

Only one violation is reported. When there are more, the violation is followed by `(and N more)`, before the custom fields reminder when there is one. Violations are ordered by path, then rule, so the same write always reports the same one.

For `oneOf` and `anyOf`, Stream reports the failure in the alternative that came closest to matching, rather than every failing branch. When no alternative stands out, the violation is the `oneOf` or `anyOf` itself.

When the path is in the `custom` of a message, an attachment or a reaction, the message reminds you that custom fields are sent flat on the wire. The message never repeats a string or object value from the request. It can repeat a number, such as a value that is below a `minimum`, and `path` contains the names of the custom fields the client sent. The prefix names the endpoint, such as `SendMessage` or `UpdateMessagePartial`.

## Report mode events

In `report` mode, a checked write that breaks the schema is accepted, and Stream sends one event for it: the write that `enforce` would have rejected. In `enforce` mode no event is sent, because the client gets the `400` error instead.

| Event                       | Sent for                                                                                                                                   |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `message.schema_violation`  | Message writes: sending, updating and partially updating a message, scheduled messages, live location updates and channel system messages. |
| `reaction.schema_violation` | Reactions.                                                                                                                                 |

### Delivery

The events are delivered to your [webhook](https://getstream.io/docs/platform/webhooks/), SQS, SNS and Pub/Sub, like the other [webhook events](https://getstream.io/chat/docs/go-golang/webhook-events/). They are not sent over the WebSocket, and they trigger no push notification.

A hook with an empty `event_types` list receives them. A hook with an explicit list receives them only once you add `message.schema_violation` and `reaction.schema_violation` to it.

### Payload

```json
{
  "type": "message.schema_violation",
  "created_at": "2026-12-01T10:15:30.123456Z",
  "cid": "messaging:general",
  "message_id": "8f7a9c2e-1d4b-4a8e-9b0c-3e2f1a6d5c4b",
  "operation": "send",
  "user": {
    "id": "john",
    "role": "user",
    "teams": [],
    "language": "en",
    "custom": {},
    "banned": false,
    "online": true,
    "blocked_user_ids": [],
    "created_at": "2026-01-15T08:00:00Z",
    "updated_at": "2026-11-30T17:42:10Z"
  },
  "violations": [
    {
      "path": "/message/custom/discount",
      "rule": "additionalProperties",
      "message": "property is not allowed"
    },
    {
      "path": "/message/custom/order_id",
      "rule": "pattern",
      "message": "does not match pattern ^ord_[0-9]+$"
    }
  ]
}
```

| Field                  | Description                                                                                                                                                                          |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `type`                 | `message.schema_violation` or `reaction.schema_violation`.                                                                                                                           |
| `created_at`           | When the event was created.                                                                                                                                                          |
| `cid`                  | The channel the write was made in.                                                                                                                                                   |
| `message_id`           | The ID of the message. For `reaction.schema_violation`, the message the reaction is on.                                                                                              |
| `scheduled_message_id` | The ID of the scheduled message. Only on `message.schema_violation`, and only for scheduled message writes.                                                                          |
| `user`                 | The user who made the write.                                                                                                                                                         |
| `operation`            | The write that was checked: `send`, `update`, `partial_update`, `schedule`, `update_scheduled`, `live_location`, `system_message` or `reaction`. More values may be added later.     |
| `violations`           | Every violation, not only the first. Each has `path`, `rule` and `message`, as in the [error](#errors): `path` is a JSON Pointer into the [document](#the-document-the-schema-sees). |

`system_message` is the system message a client sends with a channel update or truncate. `reaction` is the only `operation` of `reaction.schema_violation`.

For a scheduled message (`schedule` and `update_scheduled`), use `scheduled_message_id` to identify it. `message_id` is the ID the message is normally sent with when it fires, but the message can get a different one.

### When events are sent

- **When the write is checked, not after it is stored.** The event can arrive for a write that then fails for another reason, or for a channel update whose change turns out to send no system message. Its `message_id` may never exist.
- **Once per checked write.** A client that retries a write is reported again.
- **With no cap and no sampling.** A wrong schema in `report` mode sends one event for every checked write. Make sure your webhook endpoint can take that volume before you turn `report` on.

## Things to know before you turn it on

- **Existing messages are not re-checked.** Turning on a schema, or changing it, doesn't touch stored messages. But a checked caller editing an old message that doesn't match the current schema gets the error, even when the edit changes nothing that the schema checks. Pinning still works, see [Pinning is not checked](#pinning-is-not-checked).
- **Not every write is checked.** Message writes and reactions are, see [Which writes are checked](#which-writes-are-checked). Other writes made with the same token, such as channel and member updates, are not checked. Use [permissions](https://getstream.io/chat/docs/go-golang/chat-permission-policies/) to control them.
- **Test the schema before you use it.** Validate sample documents with your schema in any JSON Schema 2020-12 validator, remembering that custom data is under `custom` and default values are dropped. Then turn it on for a test user's token first, or save it with `mode` set to `report` and watch the [events](#report-mode-events) before you switch to `enforce`.

## Example

This example lets checked clients send messages with a short text and two custom fields, `order_id` and `priority`. `order_id` can't change once the message exists.

### 1. Save the setting

```json
{
  "message_schema": {
    "mode": "enforce",
    "message": {
      "schema": {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "properties": {
          "message": {
            "type": "object",
            "properties": {
              "text": { "type": "string", "maxLength": 2000 },
              "poll_id": false,
              "custom": {
                "type": "object",
                "properties": {
                  "order_id": { "type": "string", "pattern": "^ord_[0-9]+$" },
                  "priority": { "enum": ["low", "normal", "high"] }
                },
                "additionalProperties": false
              }
            }
          }
        }
      },
      "frozen_fields": ["custom.order_id"]
    }
  }
}
```

### 2. Issue a checked token

Your backend signs the user's token with the claim. The payload of the token:

```json
{
  "user_id": "john",
  "stream_check_writes": true,
  "exp": 1767225600
}
```

### 3. An accepted message

The client sends custom fields flat, as usual:

```js
await channel.sendMessage({
  text: "Can you ship it today?",
  order_id: "ord_1234",
  priority: "high",
});
```

The document has `order_id` and `priority` under `message.custom`, both allowed, so the message is stored.

### 4. A rejected message

```js
await channel.sendMessage({
  text: "Can you ship it today?",
  order_id: "ord_1234",
  discount: "50%",
});
```

`discount` is not one of the allowed custom fields, so the API returns:

```json
{
  "code": 141,
  "message": "SendMessage failed with error: \"message schema violation at /message/custom/discount: additionalProperties: property is not allowed (custom fields are sent flat on the wire, at the top level of the message, attachment or reaction)\"",
  "exception_fields": {
    "reason": "message_schema_violation",
    "path": "/message/custom/discount",
    "rule": "additionalProperties"
  },
  "StatusCode": 400,
  "duration": "3.42ms",
  "more_info": "https://getstream.io/chat/docs/api_errors_response",
  "details": []
}
```

### 5. A rejected edit

Changing the frozen `order_id` on the accepted message:

```js
await client.partialUpdateMessage(messageId, {
  set: { order_id: "ord_9999" },
});
```

`ord_9999` matches the pattern, but `order_id` is frozen, so the edit fails with `path` `/message/custom/order_id` and `rule` `frozen`:

```json
{
  "code": 141,
  "message": "UpdateMessagePartial failed with error: \"message schema violation at /message/custom/order_id: frozen: frozen field cannot change after the message is created (custom fields are sent flat on the wire, at the top level of the message, attachment or reaction)\"",
  "exception_fields": {
    "reason": "message_schema_violation",
    "path": "/message/custom/order_id",
    "rule": "frozen"
  },
  "StatusCode": 400,
  "duration": "2.87ms",
  "more_info": "https://getstream.io/chat/docs/api_errors_response",
  "details": []
}
```

The same requests made from your server, or with a token without the claim, are accepted.

---

For the most recent version of this documentation, visit [https://getstream.io/chat/docs/go-golang/message-schema/](https://getstream.io/chat/docs/go-golang/message-schema/).