---
title: Snippets, tracking and custom code
status: current
order: 13
---

# Snippets, tracking and custom code

Add Google Analytics, a Meta Pixel, a chat widget or a video embed without touching the site's code each time. There are three levels, from safest to most powerful, and all three work from the dashboard, the [API](../api/management.md#snippets) and the [MCP](../mcp/tools.md):

| Level | What | Who can set it | Goes live |
| --- | --- | --- | --- |
| 1. [Integrations](#integrations) | An **ID** for a known tool. Pluma writes its code | Anyone who can change the site's settings (owners, admins, their agents) | With the next build |
| 2. [Site-wide code](#site-wide-code) | Raw HTML for **every page**: `head` and `body_end` | Only people and agents with **code permission** | When a **person** with code permission publishes it |
| 3. [Code fields](#code-fields) | Raw HTML **inside a page**, in a field of type `code` | Only people and agents with **code permission** | When a **person** with code permission publishes the entry |

Your site's frontend does the printing, once: it reads `head` and `body_end` from Pluma and puts them in its layout, and it renders `code` fields unescaped. See [Render it](#render-it-astro-and-next).

## Integrations

Paste only the ID; Pluma checks its format and generates the tool's standard snippet. **Settings → Integrations → Analytics and tracking**, or `update_integrations` / `PATCH /api/v1/spaces/:space_id/integrations`.

| Tool | Key | ID looks like | Goes in |
| --- | --- | --- | --- |
| Google Analytics 4 | `google_analytics` | `G-ABC123DEF4` (measurement ID) | `head` |
| Google Tag Manager | `google_tag_manager` | `GTM-ABC1234` | `head`, plus its `<noscript>` in `body_end` |
| Meta Pixel | `meta_pixel` | `123456789012345` (digits) | `head`, plus its `<noscript>` image in `body_end` |
| Hotjar | `hotjar` | `3456789` (site ID, digits) | `head` |
| Microsoft Clarity | `clarity` | `abcd1234ef` (project ID) | `head` |
| Plausible | `plausible` | `example.com` (the domain in Plausible) | `head` |

- An ID that doesn't fit its format is refused with [`validation_failed`](../errors/validation_failed.md) and an example of the right one, and nothing is saved. `null` or `""` turns a tool off.
- IDs aren't code, so there's no draft: they're in `head` / `body_end` right away and reach visitors with the site's **next build**. Deploy hooks that rebuild on publish also rebuild on this change (the `snippets.changed` event, see [Webhooks](../api/webhooks.md)).
- Google Tag Manager's `<noscript>` officially goes right after `<body>`; Pluma puts it in `body_end`, where it works the same for the rare visitor without JavaScript.
- If a tool has an ID here, **don't** also paste its code in site-wide code: it would count every visit twice.

## Site-wide code

For anything without an ID: a chat widget, a cookie banner, a verification meta tag. Two places:

- **`head`**: at the end of `<head>`. For what must load early (verification tags, consent scripts).
- **`body_end`**: right before `</body>`. For widgets and scripts that can load last.

In **Settings → Code**, or with `code: { "head": "…", "body_end": "…" }` in the same `PATCH /integrations` (a place you don't send keeps its code; `""` empties it).

It's versioned like an entry: **every save is a new version, as a draft**. The site only ever gets the **published** version, with any key, staging included: an unreviewed draft never runs anywhere. Settings → Code lists the versions; restoring one makes it the new draft. Status is `none`, `draft` (never published), `published` or `changed` (a draft newer than what's live).

## Code fields

A field of type **Code** (`code`) holds raw HTML inside a page: a video or map embed, a booking widget, a form from another service. Add it to any content type, like a `section_embed` section that a [composable page](composable-pages.md) can use:

```json
{ "name": "Embed", "api_id": "section_embed", "kind": "section",
  "fields": [ { "api_id": "title", "name": "Title", "type": "symbol" },
              { "api_id": "embed", "name": "Code", "type": "code", "help": "The embed code from YouTube, Calendly, Typeform…" } ] }
```

- The Delivery API returns the **raw string**, exactly as saved. Your frontend renders it **unescaped, only for this field type** (every other text field stays escaped).
- In the dashboard it's a monospace box. Without code permission you can see it, not change it.
- Saving a changed code field needs code permission. **Publishing** an entry whose code fields gained or changed code needs a **person** with code permission; removing code doesn't.

## Who can change code

Code permission (`manage_code`) is **off for everyone** until an owner turns it on, even for owners:

1. **People:** in **Settings → Team**, an owner sets **Code: on** for a person (themselves too). Not for viewers.
2. **Agents:** someone with code permission sets **Code: on** for one agent, in **Assistants**. It works only while the person who connected that agent has code permission too. New agents never get it by default.
3. **Keys:** `management` keys never write code.

What each one can do:

| | Save code (draft) | Publish code |
| --- | --- | --- |
| Person with code permission | Yes | Yes, in the dashboard |
| Agent with code permission | Yes | **No**: a person publishes it |
| Anyone else | No: [`key_cannot`](../errors/key_cannot.md) | No |

- Without the permission, a write that changes code gives `key_cannot` (`details.needs: "manage_code"`) with a `fix` that says who can give it.
- An agent that publishes an entry with new code, or tries to make site-wide code live, gets `key_cannot` (`details.needs: "person_with_manage_code"`), and the `fix` sends a person to the dashboard page where they publish it (`details.publish_in`). The draft stays saved.

## The check

Every save of code (site-wide or a code field) is read by Pluma, and the answer carries `warnings`, one plain sentence each. It never blocks a save: it tells whoever publishes what they're about to put on the site.

- **The domains it loads from:** `<script src>`, `<iframe src>`, `<link href>`, images and media, form actions, and URLs Pluma can spot inside scripts (`fetch(`, `XMLHttpRequest.open(`, `.src =`, quoted `https://…`). Code that loads from a domain you don't know is the first thing to ask about.
- **Red flags:** `http:` URLs (not `https:`), `document.cookie`, `eval(`, `new Function(`, inline event handlers (`onclick=`, `onerror=`…), and long base64-looking strings (obfuscated code).

Site-wide code also returns them structured, in `check`: `{ "domains": ["widget.example.com"], "flags": [ { "flag": "eval", "message": "…" } ] }`. The dashboard shows the same next to the draft and under each code field.

## Render it: Astro and Next

Read the snippets once per build with your `delivery` key (`GET /api/v1/spaces/:space_id/integrations`, see [Delivery](../api/delivery.md#snippets)). `head` and `body_end` are ready-made HTML: the integrations' snippets plus the published custom code.

**Astro**, in the layout every page uses:

```astro
---
// src/layouts/Base.astro
const res = await fetch(`https://pluma.so/api/v1/spaces/${import.meta.env.PLUMA_SPACE}/integrations`, {
  headers: { Authorization: `Bearer ${import.meta.env.PLUMA_DELIVERY_KEY}` },
})
const snippets = res.ok ? await res.json() : { head: "", body_end: "" }
---
<html>
  <head>
    <slot name="head" />
    <Fragment set:html={snippets.head} />
  </head>
  <body>
    <slot />
    <Fragment set:html={snippets.body_end} />
  </body>
</html>
```

And a component for `code` fields:

```astro
---
// src/components/CodeField.astro: ONLY for fields of type code
const { code } = Astro.props
---
{code && <Fragment set:html={code} />}
```

**Next.js** (App Router). React doesn't run `<script>` tags set with `dangerouslySetInnerHTML`, so parse the HTML and let `next/script` run the scripts, or print the raw string in the static HTML. The simplest reliable way is a small client component that inserts it as real DOM:

```tsx
// app/raw-html.tsx: ONLY for Pluma's head/body_end and code fields
"use client"
import { useEffect, useRef } from "react"

export function RawHtml({ html }: { html: string }) {
  const ref = useRef<HTMLDivElement>(null)
  useEffect(() => {
    if (!ref.current || !html) return
    // createContextualFragment runs <script> tags, unlike innerHTML
    ref.current.replaceChildren(document.createRange().createContextualFragment(html))
  }, [html])
  return <div ref={ref} style={{ display: "contents" }} />
}
```

```tsx
// app/layout.tsx
import { RawHtml } from "./raw-html"

async function snippets() {
  const res = await fetch(`https://pluma.so/api/v1/spaces/${process.env.PLUMA_SPACE}/integrations`, {
    headers: { Authorization: `Bearer ${process.env.PLUMA_DELIVERY_KEY}` },
    next: { revalidate: 300 },
  })
  return res.ok ? res.json() : { head: "", body_end: "" }
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const { head, body_end } = await snippets()
  return (
    <html>
      <body>
        <RawHtml html={head} />
        {children}
        <RawHtml html={body_end} />
      </body>
    </html>
  )
}
```

The `head` code runs from the body here, which works for analytics and widgets. A verification `<meta>` tag must be in the real `<head>`: for those, prefer the tool's own way (for Google, verify by DNS) or render the page statically and inject the string into `<head>` at build time.

A `code` field in a section uses the same component: `<RawHtml html={section.fields.embed} />`.

## Security notes

- **Raw code runs with your site's full power.** It can read what visitors type, change any page, and send data anywhere. That's why code needs its own permission, a person to publish, and the check on every save.
- **Render unescaped only what Pluma marks as code:** `head`, `body_end` and `code` fields. Every other field is text; render it escaped, as your framework does by default.
- **Read the check before publishing.** A domain you don't recognize, or a red flag, is a question to ask whoever wrote it, especially when an agent wrote it.
- **Give code permission to few people**, and to agents only while they need it. Take it away in Team or Assistants; it stops at once.
- **Prefer integrations** for known tools: an ID can't carry anything but that tool's standard snippet.
- **Content-Security-Policy:** if your site sends one, add each domain the check lists to it, or the browser blocks the code.
- **History:** every version of site-wide code and every entry version is kept, with who saved it, and the site's activity says who published it.
