> ## Documentation Index
>
> Fetch the complete documentation index at: https://www.cosmicjs.com/llms.txt
> Use this file to discover all available pages before exploring further.
>
> For a question these docs do not answer, such as which plan fits a team, read https://www.cosmicjs.com/agent.txt and ask Cosmic's concierge.
>
> Machine-readable API spec: https://www.cosmicjs.com/openapi.json

# Rich text & blocks

The `rich-text` Metafield is the recommended field for long-form, formatted
content. It stores **markdown prose** interleaved with `` tokens
that reference reusable **blocks**. The API stores and returns the value
verbatim, your app resolves the tokens when it renders.

## Value format

A `rich-text` value is a single string: markdown, plus zero or more block
tokens.
```text
## Welcome

Some **rich** prose, then a synced reusable block:

{{ cta /}}

And an editable, per-instance block (content lives inline):

{{ callout }}
This copy is unique to this page.
{{/ callout }}

```
- `` references a block by `name` (its shortcode slug). This is a
**synced** reference: its content is resolved from the block definition, so
editing the block in settings updates every synced instance.
- `...` is an **editable ("Edit on page")** instance: its
content lives inline between the tags rather than in settings, so it is unique
to this value. Authors create these in the editor with the block's "Edit on
page" action. A detached instance no longer syncs with the saved block, but
authors can "Reset to synced" to discard the inline edits and reference the
saved block again.
- Whitespace inside the braces is flexible: `` and `` are equivalent.
- Unknown tokens (no matching block definition) are preserved verbatim, never silently dropped.
- The reserved `` token references a live Cosmic Object inline (see [Inline object embeds](#inline-object-embeds)).

## Blocks

Blocks are reusable content snippets defined per Bucket in the dashboard under
**Settings -> Custom Blocks**, and stored on the Bucket at
`settings.content_blocks`.

| Field | Type | Description |
| --- | --- | --- |
| `name` | string | The block's shortcode slug, e.g. `cta`. Referenced as ``. |
| `title` | string | Human-friendly title shown in the editor. |
| `description` | string | Optional description shown in the editor. |
| `content` | string | The block body, authored as markdown (`rich-text`), plain text (`plain`), or raw HTML (`html`). |
| `editor` | string | How `content` is authored and rendered: `rich-text` (markdown), `plain` (escaped text), or `html` (rendered verbatim). |

## Inline object embeds

In addition to blocks, a `rich-text` value can reference a **live Cosmic Object**
inline. Unlike a block (whose content lives in Bucket settings), an embed points
at a real Object by `id`, so it always reflects the latest version of that
Object. Authors insert embeds in the editor via the slash command **Embed
object** or the toolbar.

Embeds use a reserved, self-closing `object` shortcode:
```text
Here is a related post:

{{ object type="posts" id="64f0c1abc1234567890abcde" slug="hello-world" /}}

```
- `id` is authoritative: it identifies the referenced Object.
- `type` is the Object type slug, used to pick a renderer.
- `slug` is included for readability and resilience.
- `object` and `objects` are reserved and cannot be used as block names.

The API stores and returns embeds verbatim, just like any other part of the
value. To render the referenced content, fetch the Object (optionally with
relationship depth) and resolve the embed when you render (see
[Inline object embeds](#inline-object-embeds) below).

## Get blocks (`GET` `/v3/buckets/:bucket_slug/blocks`)

Retrieve the Bucket's block definitions. This endpoint is read-key authed and
cached on the Bucket, so you can fetch it once and reuse the result across many
Objects. The same data is also available on the Bucket at
`settings.content_blocks`.

### Required parameters

- **`read_key`** (`string`): The Bucket read key.
```bash
curl https://api.cosmicjs.com/v3/buckets/${BUCKET_SLUG}/blocks \
    -d read_key=${BUCKET_READ_KEY} \
    -G

```
```js
import { createBucketClient } from '@cosmicjs/sdk'

const cosmic = createBucketClient({
  bucketSlug: BUCKET_SLUG,
  readKey: BUCKET_READ_KEY,
})

const { blocks } = await cosmic.blocks.find()
```

```json
{
  "blocks": [
    {
      "name": "cta",
      "title": "Call to action",
      "description": "Reusable CTA banner",
      "content": "## Ready to start?\n\n[Get started](https://app.cosmicjs.com)",
      "editor": "rich-text"
    }
  ]
}
```
---

## Rendering rich text

Fetch the Object (which carries the raw `rich-text` value) and the Bucket's
blocks, then resolve the tokens. The recommended pattern is to fetch blocks once
and reuse them.

```js
import { createBucketClient } from '@cosmicjs/sdk'

const cosmic = createBucketClient({
  bucketSlug: BUCKET_SLUG,
  readKey: BUCKET_READ_KEY,
})

const { object: post } = await cosmic.objects
  .findOne({ type: 'posts', slug: 'hello-world' })
  .props('slug,title,metadata')
  .depth(1)

const { blocks } = await cosmic.blocks.find()
```
### Official React renderer

[`@cosmicjs/rich-text`](https://www.npmjs.com/package/@cosmicjs/rich-text) parses the
value, resolves blocks against their definitions, and renders to React.

```tsx
import { RichText } from '@cosmicjs/rich-text'

export default function Post({ post, blocks }) {
  return <RichText value={post.metadata.body} blocks={blocks} />
}
```
```tsx
import { RichText, BlockProps } from '@cosmicjs/rich-text'

const Cta = ({ contentHtml }: BlockProps) => (
  <aside className="my-cta" dangerouslySetInnerHTML={{ __html: contentHtml }} />
)

;<RichText value={value} blocks={blocks} components={{ cta: Cta }} />
```

Each component receives `{ name, definition, contentHtml }`, where `contentHtml`
is the block's content already rendered to HTML: the inline content for an
editable instance, or the definition's content for a synced reference.

### Render to an HTML string (no React)

For non-React stacks (Vue, Svelte, Astro, server templates), import
`renderToHtml` from the `@cosmicjs/rich-text/html` entry point, which has no
React dependency. It returns a single HTML string.

```js
import { renderToHtml } from '@cosmicjs/rich-text/html'

const html = renderToHtml(post.metadata.body, { blocks })
```
```js
import { renderToHtml } from '@cosmicjs/rich-text/html'

const byId = new Map(related.map((o) => [o.id, o]))

const html = renderToHtml(post.metadata.body, {
  blocks,
  // Wrap each block however you like.
  blockWrapper: ({ name, innerHtml }) =>
    `<aside class="block block-${name}">${innerHtml}</aside>`,
  // Resolve inline object embeds to your own markup.
  resolveObjectHtml: ({ id }) => {
    const obj = byId.get(id)
    return obj ? `<a href="/posts/${obj.slug}">${obj.title}</a>` : undefined
  },
})
```

By default, blocks render to the same ``
wrapper as the React renderer, and unresolved object embeds render to a
`data-object` placeholder.

### Rendering inline object embeds

Object embeds render control-first: you provide a React component per Object type
and a `resolveObject` function that returns the referenced Object. Fetch the
parent Object with relationship depth so the referenced Objects are available,
then look them up by `id`.

```tsx
import { RichText, ObjectBlockProps } from '@cosmicjs/rich-text'

const PostCard = ({ object }: ObjectBlockProps) => {
  if (!object) return null
  return (
    <a href={`/posts/${object.slug}`} className="post-card">
      {object.title}
    </a>
  )
}

export default function Post({ post, blocks }) {
  // `post` was fetched with depth so related objects are embedded.
  const related = (post.metadata?.related ?? []) as any[]
  const byId = new Map(related.map((o) => [o.id, o]))

  return (
    <RichText
      value={post.metadata.body}
      blocks={blocks}
      objects={{ posts: PostCard }}
      resolveObject={({ id }) => byId.get(id)}
    />
  )
}
```
Each object component receives `{ id, type, slug, object }`. If you don't
register a component for a type, a default placeholder renders, the reference is
never silently dropped.

### Bring your own renderer

If you want full control, render the value yourself: run the markdown through
your renderer of choice and replace each `` token with your own
markup. The default `@cosmicjs/rich-text` renderer emits this wrapper per block:

```html
<div class="cosmic-block cosmic-block-cta" data-block="cta">
  <!-- block content rendered to HTML -->
</div>
```
For inline object embeds, parse the `` token's `id`, `type`,
and `slug` attributes and render however you like. The default renderer emits a
reference placeholder when no component is provided:

```html
<div class="cosmic-object" data-object="64f0c1abc1234567890abcde" data-object-type="posts">
  posts: hello-world
</div>

```
> Migrating from `html-textarea`? The legacy Froala field stores raw HTML and
> returns it as a string. `rich-text` stores markdown + block tokens instead, so
> render it with the patterns above rather than injecting raw HTML.

## FAQ

### How much does Cosmic cost?

Project plans are Free ($0), Builder ($99/mo), Team ($299/mo), Business ($499/mo), Enterprise (custom pricing). Yearly billing saves 10%. Workspace plans are Small Workspace ($999/mo) and Large Workspace ($2,999/mo), and they start with a 30-day free trial. Allowances, add-on rates, and the rest of the pricing FAQ are plain text at https://www.cosmicjs.com/pricing.md.

### Are API keys required, and is content private?

Each Bucket has a read key and a write key in Bucket Settings > API Access. GET requests use the read key. POST, PATCH, and DELETE use the write key as Authorization: Bearer. Do not put the write key in a browser bundle, a mobile app, or a NEXT_PUBLIC_ variable. SAML single sign-on is on Large Workspace and Enterprise. The audit log is append-only. Text versions: https://www.cosmicjs.com/security.md and https://www.cosmicjs.com/docs/dashboard/audit-log.md.

### Can an agent create a Cosmic project without an existing account?

Yes. POST https://dapi.cosmicjs.com/v3/agents/sign-up provisions a free-tier project and bucket tied to a human email, with no existing Cosmic account. The human claims it with the emailed one-time code. The playbook is https://www.cosmicjs.com/docs/ai-onboarding.md.
