# Blocks

A blocks field builds a page from ordered, typed sections stored inside the entry - how to define block types, the JSON they produce and when to link instead.

Most pages are a stack of sections: a hero, a few features, a quote, a call to action. A `blocks` field holds that stack inside the page's own entry. Editors add, reorder and remove sections, each section has its own typed fields, and your front end gets an ordered list to render.

Use blocks for sections that belong to one page. For content shared between pages, link to it with a [reference field](/docs/concepts/links).

## Define the block types

A blocks field has a palette of **block types**. Each block type has an API id, a label and its own fields. They live in the field's `config.blocks`.

### In the app

Under **Content model**, add a field of type **Blocks** and describe the block types as text. A line with no indent starts a block type, written `id: Label`. The indented lines under it are its fields, written `name: type`.

```text block types
hero: Hero
  heading: symbol!
  body: rich_text
  image: media
quote: Quote
  text: text!
  author: symbol
  tone: select(light, dark)
```

A `!` after the type makes the field required. The options of a select go in brackets.

### Over the API

Send the same thing as a field definition. `blocks` maps each block type's id to its `label` and `fields`, and each field is an ordinary [field definition](/docs/concepts/field-types).

```bash
curl -X POST https://mojimoto.com/api/v1/acme/manage/content-types/page/fields \
  -H "Authorization: Bearer mjmt_your_write_token" \
  -H "Content-Type: application/json" \
  -d '{
    "field": "sections",
    "definition": {
      "type": "blocks",
      "config": {
        "label": "Sections",
        "max": 12,
        "blocks": {
          "hero": {
            "label": "Hero",
            "fields": {
              "heading": { "type": "symbol", "config": { "label": "Heading", "required": true } },
              "image": { "type": "media", "config": { "label": "Image" } }
            }
          },
          "quote": {
            "label": "Quote",
            "fields": {
              "text": { "type": "text", "config": { "label": "Text", "required": true } },
              "author": { "type": "symbol", "config": { "label": "Author" } }
            }
          }
        }
      }
    }
  }'
```

| Config key | Description |
| --- | --- |
| `blocks` | Required. At least one block type, keyed by API id, each with at least one field. `label` defaults to the id made readable. |
| `min`, `max` | The fewest and most blocks an entry may have. `min` is not checked on an empty field, so set `required` to insist on at least one block. |

Labels and descriptions set through the API are kept when the block types are edited in the app.

## Write blocks

A blocks value is an array. Each item names its block type in `type` and holds that block's fields in `data`. The order of the array is the order of the page.

```json request body
{
  "type": "page",
  "uid": "home",
  "data": {
    "title": "Home",
    "sections": [
      {
        "type": "hero",
        "data": { "heading": "Welcome", "image": { "asset_id": 7, "fit": "cover" } }
      },
      {
        "type": "quote",
        "data": { "text": "It keeps for days.", "author": "Sam" }
      }
    ]
  }
}
```

Values inside `data` use the same shapes as fields on the entry itself. Media is `{ "asset_id", "fit" }`, for example. To change one block, send the whole array again.

## How blocks come back

The read API returns the blocks in order, in the entry's `data`. Each has an `id`, its `type` and its `data`, with media expanded to the full file object and rich text as an array of nodes.

```json
{
  "sections": [
    {
      "id": "9f2c41d07a",
      "type": "hero",
      "data": {
        "heading": "Welcome",
        "image": {
          "id": 7,
          "url": "https://.../hero.jpg",
          "alt": "A table laid for breakfast",
          "width": 2400,
          "height": 1200,
          "content_type": "image/jpeg",
          "fit": "cover"
        }
      }
    },
    {
      "id": "c07be1a5d3",
      "type": "quote",
      "data": { "text": "It keeps for days.", "author": "Sam" }
    }
  ]
}
```

Blocks are part of the entry. They need no `depth`, and they are published, unpublished and translated with the entry. An empty blocks field is `[]`.

## Block ids

Every block has an `id`, a short string meant as a render key.

- A block added in the app gets a random id and keeps it.
- A block written over the API with an `id` keeps it. Any string will do.
- A block written without one is given an id made from its position and content. The same block in the same place gets the same id. Change its text or move it and the id changes.

For stable keys, read the ids back after the first write and send them with later writes.

## What is checked at publish

A draft is not held to these rules. Publishing checks the field, then each block's fields with the usual rules, and answers `422`. Error keys count blocks from 0 and messages count them from 1.

| Problem | Error key | Message |
| --- | --- | --- |
| A required field in a block is empty | `sections.0.data.heading` | `Sections, block 1 (Hero): Heading is required.` |
| The block's `type` is not one the field defines | `sections.1` | `Sections, block 2: unknown block type. Use one of: hero, quote.` |
| Fewer blocks than `min` | `sections` | `Sections needs at least 2 blocks.` |
| More blocks than `max` | `sections` | `Sections allows at most 12 blocks.` |
| The value is not an array | `sections` | `Sections must be a list of blocks, each {"type": ..., "data": {...}}.` |

```json 422
{
  "message": "Sections, block 1 (Hero): Heading is required.",
  "errors": {
    "sections.0.data.heading": ["Sections, block 1 (Hero): Heading is required."]
  }
}
```

## Render blocks

Map each block's `type` to a component or a template, and use `id` as the key.

```js
for (const block of page.data.sections) {
  switch (block.type) {
    case 'hero':
      renderHero(block.id, block.data)
      break

    case 'quote':
      renderQuote(block.id, block.data)
      break
  }
}
```

The [generated TypeScript types](/docs/tools/generated-types) include a union for each blocks field. For `sections` on `page` it is `PageSectionsBlock`, with one member per block type, so `block.data` is typed once you narrow on `block.type`.

## Blocks or references

Both can build a page from sections. A `references` field does it with separate entries, usually of a component type, that the page links to in order.

| | Blocks | References |
| --- | --- | --- |
| Where the section lives | Inside the page's entry | In its own entry |
| Used on more than one page | No | Yes |
| Publishing | With the page | On its own. The app offers to publish it with the page. |
| Reading | Always in `data` | Filled in by `depth`. A stub if it is not published. |
| Can link to other entries | No | Yes |
| Locales | Translated with the page | Translated on its own |
| Filtering a list | `[exists]` only | By the linked entry's id |

Choose blocks unless you need something from the right-hand column. A page can have both.

Do not store page sections in a `json` field. They would get no validation, no media handling and no editor.

## Limits

- A field inside a block can be `symbol`, `text`, `rich_text`, `number`, `boolean`, `date`, `select`, `media`, `location` or `json`.
- It cannot be a `reference`, `references`, `slug` or another `blocks` field, so blocks do not nest.
- Block type ids and the ids of fields inside them follow the rule for every API id. See [Content model](/docs/concepts/content-model).
- Removing a block type does not remove its blocks from existing entries. They are still returned, and the entry cannot be published again until they are taken out.
