`, which does not affect layout. Values that could break out of the stylesheet are dropped, so the CSS is safe to inline.
### Design tokens
[Section titled “Design tokens”](#design-tokens)
Register your brand colors and fonts so editors pick from them instead of typing hex codes:
lib/blocks.ts
```ts
import { registerTheme } from "@plenary/react";
registerTheme({
colors: [
{ name: "brand", value: "#2563eb", label: "Brand" },
{ name: "ink", value: "#0f172a", label: "Ink" },
],
fonts: [{ name: "font-display", value: "Georgia, serif", label: "Display" }],
});
```
app/globals.css
```css
:root {
--brand: #2563eb;
--ink: #0f172a;
--font-display: Georgia, serif;
}
```
Color pickers (text, background, border) offer `colors` first, and the Typography panel’s font picker offers `fonts`. Picking a token stores `var(--brand)`, not the hex value, so changing `--brand` in your CSS restyles every page that uses it. `value` is only the swatch the console displays. Every token must exist as a CSS custom property on your site.
## Image block variants
[Section titled “Image block variants”](#image-block-variants)
The built-in Image block can serve a resized copy of its image instead of the original. Its props are a one-off variant spec:
| Property | Prop | Meaning |
| ------------------- | --------- | -------------------------------------------------------------------------------------------------------------- |
| **Max Width (px)** | `width` | Output width in pixels |
| **Max Height (px)** | `height` | Output height in pixels |
| **Quality (%)** | `quality` | Encoding quality, 1 to 100 |
| **Crop to fill** | `crop` | Crop to fill `width` × `height` instead of fitting inside, centered on the image’s focal point when one is set |
Set at least a width or a height. When the entry is saved, the server queues the variant for generation. Reads of the entry then include `media.variant_url` on that Image block, and the renderer uses it as the `
![]()
` source. With no width or height, or with an invalid spec, the original is served. Identical specs on the same image share one generated file.
These are output pixels, not layout size: use the Style tab’s **Sizing** panel to control how large the image displays. The canvas always shows the original, because the variant is generated only after saving.
Only the built-in `image` block gets variants. Media props on your own components are passed through as the original plus any variants defined on the asset.
## The component manifest
[Section titled “The component manifest”](#the-component-manifest)
The console needs to know your components even when your site is not connected, to show the palette and property forms. Each time a preview connects, the bridge announces its manifest (every registered component and your theme), and the console stores it on the server, one per [site](/guides/sites/), whenever it differs from the stored copy. When no preview is connected, the console falls back to the stored manifest.
| Method and path | Permission | Description |
| --------------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- |
| `GET /api/v1/page-builder/manifest?site_key={site}` | `content:entries:read` on the site | The stored manifest: `{ "components": [...], "theme": {...}, "updated_at": "..." }` |
| `PUT /api/v1/page-builder/manifest?site_key={site}` | `content:entries:update` on the site | Replace it. Body: `{ "components": [...], "theme": {...} }` |
```bash
curl "https://your-instance.plenarycms.io/api/v1/page-builder/manifest?site_key=default" \
-H "Authorization: Bearer $PLENARY_ACCESS_TOKEN"
```
```json
{
"components": [
{
"name": "hero",
"label": "Hero",
"category": "Marketing",
"icon": "data:image/svg+xml,%3Csvg...",
"props": [{ "key": "heading", "type": "text", "required": true, "defaultValue": "Your headline here" }],
"slots": [],
"styles": ["size", "background", "typography", "css"]
}
],
"theme": { "colors": [{ "name": "brand", "value": "#2563eb", "label": "Brand" }] },
"updated_at": "2026-10-07T09:16:55.534Z"
}
```
The server stores component definitions as given. It rejects a manifest with more than 500 components, a component without a `name`, or duplicate names (`manifest_components_invalid` with `reason` `too_many`, `name_missing`, or `name_duplicate`), and bodies over 1 MiB (`manifest_too_large`). See [Errors](/reference/errors/).
One manifest per site
The stored manifest is per site, not per model or per preview URL. If two codebases preview models on the same site, whichever connected last owns the palette while no preview is connected. Keep one site’s preview targets on one registry, or use separate sites.
## Related
[Section titled “Related”](#related)
* [Live Preview](/guides/live-preview/): connecting your site to the canvas
* [Page Builder Site example](/examples/page-builder-site/): a complete Next.js site
* [@plenary/react](/sdk/react/) and [@plenary/core](/sdk/core/) reference
* [Field Types](/reference/field-types/): settings and UI options for props
# Settings
> Configure a self-hosted Plenary instance's email provider, SMS provider for sign-in codes, and media storage, and learn which settings live in plenary.yaml and which are locked on Plenary Cloud.
Instance settings control how Plenary sends email, sends SMS sign-in codes, stores media, and signs people in through an identity provider. An administrator sets them once per installation in the console, under **Admin Settings → Global Settings**. They apply to every site. Site-level options such as locales and timezone are on each site; see [Sites](/guides/sites/).
On **Plenary Cloud**, the platform manages email, SMS, and storage for you, and the Global Settings page is not shown; single sign-on stays yours to configure. See [Settings on Plenary Cloud](#settings-on-plenary-cloud).
## Where settings live
[Section titled “Where settings live”](#where-settings-live)
A self-hosted instance keeps configuration in two places:
* **`plenary.yaml`**, the server’s configuration file, holds anything the server needs before it can reach its database, and anything that describes the host: ports, the public URL, the database URL, secret key files, filesystem paths, logging, and tuning.
* **The database**, edited in the console, holds what the installation does: which email provider to use, which SMS provider, and where media goes.
| Setting | Where | Edited by |
| --------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| Server port, `public_url`, trusted proxies | `plenary.yaml` (`server`) | Whoever deploys the server |
| MongoDB URL | `plenary.yaml` (`mongodb`) | Deployer |
| Encryption and JWT signing key files | `plenary.yaml` (`secrets`) | Deployer |
| Token lifetimes | `plenary.yaml` (`auth.jwt`) | Deployer |
| Local media directory and temp directory | `plenary.yaml` (`storage.local_data_dir`, `storage.temp_dir`) | Deployer |
| Default locale and timezone for new sites | `plenary.yaml` (`locale`) | Deployer |
| Logging, webhook delivery tuning, schedule sweep interval | `plenary.yaml` (`logging`, `webhooks`, `content`) | Deployer |
| License file path | `plenary.yaml` (`license.file`) or `PLENARY_LICENSE` | Deployer; see [Licensing](/reference/licensing/) |
| Email provider | Database | Admin, in **Email Sending** |
| SMS provider | Database | Admin, in **SMS Sending** |
| Media storage backend | Database | Admin, in **File Storage** |
| Identity provider for single sign-on | Database, or seeded once from `plenary.yaml` (`single_sign_on`) | Admin, in **Single Sign-On**; see [Single sign-on](/reference/single-sign-on/) |
| Sites, locales, timezones | Database | Admin, in **Site Management**; see [Sites](/guides/sites/) |
The Global Settings endpoints are for super users only. No role or grant reaches them.
## Stored credentials
[Section titled “Stored credentials”](#stored-credentials)
Provider API keys, SMTP passwords, and AWS secret access keys are encrypted before Plenary stores them. They are write-only:
* No response ever returns a stored secret. The API returns `*_configured: true` and a `*_hint` with the last four characters (for secrets of twelve characters or more), so you can tell which credential is stored.
* Leaving a secret field out of a save keeps the stored value. Sending an empty string clears it.
* The console shows “A value ending … is stored. Leave this blank to keep it.”
The encryption key comes from the file named by `secrets.encryption_key_file` in `plenary.yaml`. **Back up that file with your database.** Without it, every stored credential is unreadable and must be entered again.
## Email sending
[Section titled “Email sending”](#email-sending)
Plenary sends email for user invitations, password resets, email address confirmations, email sign-in codes, and form notifications. Until a provider is configured and **Send email** is on, none of these are sent.
1. Go to **Admin Settings → Global Settings** and select **Email Sending**.
2. Choose a provider:
| Provider | Console label | Needs |
| ---------- | -------------------- | -------------------------------------------------------------------- |
| `ses` | AWS SES | Access key ID, secret access key, region, optional configuration set |
| `sendgrid` | SendGrid | An API key with Mail Send permission |
| `mandrill` | Mailchimp (Mandrill) | A Mandrill transactional API key |
| `smtp` | Custom SMTP | Host, port, username, password, encryption (STARTTLS, TLS, or none) |
3. Fill in the **Sender identity**: **From address**, **From name**, and optionally **Reply-to address**. The from address’s domain must be verified with your provider.
4. Click **Save changes**.
5. Click **Send test email**. The test goes to your own address and uses the saved settings, so save first.
Plenary builds the provider when you save. If the settings cannot produce a working provider, the save is refused with `422 email_settings_invalid` and a `reason`, so you find out while you can still see what you typed.
Each provider’s settings are kept when you switch to another one, so switching back loses nothing. A development installation also offers a **Development** provider that writes mail to the server log instead of sending it.
The email templates (invitation, password reset, sign-in code, email confirmation, form notification) are built into Plenary and are not edited in the console.
Below the provider list, the panel shows the last 24 hours of sends: status, template, provider, a masked destination, and any failure message. It never shows message bodies or full addresses.
## SMS sending
[Section titled “SMS sending”](#sms-sending)
Plenary uses SMS for one thing: sign-in codes for users with two-factor sign-in, sent to their verified phone number. Plenary always generates the code; the provider only delivers it inside a message the provider composes. Neither provider sends arbitrary text.
1. Go to **Admin Settings → Global Settings** and select **SMS Sending**.
2. Choose a provider:
**Twilio Verify** (`twilio`)
* **Account SID** and **Auth token**.
* **Verify service SID**, which starts with `VA`.
* In the Twilio console, enable **Custom Verification Code** on that Verify service. Twilio refuses Plenary’s codes until you do. There is no from number to configure.
**AWS End User Messaging Notify** (`aws`)
* **Access key ID**, **Secret access key**, and **Region**.
* **Notify configuration ID**, which starts with `nc-`. The configuration owns the sender identity.
* Optional **Template ID** for a pre-approved code-verification template. Leave it blank to use the configuration’s default.
* Optional **Configuration set**.
3. Click **Save changes**.
4. Enter a **Test recipient** and click **Send test message**. The test sends a real code, which you can ignore.
Choose **SMS Disabled** to stop all text messages. The provider settings are kept for when you turn SMS back on.
While SMS is disabled, the console hides the SMS phone field and the two-factor switch on users, and users with two-factor sign-in receive their codes by email, if their email address is verified. A two-factor user with no usable destination cannot sign in. See [Users & Permissions](/guides/users-and-permissions/#two-factor-sign-in).
## File storage
[Section titled “File storage”](#file-storage)
**File Storage** decides where the Media Library keeps uploaded files and their generated variants.
| Backend | Console label | Configured where |
| ------- | ------------- | ------------------------------------------------------------------------------------------------------------------ |
| `local` | Local disk | Nothing to set here. Files go under `storage.local_data_dir` in `plenary.yaml`, normally a mounted volume. |
| `s3` | AWS S3 | **Access key ID**, **Secret access key**, **Region**, **Bucket**, optional **Key prefix**, and **Public base URL** |
**Public base URL** is where public objects are served from: the bucket’s own URL or a CDN in front of it.
Media URLs do not depend on the backend. Every file is addressed as `/media/{media_id}/{filename}` on your instance, and Plenary redirects to the bucket when the file is stored there. URLs already inside published content keep working when you change backends.
Switching backends affects new uploads only. Files already stored stay where they are and are still served. Plenary does not copy existing media between backends.
### S3 bucket setup
[Section titled “S3 bucket setup”](#s3-bucket-setup)
* Public assets must be publicly readable, either directly or through the CDN at your **Public base URL**.
* Private assets are stored under `{prefix}private/`. Your bucket policy must **not** grant public read on that path, or private files become public. Plenary hands out short-lived signed URLs for private assets and never links to that path directly.
* **Key prefix** lets one bucket hold more than one installation.
* Public files are stored with `Cache-Control: public, max-age=86400`, so a browser or CDN may keep serving a file for up to a day after you make it private. Private files are not cached.
For private media in the Media Library, see [Media Library](/guides/media-library/).
### AWS credentials
[Section titled “AWS credentials”](#aws-credentials)
Each AWS-backed setting (SES, End User Messaging, S3) carries its own access key ID and secret access key, entered on its own panel. You can use the same IAM user for all three or a separate least-privilege user for each.
## Locale and timezone defaults
[Section titled “Locale and timezone defaults”](#locale-and-timezone-defaults)
Two `plenary.yaml` keys supply defaults when a site is created without them:
plenary.yaml
```yaml
locale:
default: en-us
timezone: America/Denver
```
* `locale.default` becomes a new site’s default locale when you do not choose one.
* `locale.timezone` becomes a new site’s timezone (an IANA name). With no value, sites default to `UTC`.
After a site exists, change its locales and timezone on the site itself. See [Sites](/guides/sites/) and [Localization](/guides/localization/).
## Settings API
[Section titled “Settings API”](#settings-api)
| Method | Path | Does |
| ------------ | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `GET`, `PUT` | `/api/v1/settings/email-sending` | Read or replace the email binding |
| `POST` | `/api/v1/settings/email-sending/test` | Send a test email: `{"to": "you@example.com"}` |
| `GET`, `PUT` | `/api/v1/settings/sms-sending` | Read or replace the SMS binding |
| `POST` | `/api/v1/settings/sms-sending/test` | Send a test code: `{"to": "+15551234567"}` |
| `GET`, `PUT` | `/api/v1/settings/file-storage` | Read or replace the storage backend |
| `GET` | `/api/v1/settings/message-deliveries?channel=email` | Recent sends (`channel` is `email` or `sms`) |
| `GET`, `PUT` | `/api/v1/settings/single-sign-on` | Read or replace the identity provider connection; see [Single sign-on](/reference/single-sign-on/) |
| `POST` | `/api/v1/settings/single-sign-on/test` | Check a connection without saving it |
| `POST` | `/api/v1/settings/single-sign-on/saml/regenerate-key` | Replace the SAML signing key pair |
All require a super user’s session. A `GET` returns every provider’s block plus `available_providers` (or `available_backends`):
```json
{
"enabled": true,
"provider": "ses",
"from_address": "cms@example.com",
"from_name": "Example CMS",
"reply_to": "",
"ses": {
"access_key_id": "AKIAEXAMPLE",
"secret_access_key_configured": true,
"secret_access_key_hint": "Q4bZ",
"region": "us-east-1",
"configuration_set": ""
},
"sendgrid": { "api_key_configured": false, "api_key_hint": "" },
"mandrill": { "api_key_configured": false, "api_key_hint": "" },
"smtp": {
"host": "",
"port": 0,
"username": "",
"password_configured": false,
"password_hint": "",
"tls_mode": "",
"timeout_seconds": 0
},
"available_providers": ["ses", "sendgrid", "mandrill", "smtp"]
}
```
On `PUT`, send the secret fields (`secret_access_key`, `api_key`, `password`, `auth_token`) only when you change them. With `"enabled": false`, the binding is saved without validation, so you can turn a channel off without completing its fields. Changes take effect without a restart.
Errors are listed under [Settings errors](/reference/errors/#settings).
## Settings on Plenary Cloud
[Section titled “Settings on Plenary Cloud”](#settings-on-plenary-cloud)
On Plenary Cloud the platform provisions email, SMS, and storage, and owns your license. The console shows a **Subscription** page instead of Global Settings and License, and a **Single Sign-On** page of its own, because your identity provider is yours to connect. These endpoints answer `403 cloud_managed`:
* `/api/v1/settings/email-sending` and its `/test`
* `/api/v1/settings/sms-sending` and its `/test`
* `/api/v1/settings/file-storage`
* `/api/v1/settings/message-deliveries`
* `/api/v1/license` and `/api/v1/settings/license`
`/api/v1/settings/single-sign-on` works the same on Cloud as on a licensed self-hosted instance.
Sites, users, roles, API keys, metrics, and all content features work the same on Cloud and self-hosted. To check which edition you are talking to, `GET /api/v1/health` returns `"edition": "cloud"` or `"on-prem"`. See [Plenary Cloud](/getting-started/cloud/).
## Related
[Section titled “Related”](#related)
* [Sites](/guides/sites/): per-site name, locales, timezone, and site webhooks.
* [Self-hosted](/getting-started/self-hosted/): installing and configuring `plenary.yaml`.
* [Licensing](/reference/licensing/): installing a license on a self-hosted instance.
* [Media Library](/guides/media-library/): private assets and folders.
# Sites
> Run several websites or apps from one Plenary instance with sites, including site keys, locales and timezones, which models a site offers, site-restricted API keys, and site webhooks.
A **site** is one website or app that an instance serves content to. One Plenary instance can hold several sites, such as a marketing site, a docs site, and a mobile app, or one site per brand or region. Every entry belongs to exactly one site, each site has its own locales and timezone, and API keys can be limited to specific sites. A new instance starts with one site whose key is `default`.
## The site object
[Section titled “The site object”](#the-site-object)
```json
{
"key": "default",
"name": "Rocky Mountain Synod",
"is_active": true,
"default_locale": "en-us",
"locales": ["en-us", "es-mx"],
"timezone": "America/Denver",
"config": {},
"created_at": "2026-06-26T00:00:00Z"
}
```
| Property | Type | Meaning |
| ---------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `key` | string | Permanent identifier. Lowercase letters, digits, and underscores, starting with a letter. Appears as `site_key` on entries and in `?site_key=`. |
| `name` | string | Display name, shown in the console’s site switcher. |
| `description` | string or `null` | Optional. |
| `is_active` | boolean | Whether the site is active. See [Deactivate a site](#deactivate-a-site). |
| `default_locale` | string | The locale used when a read or write does not name one. Must be in `locales`. |
| `locales` | array of strings | The locales content may be written in. See [Localization](/guides/localization/). |
| `timezone` | string | IANA timezone such as `Europe/Berlin`. Used for schedule inputs and stats. |
| `config` | object | Free-form JSON stored with the site. |
## Manage sites in the console
[Section titled “Manage sites in the console”](#manage-sites-in-the-console)
Sites live under **Admin Settings → Site Management**. Only a super user can create or delete a site; editing a site’s settings needs `admin:sites:update` on that site, which its Admin role has.
* **Create**: select **New** in the **Sites** rail. Enter a **Name** and **Key**, then **Create site**. The key cannot be changed later.
* **Edit**: select a site to change its **Name**, **Timezone**, **Locales** (with **Add locale** and **Make default**), and active state, then save.
* **Webhooks**: each site has its own webhooks. See [Site webhooks](#site-webhooks).
* **Delete**: select **Delete site** and type the key to confirm.
Everyone working in the console picks a site from the console’s site switcher. The **Content** catalog, entry lists, and dashboards show the selected site.
## Manage sites with the API
[Section titled “Manage sites with the API”](#manage-sites-with-the-api)
Site management is an administrative task, so it needs a signed-in user’s token rather than an API key.
| Method | Path | Permission | Notes |
| -------- | ------------------------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `GET` | `/api/v1/sites` | any signed-in user or private key | Lists every site. Public keys get `403`. |
| `POST` | `/api/v1/sites` | Super user | Body: `key`, `name`, and optional `description`, `is_active`, `default_locale`, `locales`, `timezone`, `config`. |
| `PUT` | `/api/v1/sites/{site_key}` | `admin:sites:update` | Body: `name` (required) and the fields to change. |
| `DELETE` | `/api/v1/sites/{site_key}?confirm_key={site_key}` | Super user | Add `&purge_content=true` if the site has entries. |
```bash
curl -X POST "https://your-instance.plenarycms.io/api/v1/sites" \
-H "Authorization: Bearer $PLENARY_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"key": "app",
"name": "Mobile App",
"default_locale": "en-us",
"locales": ["en-us", "fr-ca"],
"timezone": "America/Toronto"
}'
```
On create:
* `default_locale` defaults to the instance default locale (`locale.default` in `plenary.yaml`, `en-us` unless changed).
* `locales` defaults to just the default locale. A list that leaves out the default is refused (`422 site_default_locale_not_allowed`).
* `timezone` defaults to the instance timezone (`locale.timezone`), or `UTC`.
* A taken key returns `409 site_key_taken`.
On update, an omitted `default_locale`, `locales`, `timezone`, or `config` keeps its stored value. An omitted `description` is cleared, and an omitted `is_active` sets the site active, so send both when you want to keep them.
## Timezone
[Section titled “Timezone”](#timezone)
A site’s `timezone` is an IANA name such as `America/Denver`. The console uses it when editors set **Schedule publish** and **Schedule unpublish** on an entry: the times they type are in the site’s timezone, and the editor shows “Timezone: America/Denver” under the inputs. The API always stores and returns UTC, so changing the timezone later does not move schedules already saved. The console’s stats for the site use the same timezone.
## Models on a site
[Section titled “Models on a site”](#models-on-a-site)
Every content model, form, and object model belongs to exactly one site, named by its `site_key`. A model created in the console belongs to the site selected in the site switcher; through the API, send `site_key` when you create it. A model cannot move to another site afterwards (`422 model_site_key_immutable`).
* The **Content** catalog shows the models that belong to the selected site.
* Model keys are unique within a site only, so two sites can each have a `page` model with its own fields and entries. A request that names a model by key passes `?site_key=` (a site-bound API key implies it); when two sites use the key and no site is given, the response is `422 model_site_key_required`.
* A model’s `reference` and `object` fields may only point at models on the same site (`422 model_reference_cross_site`).
To give two sites the same structure, create the model on each site, for example by pushing the same [YAML file](/reference/model-yaml/) to both.
## Read content from a site
[Section titled “Read content from a site”](#read-content-from-a-site)
Pass the site key on every content read:
```bash
curl "https://your-instance.plenarycms.io/api/v1/content/article?site_key=app&locale=en-us" \
-H "X-API-KEY: $PLENARY_API_KEY"
```
With the SDK, set `siteKey` once on the client and override it per call if one app reads several sites:
lib/plenary.ts
```ts
import { createClient } from "@plenary/client";
export const plenary = createClient({
baseUrl: process.env.PLENARY_BASE_URL!,
apiKey: process.env.PLENARY_API_KEY!,
siteKey: "app",
locale: "en-us",
});
export async function getMarketingHome() {
return plenary.getSingleton("home", { siteKey: "marketing" });
}
```
A read with no `site_key` is not limited to one site: a list returns entries from every site the caller can read, and a slug lookup can match an entry on any of them. Always send `site_key` when your instance has more than one site.
## API keys and sites
[Section titled “API keys and sites”](#api-keys-and-sites)
Every **public** API key belongs to exactly one site, its `site_key` (`422 api_key_sites_required` without one):
* Reads return only entries from the key’s site.
* A `site_key` naming another site returns `403 permission_denied`.
* Reads without `?site_key=` use the key’s site and its default locale.
A leaked public key therefore exposes only one site’s published content.
A **private** API key usually belongs to one site too: its grants are held to that site, and a grant naming another site is refused (`422 api_key_grant_site_mismatch`). A super user can create an instance-wide private key instead, whose grants may each name a site. Roles work like a site-bound key: each role belongs to one site. See [API Keys](/guides/api-keys/) and [Permissions](/reference/permissions/).
## Site webhooks
[Section titled “Site webhooks”](#site-webhooks)
Besides webhooks on each model, a site can have its own webhooks that fire for changes to **any** model or form on that site. Use them for site-wide jobs such as rebuilding a static site or clearing a CDN cache. Configure them on the site in **Site Management**, or with `GET` and `PUT /api/v1/sites/{site_key}/webhooks`. See [Webhooks](/guides/webhooks/) for events, payloads, and signing.
## Deactivate a site
[Section titled “Deactivate a site”](#deactivate-a-site)
Turning a site **Inactive** keeps its content and media. Inactive sites drop out of the console’s site switcher.
## Delete a site
[Section titled “Delete a site”](#delete-a-site)
Deleting a site removes it and its webhooks.
* The last remaining site cannot be deleted (`400 site_last_site`).
* A site that still has content entries or form entries is refused (`400 site_has_entries`) unless you pass `purge_content=true`, which permanently deletes them. Purged entries record no revisions and cannot be restored. In the console, tick **Also permanently delete this site’s entries**.
* A site that still owns content models or forms is refused (`400 site_has_models`). Delete its models first.
* `confirm_key` must equal the site key (`400 site_key_confirm_mismatch`). Public keys assigned only to a deleted site stop returning content.
## Related
[Section titled “Related”](#related)
* [Localization](/guides/localization/): locales and translations.
* [Content Models](/guides/content-models/): creating a model on a site.
* [API Keys](/guides/api-keys/): public keys per site.
* [Webhooks](/guides/webhooks/): model and site webhooks.
# Transformers
> Write JavaScript transformers that change or reject an entry while it is being saved, learn what the sandbox allows (and why there is no regex), and see tested examples.
A **transformer** is a short JavaScript script attached to a content model. Plenary runs it every time an entry of that model is created or updated, after the request is parsed and before the values are validated and stored. A transformer can change the entry’s values (fill a slug, normalize a phone number, derive a label) or refuse the save with a message for the editor.
Transformers run inside the save. To react to a change after it is saved, for example to notify another system, use a [webhook](/guides/webhooks/) instead.
```js
// Derive a display label from the numeric price.
data.price_label = data.price === null ? 'Free' : `$${data.price.toFixed(2)}`
```
## When transformers run
[Section titled “When transformers run”](#when-transformers-run)
| Write | Transformers run |
| ----------------------------------------------------------------- | ----------------------------------------------------------------- |
| Creating an entry (console or `POST /api/v1/content/{model_key}`) | Yes, with `ctx.operation` = `"create"` |
| Updating an entry (console or `PUT /api/v1/content/{entry_id}`) | Yes, with `ctx.operation` = `"update"` |
| Restoring an entry from a revision | Yes: a revert runs as `"update"`, an undelete as `"create"` |
| Publishing or unpublishing without editing | No |
| [Form entries](/guides/forms/) | No. Forms accept public input, and transformers do not run on it. |
Within one save:
1. Text values are trimmed (for text fields with trimming on).
2. Every **active** transformer runs, in the order listed on the model. Each one sees the previous one’s changes.
3. Empty values are cleared, then the result is validated against the model’s fields and rules.
4. The entry is stored, a revision is recorded, and webhooks are queued.
Because transformers run before validation, everything a transformer writes is held to the same rules as an editor’s input; a transformer cannot store a value the model would refuse. Its changes are simply part of the saved entry, so they appear in revision history and webhook payloads. Computed fields are rendered after validation, so a transformer reading a computed field sees its value from before this save.
## Add a transformer in the console
[Section titled “Add a transformer in the console”](#add-a-transformer-in-the-console)
1. Open the model’s **Settings** from **Content** and go to the **Transformers** tab.
2. Click **Add transformer**, give it a **Name**, and write the **Script**.
3. Leave **Active** on. A paused transformer is kept but does not run.
4. Use **Move up** and **Move down** to put transformers in the order they should run, then click **Save model**.
The script is checked when you save the model. If it uses something the sandbox does not allow, the save is refused with the reason and the line and column, for example `Transformer "Slug from title" is not valid: a regular expression is not available (line 1, column 36)`.
Managing transformers needs the `content:transformers:manage` capability, which can be scoped to one model. It is deliberately separate from the webhooks capability. Transformers are stored on the model, so every change to one is a model revision, and they are part of the model’s YAML file (`transformers: [{ name, source, active }]`); see [Models as code](/guides/models-as-code/).
## Configure transformers through the API
[Section titled “Configure transformers through the API”](#configure-transformers-through-the-api)
```bash
curl -X PUT https://your-instance.plenarycms.io/api/v1/models/MODEL_ID/transformers \
-H "Authorization: Bearer $PLENARY_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"transformers": [
{ "name": "Price label", "source": "data.price_label = data.price === null ? \"Free\" : `$${data.price.toFixed(2)}`", "active": true }
]
}'
```
`MODEL_ID` is the model’s UUID. The array replaces the model’s transformers and sets their order. Include an existing transformer’s `id` to update it; omit `id` to create one. `active` defaults to `true`. The response returns the saved array, each item with `id`, `name`, `event` (always `before_save`), `source`, and `active`.
| Status | Code | Meaning |
| ------ | ----------------------------- | ----------------------------------------------------------------------------------------------------- |
| 422 | `transformer_name_required` | A transformer has no name. `vars.index` |
| 422 | `transformer_source_required` | A transformer has no script. `vars.index`, `vars.name` |
| 422 | `transformer_source_invalid` | The script does not parse or uses something not allowed. `vars.message` includes the line and column. |
| 422 | `transformer_not_found` | An `id` names no existing transformer. |
| 422 | `transformer_duplicate` | The same `id` appears twice. |
## What a script can read and change
[Section titled “What a script can read and change”](#what-a-script-can-read-and-change)
A script gets two variables:
| Name | Contents | Writable |
| ------ | --------------------------------------------- | ---------------------------------------------- |
| `data` | The entry’s field values, keyed by field key. | Yes. Assign to `data.
` (or nested paths). |
| `ctx` | Read-only facts about the save. | No |
`ctx` contains:
| Property | Example | Description |
| --------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `ctx.operation` | `"create"` | `"create"` or `"update"`. |
| `ctx.model` | `"event"` | The model key. |
| `ctx.site_key` | `"default"` | The `site_key` query parameter of the request, or `""` if it was not sent. |
| `ctx.locale` | `"en-us"` | The `locale` query parameter of the request, or `""` if it was not sent. |
| `ctx.now` | `"2026-10-07T09:15:46Z"` | The time of the save as an RFC 3339 UTC string, the same for every transformer in the save. |
| `ctx.actor` | `{ "type": "user", "label": "editor@example.com" }` | Who is saving. `type` is `user`, `api_key`, or `system`. |
How values look in `data`:
* Every field the model declares is present, even if this entry has no value for it. Unset values are `null`. An `object` field is always an object, so `data.address.city` reads `null` rather than throwing. Only a typo in a key gives `undefined`.
* A `select` field holds its stored value (`"CO"`), not its label (`"Colorado"`).
* `date` values are strings like `"2026-11-01"`, so `<` and `>` compare them correctly.
* Calling a method on a `null` value throws. Guard first: `if (data.phone) { … }` or `data.notes?.trim()`.
What gets saved: the submitted values plus any key the scripts changed. Setting a field the request did not include adds it. To clear a field, assign `null`.
## The sandbox
[Section titled “The sandbox”](#the-sandbox)
A transformer is plain JavaScript restricted to a fixed set of language features. The restriction is enforced when you save the model, by checking the script’s syntax tree against an allowlist, not at run time. A script that passes the check cannot reach anything outside `data` and `ctx`.
**Allowed:**
* `const`, `let`, `var`; `if`/`else`; `for`, `while`, `do…while`; `break`, `continue`; `return` (to stop early); `throw` (to [refuse the save](#refuse-a-save)).
* Literals, template strings, array and object literals, arithmetic, comparison, logical and bitwise operators, `??`, `?.`, `typeof`, `in`, the ternary operator, `++`/`--` on your own variables and on `data`.
* Calling these methods on any value: `toUpperCase`, `toLowerCase`, `trim`, `trimStart`, `trimEnd`, `substring`, `slice`, `charAt`, `charCodeAt`, `indexOf`, `lastIndexOf`, `includes`, `startsWith`, `endsWith`, `split`, `replace`, `replaceAll`, `repeat`, `padStart`, `padEnd`, `concat`, `at`, `toString`, `normalize`, `localeCompare`, `toFixed`, `toPrecision`, `join`.
* `Math.round`, `floor`, `ceil`, `abs`, `min`, `max`, `pow`, `sqrt`, `trunc`, `sign`; `JSON.stringify`, `JSON.parse`; `Number.isInteger`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`; `String.fromCharCode`; `Array.isArray`; `undefined`, `NaN`, `Infinity`.
**Not allowed** (refused when you save):
| Not available | Use instead |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Regular expressions (`/…/`, `RegExp`) | `includes`, `startsWith`, `endsWith`, `split`, `replaceAll`, `indexOf`, or a character loop |
| `fetch`, `require`, `import`, timers, any I/O | A [webhook](/guides/webhooks/) for anything that calls another system |
| `Date`, `Math.random` | `ctx.now` for the current time |
| Function declarations, arrow functions, `class`, `new`, `this`, `eval` | Inline code; loops |
| Calling anything except a listed method, such as `Number(x)` or `String(x)` | `Number.parseFloat(x)`, `` `${x}` `` or `x.toString()` |
| `try`/`catch` | Guard with `if` and `?.` before the call that could fail |
| `switch`, `for…of`, `for…in`, labels, the comma operator, destructuring, spread, getters and setters | `if`/`else if`; an index-based `for` loop |
| Array methods `map`, `filter`, `reduce`, `forEach`, `push`, `pop`, `sort`, `reverse`, `splice` | A `for` loop that builds a new array with `concat`, then assign it |
| Assigning to `ctx` or replacing `data` itself | Assign to `data.` |
| The `delete` operator | Assign `null` to clear a field |
| `constructor`, `prototype`, `__proto__` | |
### Why there are no regular expressions
[Section titled “Why there are no regular expressions”](#why-there-are-no-regular-expressions)
The script engine hands any pattern it cannot compile natively to a backtracking matcher, and a running match cannot be interrupted by the time limit. One badly shaped pattern applied to a long value could hang the request indefinitely. Rather than let a single expression take down a save, the sandbox refuses regular expressions entirely. String methods and character loops cover the common cases, as the examples below show. (Field validation is separate: a `text` field’s `regex` validation rule is still available.)
### Time limit
[Section titled “Time limit”](#time-limit)
A transformer that is still running after **200 ms** is stopped and the save is refused with `entry_transformer_timeout`. The limit is fixed. It exists to stop an accidental infinite loop from holding a request.
## Refuse a save
[Section titled “Refuse a save”](#refuse-a-save)
`throw` a message to reject the save. Nothing is stored, later transformers do not run, and the editor sees your text:
```js
if (data.starts && data.ends && data.ends < data.starts) {
throw { field: 'ends', message: 'An event cannot end before it starts.' }
}
```
Throw either a non-empty string or an object with a string `message` and an optional `field`. With `field`, the console shows the message under that field. The API answers `422`:
```json
{
"error": {
"code": "entry_transformer_rejected",
"vars": {
"field": "ends",
"message": "An event cannot end before it starts.",
"transformer": "Date order"
}
}
}
```
The message is sent exactly as written; Plenary does not translate it. Branch on `ctx.locale` if editors work in several languages. Transformers run before validation, so a rejection is reported before any ordinary field errors. A refusal applies to restores too: restoring an old revision that breaks a newer rule is refused the same way.
## Errors editors can see
[Section titled “Errors editors can see”](#errors-editors-can-see)
| Code | When | `vars` |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| `entry_transformer_rejected` | The script threw a message on purpose. | `transformer`, `message`, optional `field` |
| `entry_transformer_failed` | The script crashed, for example by calling a method on `null`, or threw something that is not a message (`throw 42`). | `transformer`, `message`, and `line`/`column` when known |
| `entry_transformer_timeout` | The script ran longer than 200 ms. | `transformer`, `message` |
All three are `422` and nothing is saved. A crash looks like this:
```json
{
"error": {
"code": "entry_transformer_failed",
"vars": {
"transformer": "Trim notes",
"message": "TypeError: Cannot read property 'trim' of undefined or null",
"line": 1,
"column": 19
}
}
}
```
In the console the editor sees `The "Trim notes" transformer failed: …`. A failing transformer blocks every save of that model until it is fixed or paused, so test new scripts on a draft entry.
## Examples
[Section titled “Examples”](#examples)
Each example below was run against a live instance. Field keys are placeholders for your own.
### Slugify a title
[Section titled “Slugify a title”](#slugify-a-title)
Fills `url_slug` from `title` when the editor left it empty: lowercases, strips accents, and joins runs of letters and digits with single hyphens. `" Café Résumé Night! "` becomes `"cafe-resume-night"`.
```js
// Fill url_slug from the title when the editor left it empty.
if (!data.url_slug && data.title) {
const allowed = 'abcdefghijklmnopqrstuvwxyz0123456789'
const source = data.title.toLowerCase().normalize('NFKD')
let slug = ''
let pendingDash = false
for (let i = 0; i < source.length; i++) {
const ch = source.charAt(i)
if (ch >= '̀' && ch <= 'ͯ') continue // accent marks: drop them
if (allowed.includes(ch)) {
if (pendingDash && slug.length > 0) slug += '-'
slug += ch
pendingDash = false
} else {
pendingDash = true
}
}
data.url_slug = slug
}
```
### Normalize a phone number
[Section titled “Normalize a phone number”](#normalize-a-phone-number)
Keeps only digits, accepts 10-digit US numbers with or without a leading `1`, stores them in E.164 form, and refuses anything else under the field. `"(303) 555-0142"` becomes `"+13035550142"`.
```js
// Keep only digits, then store US numbers as +1XXXXXXXXXX.
if (data.phone) {
let digits = ''
for (let i = 0; i < data.phone.length; i++) {
const ch = data.phone.charAt(i)
if ('0123456789'.includes(ch)) digits += ch
}
if (digits.length === 11 && digits.startsWith('1')) digits = digits.substring(1)
if (digits.length !== 10) {
throw { field: 'phone', message: 'Enter a 10-digit US phone number.' }
}
data.phone = `+1${digits}`
}
```
### Compute a field
[Section titled “Compute a field”](#compute-a-field)
Writes a display label from a `number` field. `12.5` becomes `"$12.50"`; an empty price becomes `"Free"`.
```js
// Derive a display label from the numeric price.
data.price_label = data.price === null ? 'Free' : `$${data.price.toFixed(2)}`
```
For a value that is purely a template of other fields, such as a title made of a first and last name, a computed field is simpler. Use a transformer when the value needs logic or must be validated like typed input.
### Stamp new entries only
[Section titled “Stamp new entries only”](#stamp-new-entries-only)
```js
if (ctx.operation === 'create' && !data.received_on) {
data.received_on = ctx.now.substring(0, 10) // "2026-10-07"
}
```
## Conditional field visibility
[Section titled “Conditional field visibility”](#conditional-field-visibility)
The same sandbox powers conditional field visibility. On a field in the model editor, set **Editor visibility** to **Visible on condition** and write an expression in **Show this field when**. In the API and YAML, this is the field’s `visible_when` property:
```js
data.event_type === 'online'
```
A visibility condition differs from a transformer in three ways:
* It is a single expression that produces a value. It cannot assign, loop, or throw.
* It can read `data` but not `ctx`, because the console evaluates it while the editor types, without server context. Every field it reads must exist on the model; a condition naming an unknown field is refused when you save the model.
* It has a 50 ms time limit.
The console hides the field while the condition is false, and the server reaches the same answer on save: a hidden field is exempt from `required` and from its validation rules, and keeps whatever value it already had. If a condition throws while the editor is typing, the field is shown.
## Related
[Section titled “Related”](#related)
* [Content models](/guides/content-models/)
* [Fields](/guides/fields/)
* [Webhooks](/guides/webhooks/): react after a save
* [Model YAML](/reference/model-yaml/)
* [Errors](/reference/errors/)
# Users & Permissions
> Add people to a Plenary instance, make them a super user or give them a role on each site, build roles from grants, and set up common arrangements such as a one-site editor or a form-entry reader.
Every person who signs in to the console is a **user**. A user’s access is one of two things: the **super user** flag, which passes every check and alone manages users, roles, sites, and global settings; or a **role per site**, where each role is a named list of **grants** that reach that site and nothing else. A grant allows one capability, optionally narrowed to one content model or form. Use this page to invite people, choose their access, and build roles for common team setups.
Access is deny-by-default and allow-only: a user can do only what some grant allows, and nothing can take access away except removing a grant or a role. The full capability list is in the [Permissions reference](/reference/permissions/).
## Users
[Section titled “Users”](#users)
A user is an account, not content. Its fields are fixed on every Plenary instance:
| Field | Notes |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `username` | Unique. Stored in lowercase. The sign-in handle; it cannot be changed in the console after the user is created. |
| `email` | Unique. Required. Invitations, password resets, and email sign-in codes go here. |
| `sms_phone` | Unique when set. E.164 format (`+15551234567`). Used for SMS sign-in codes. The console accepts a US number such as `(415) 555-0192`. |
| `first_name`, `last_name` | Required. |
| `display_name` | Optional. Shown instead of the full name across the console. |
| `avatar` | Optional image from the Media Library. |
| `is_active` | An inactive user cannot sign in. Turning it off signs them out everywhere; their content and history stay. |
| `is_email_verified`, `is_sms_phone_verified` | Sign-in codes go only to verified destinations. |
| `is_2fa_enabled` | Require a one-time code at sign-in. |
| `is_super_user` | Full access everywhere, plus user, role, site, and settings management. See [Super users](#super-users). |
| `site_roles` | The user’s role on each site, as `[{ "site_key", "role_key" }]`, at most one per site. See [Site access](#site-access). |
| `identities` | Identity-provider links, written only by single sign-on. See [Single sign-on users](#single-sign-on-users). |
You cannot add custom fields to users. To store more about a person (a job title, a bio, a department), create a content model with a [`user` field](/reference/field-types/) that points at the account, such as a `staff_profile` collection with `account`, `job_title`, and `bio` fields. That model gets revision history, publishing, site scoping, and Content API delivery like any other.
### Invite a user
[Section titled “Invite a user”](#invite-a-user)
Only a super user can manage users. Under **Access Management → Users**:
1. Click **New user**.
2. Fill in **Email**, **Username**, **First name**, and **Last name**. **Display name**, **SMS phone**, and **Avatar** are optional.
3. Choose the access. Either turn on **Super user**, or leave it off and pick a role for each site in the **Site access** card. A site left at **No access** is one the user cannot see.
4. Leave **Active on create** on unless the account should wait.
5. Click **Create & send invite**.
Plenary emails the user a link to set their own password. The link is valid for 24 hours. Email sending must be configured first; see [Settings](/guides/settings/). An email address or phone number that an administrator enters is marked verified automatically.
To create a user through the API, `POST /api/v1/users` as a super user. Send `"password": null` and `"password_reset_required": true` to email the same set-password link:
```bash
curl -X POST https://your-instance.plenarycms.io/api/v1/users \
-H "Authorization: Bearer $PLENARY_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"username": "jsmith",
"email": "jsmith@example.com",
"first_name": "Jane",
"last_name": "Smith",
"is_active": true,
"is_super_user": false,
"site_roles": [
{ "site_key": "marketing", "role_key": "editor" },
{ "site_key": "docs", "role_key": "reviewer" }
],
"password": null,
"password_reset_required": true
}'
```
`PUT /api/v1/users/{id}` replaces the user’s profile fields, so send every field each time, `is_super_user` included. Its `site_roles` array is optional: omit it to keep the user’s roles, or send `[]` to clear them. Each entry must name an existing site and a role on that site (`422 user_site_role_site_not_found`, `user_site_role_role_not_found`), and a site may appear once (`422 user_site_role_duplicate`).
### Super users
[Section titled “Super users”](#super-users)
A super user passes every permission check on every site and is the only kind of user who can:
* manage users and roles;
* create and delete sites;
* change Global Settings, install a license, and read usage;
* see the instance-wide counts on the dashboard;
* create and manage an instance-wide API key, one that belongs to no site.
The console hides **Users**, **Roles**, **Global Settings**, **License**, and **Subscription** from everyone else. No role or grant can reach those pages or their endpoints. Setup makes the first user a super user.
An instance always keeps at least one active super user. You cannot change your own **Super user** switch, deactivate yourself, or delete yourself (`403 user_super_user_self`, `user_deactivate_self`, `user_delete_self`), and nobody can clear the flag on, deactivate, or delete the last active super user (`409 user_last_super_user`). The console disables those controls when you are editing yourself.
A super user’s site roles are kept but idle while the flag is on, and apply again if it is turned off.
### Site access
[Section titled “Site access”](#site-access)
A user who is not a super user gets their access from the **Site access** card: one role per site, chosen from that site’s own roles. A role’s grants reach its site only, so **Admin** on a site is full access to that one site, including its API keys and site settings, and nothing on any other site and no user or role management. A user with no role on a site cannot see it; the console’s site selector lists only the sites where the user holds a role.
The user list’s **Access** column summarises this, with a **Super user** pill or the sites the user reaches, and the filter narrows the list to super users.
### Deactivate or delete a user
[Section titled “Deactivate or delete a user”](#deactivate-or-delete-a-user)
Open the user and use **Set status** to make them inactive. They are signed out everywhere and cannot sign in, and their content and history stay. This is the usual way to remove access.
Deleting is permanent. The console asks you to type the user’s email address. Through the API, pass the address as `email_confirm`: `DELETE /api/v1/users/{id}?email_confirm=jsmith@example.com`. You cannot delete yourself, and the last active super user cannot be deleted or deactivated.
### Two-factor sign-in
[Section titled “Two-factor sign-in”](#two-factor-sign-in)
Turn on **Two-factor auth** in the **Security** group of a user’s **Details** tab. At sign-in, after the password, Plenary sends a 6-digit code that expires in 10 minutes. The code goes to the user’s verified email address or verified SMS phone; when both are available, the user chooses.
SMS codes need an SMS provider; see [Settings](/guides/settings/). While no SMS provider is configured, the console hides the 2FA switch and the SMS phone field. Users cannot turn 2FA on or off for themselves. For the sign-in API, see [Authentication](/reference/authentication/).
### Single sign-on users
[Section titled “Single sign-on users”](#single-sign-on-users)
When the instance is connected to an identity provider (see [Single sign-on](/reference/single-sign-on/)), people can sign in with **Continue with single sign-on** instead of a password. The first such sign-in links the provider’s identity to the user’s account, matched by verified email address; or, if the connection creates accounts on first sign-in, it creates the user with the connection’s default role per site.
A user’s **Details** tab shows what that produced:
* **Linked identities** lists each provider the account is linked to, with the provider’s identifier for the person, the email at the time of linking, and the link date. **Unlink** removes one; the person can no longer sign in through that provider until a verified-email match links them again. It changes nothing else about the account.
* The **Password** row reads **SSO ONLY** for an account that was created by single sign-on and has no password. **Send set-password link** emails the usual set-password link, which gives the person a password as a fallback.
Single sign-on never changes a user’s site roles or super user status. When the connection has **Require single sign-on** on, everyone but a super user must sign in through the provider; super users keep their password as the fallback. Through the API, the identities are on `GET /api/v1/users/{id}` as `identities`, with `has_password`; `DELETE /api/v1/users/{id}/identities/{provider_key}` unlinks one.
### Passkeys
[Section titled “Passkeys”](#passkeys)
A user can sign in with a passkey instead of a password and code: Touch ID, Face ID, Windows Hello, a hardware security key, or a passkey synced by a password manager. The passkey’s own unlock counts as the second factor, so no one-time code is sent. Passkeys are available on every plan and need no setting; the sign-in page shows **Sign in with a passkey** in any browser that supports them.
Only the user can enrol one, because the browser creates it on their own device: in **Account Settings → Passkeys**, click **Add a passkey**, give it a name you will recognise, and follow the browser’s prompt. The card lists each passkey with when it was added and last used; **Rename** and **Remove** act on one. Removing a passkey does not sign the user out anywhere; it only stops that device signing in. The password stays and works as before.
A super user sees a user’s passkeys in the **Passkeys** card of the user’s **Details** tab and can **Remove** one, for a lost or stolen device. There is no way for an administrator to add a passkey to someone else’s account. Through the API, the passkeys are on `GET /api/v1/users/{id}` as `passkeys`; `DELETE /api/v1/users/{id}/passkeys/{passkey_id}` removes one. The sign-in API is on [Authentication](/reference/authentication/#passkeys).
When the instance has **Require single sign-on** on, passkeys are closed to everyone but a super user, like passwords.
### Account Settings
[Section titled “Account Settings”](#account-settings)
Each user manages their own account from **Account Settings** in the account menu. They can change:
* **Display name** and **Avatar**;
* **Email** and **SMS Phone**: a changed email address is marked unverified and Plenary emails a confirmation link valid for 30 minutes; a changed phone number is marked unverified;
* their **Password**: changing it signs them out on every other device;
* their **Passkeys**: add, rename, or remove one (see [Passkeys](#passkeys)).
Username, first name, and last name are shown but read-only. The super user flag, site roles, active status, and 2FA can only be changed by a super user.
Every signed-in user has this page; it needs no grant. Changing the avatar also needs `content:media:read` on some site, because the picker browses the Media Library; without it the avatar is shown read-only with a note to ask an administrator.
The same actions are available through the API at `GET` and `PUT /api/v1/me/account`, `PUT /api/v1/me/password`, and `/api/v1/me/passkeys`. These routes take no user id; they always act on the caller.
## Roles
[Section titled “Roles”](#roles)
A role is a named list of grants that belongs to **one site**. Its grants reach that site and nothing else, so the same key, such as `editor`, can mean different things on different sites. Only a super user manages roles, under **Access Management → Roles**, where the rail lists every site’s roles.
### Seeded roles
[Section titled “Seeded roles”](#seeded-roles)
Every site gets four roles when it is created:
| Role | For | Can |
| ------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| **Admin** | People who run the site | Everything on the site: content, models, forms, media, webhooks, transformers, API keys, and the site’s own settings. |
| **Developer** | People who build and integrate the site | All content work, including models, forms, webhooks, and transformers, plus managing the site’s API keys. |
| **Editor** | Day-to-day content staff | Create, edit, publish, and delete entries; manage media; triage form entries; read models, forms, and history. |
| **Reviewer** | People who approve content | Read entries, models, media, and history, and publish entries. |
**Admin** is a system role: it cannot be edited or deleted, and Plenary resets it to every capability at each startup, so a capability added in a release reaches every site’s Admin on upgrade. **Developer**, **Editor**, and **Reviewer** are starter roles: created with the site, then ordinary roles you can edit or delete. The exact grant lists are in the [Permissions reference](/reference/permissions/#system-roles).
### Create a role
[Section titled “Create a role”](#create-a-role)
1. Go to **Access Management → Roles** and click **New**.
2. Choose the **Site** the role belongs to. It cannot be moved to another site later.
3. Enter a **Name** and a **Key**. The key is a stable identifier, such as `blog_writer`, unique within the site, and cannot be changed after the role is created.
4. Optionally add a **Description**.
5. Tick the capabilities the role should have in the grant matrix. Rows are resources (Entries, Models, Media, Forms, Form entries, and so on); columns are verbs (Read, Create, Update, Delete, Publish, Manage).
6. To narrow a row to particular models or forms, open its **Scope** cell and choose **Selected models** or **Selected forms**. The scope applies to every verb ticked on that row. Leave the **Sites** axis at **All sites**: the role already belongs to one site, and a grant naming another site is refused.
7. Click **Create Role**.
To rename a role’s key, create a new role, move its users to it, then delete the old one. A role that users still hold cannot be deleted (`409 role_in_use`).
Through the API, `POST /api/v1/sites/{site_key}/roles` as a super user:
```bash
curl -X POST https://your-instance.plenarycms.io/api/v1/sites/marketing/roles \
-H "Authorization: Bearer $PLENARY_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"key": "blog_writer",
"name": "Blog Writer",
"description": "Writes and publishes the blog on the marketing site.",
"grants": [
{ "key": "content:models:read", "content_model_key": "blog_post" },
{ "key": "content:entries:read", "content_model_key": "blog_post" },
{ "key": "content:entries:create", "content_model_key": "blog_post" },
{ "key": "content:entries:update", "content_model_key": "blog_post" },
{ "key": "content:entries:publish", "content_model_key": "blog_post" },
{ "key": "content:media:read" },
{ "key": "content:media:create" }
]
}'
```
Roles can also live in version control as YAML; see [Models as Code](/guides/models-as-code/).
## Grants
[Section titled “Grants”](#grants)
A grant is one capability, optionally narrowed to one content model or form:
```json
{ "key": "content:entries:update", "content_model_key": "blog_post" }
```
* `key` is a capability such as `content:entries:update`.
* `content_model_key` limits the grant to one content model or form on the role’s site.
A grant with no filter applies to everything of its kind on the site, including models created later. A role’s grants carry no site filter of their own: the role’s site is applied when the user signs in, and the API reads each grant back with `site_key` filled in. Not every capability accepts a model filter:
* Entries, form entries, revisions, and the model, form, webhook, and transformer definitions accept one.
* Media accepts none; each site has its own Media Library, and a media grant covers all of it.
* The `admin:*` capabilities a role may hold, for API keys, site settings, and dashboard metrics, accept none.
A model filter on a capability that does not accept one is refused with `422 role_scope_not_allowed`, as is a filter naming a model that belongs to another site.
There are no direct grants on a user and no deny rules. If one person needs more than their role gives, assign them a different role or create one; if they need *less*, make a narrower role. `GET /api/v1/auth/me` returns the caller’s resolved grants, each labelled with `source: "site_role"`, its `site_key`, and the `role_key` it comes from, so you can see where access comes from.
## Common setups
[Section titled “Common setups”](#common-setups)
The first two setups need no custom role. The others are roles you create on the site in question; replace `marketing`, `blog_post`, and `contact` with your own site, model, and form keys.
### Editor on one site
[Section titled “Editor on one site”](#editor-on-one-site)
In the user’s **Site access** card, set **Editor** on `marketing` and leave every other site at **No access**. The console’s site selector shows only that site; the Media Library the editor sees is that site’s; asking for another site’s entries through the API returns `403 permission_denied`, and a single entry from another site returns `404`.
### Site administrator
[Section titled “Site administrator”](#site-administrator)
Set **Admin** on the site. That is full access to the site, including its API keys, webhooks, transformers, and site settings, but no access to any other site and no user, role, or global settings management. For those, the person needs the **Super user** switch.
### Contributor who drafts but does not publish
[Section titled “Contributor who drafts but does not publish”](#contributor-who-drafts-but-does-not-publish)
A writer who creates and edits drafts for someone else to publish. Create a role on the site with the **Editor** grants but leave out `content:entries:publish` (and `content:entries:delete` if they should not delete). Pair them with the **Reviewer** role, or an editor, who publishes.
| Capability | Filter |
| -------------------------------------------------------------------------- | --------------------------------------------------------- |
| `content:models:read`, `content:forms:read` | none |
| `content:entries:read`, `content:entries:create`, `content:entries:update` | none, or `content_model_key` to limit them to some models |
| `content:revisions:read` | none |
| `content:media:read`, `content:media:create`, `content:media:update` | none |
Caution
Plenary keeps one copy of each entry, not a separate draft of published content. A user with `content:entries:update` who edits an entry that is already published changes the live entry when they save. On a model set to **always published**, every save publishes. A contributor role keeps people from publishing new entries, not from editing published ones.
### Form-entry reader
[Section titled “Form-entry reader”](#form-entry-reader)
Someone who reads the entries of one form, for example a sales team member who follows up on the `contact` form, and nothing else. Create this role on the site the form belongs to:
| Capability | Filter |
| ----------------------------- | --------------------------------------------------------------------------------------- |
| `content:form_entries:read` | `content_model_key: contact` |
| `content:form_entries:update` | `content_model_key: contact` (optional: lets them mark entries read, archived, or spam) |
`content:form_entries:read` also lets them see the form’s definition, so no `content:forms:read` grant is needed. An **Editor** on the site already holds both capabilities for every form there.
## Related
[Section titled “Related”](#related)
* [Permissions reference](/reference/permissions/): every capability and the evaluation rules.
* [API Keys](/guides/api-keys/): access for integrations instead of people.
* [Authentication](/reference/authentication/): sign-in, codes, and tokens.
* [Sites](/guides/sites/): the sites that roles belong to.
# Webhooks
> Configure webhooks that POST JSON to your endpoint when entries change or forms are submitted, and build a receiver that authenticates, deduplicates, and answers correctly.
A **webhook** is an HTTP POST that Plenary sends to a URL you choose when something happens to an entry: it is created, updated, published, unpublished, or deleted, or a visitor submits a form. Use webhooks to revalidate a statically built site, reindex search, notify a chat channel, or push form entries into a CRM.
Webhooks fire after the change is saved and cannot alter or block it. To change data while it is being saved, use a [transformer](/guides/transformers/) instead.
## Where webhooks live
[Section titled “Where webhooks live”](#where-webhooks-live)
You attach a webhook to one of three things. Each fires for a different set of entries:
| Attached to | Fires for | Events it can subscribe to | Configured in |
| --------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| A content model | Entries of that model | `entry.created`, `entry.updated`, `entry.published`, `entry.unpublished`, `entry.deleted` | The model’s **Webhooks** tab |
| A form | [Form entries](/guides/forms/) of that form | `form.submitted` | The form’s **Webhooks** tab |
| A site | Entries of every model and every form on that site | All six | The site’s **Webhooks** tab under **Site Management** |
When an entry’s model has a webhook and its site also has one subscribed to the same event, both fire, as separate deliveries.
Site webhooks differ in three ways: they can send **All fields** or **No field data** but not **Selected fields** (they span models, so there is no single field list), so they never carry a private field; changes to them are not recorded in revision history; and they need a `content:webhooks:manage` grant that covers the whole site, not one scoped to a single model.
## Events
[Section titled “Events”](#events)
| Event | Fires when |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `entry.created` | An entry is created, or a deleted entry is restored. |
| `entry.updated` | An entry’s data changes, it is moved to another folder, or it is reverted to an earlier revision. |
| `entry.published` | An entry goes live, by an editor or by the scheduler. |
| `entry.unpublished` | An entry stops being live, by an editor or by the scheduler. |
| `entry.deleted` | An entry is archived or permanently deleted. Permanently deleting an entry that was already archived fires nothing more. |
| `form.submitted` | A visitor submits a form and the entry is not classified as spam. |
Some changes deliberately fire nothing: a save that changed no values (on models with **Track revision history** turned off, every save fires, because there is no previous revision to compare against), a save to a published entry (the edit is [pending](/guides/entries-and-publishing/#pending-changes-on-a-published-entry) and fires `entry.published` when it goes live), a model change that rewrites many entries at once (renaming or removing a field), status changes on form entries, and anything on media or users. On a model set to **always published**, a create arrives as `entry.created` with `status: "published"` and no `entry.published` follows.
The [Webhook events reference](/reference/webhook-events/) has the full payload for each event.
## Add a webhook in the console
[Section titled “Add a webhook in the console”](#add-a-webhook-in-the-console)
1. Open the model’s or form’s **Settings**, or the site under **Admin Settings → Site Management**, and go to the **Webhooks** tab.
2. Click **Add webhook** and fill in the dialog:
* **Name**: shown in the console and sent in the payload as `webhook.name`.
* **URL**: where Plenary POSTs. It must be `https://` unless the instance runs with `dev_mode: true`.
* **Events**: at least one.
* **Headers** and **Query parameters**: optional extras sent with every delivery. Turn on **Secret** for credentials (see [Secrets](#secrets)).
* **Fields**: **All fields** (every field except private ones), **Selected fields** (only the ones you tick, private fields allowed), or **No field data** (identity and timestamps only).
3. Save the page: **Save model**, **Save form**, or **Save** on the site. Webhook edits are staged with the rest of the page until you save.
Each webhook row has buttons to **Pause**/**Resume** it, open its **Deliveries**, edit it, and remove it. Pausing stops new deliveries from being queued; deliveries already queued still go out. Removing a webhook drops its queued deliveries.
Managing webhooks needs the `content:webhooks:manage` capability, which can be scoped to a single model or form. See [Permissions](/reference/permissions/).
## Configure webhooks through the API
[Section titled “Configure webhooks through the API”](#configure-webhooks-through-the-api)
A model’s or form’s webhooks are replaced as a whole array:
```bash
curl -X PUT https://your-instance.plenarycms.io/api/v1/models/MODEL_ID/webhooks \
-H "Authorization: Bearer $PLENARY_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"webhooks": [
{
"name": "Revalidate site",
"url": "https://www.example.com/api/plenary-webhook",
"events": ["entry.published", "entry.unpublished", "entry.updated", "entry.deleted"],
"headers": [{ "name": "X-Plenary-Secret", "value": "YOUR_SHARED_SECRET", "secret": true }],
"query": [],
"payload": { "mode": "all" },
"active": true
}
]
}'
```
| Path | For |
| ---------------------------------------------- | -------------------------------------------------- |
| `PUT /api/v1/models/{model_id}/webhooks` | A content model |
| `PUT /api/v1/forms/{form_id}/webhooks` | A form (`events` may only be `["form.submitted"]`) |
| `GET`, `PUT /api/v1/sites/{site_key}/webhooks` | A site |
`MODEL_ID` and `form_id` are UUIDs. `PLENARY_ACCESS_TOKEN` stands for a user session token or a private API key with `content:webhooks:manage` (send a key as `X-API-KEY` instead of `Authorization`).
Each webhook object:
| Field | Description |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `id` | Omit to create; include an existing id to update that webhook in place. |
| `name` | Required. |
| `url` | Required. Absolute `http` or `https` URL; `https` required outside `dev_mode`. |
| `events` | Required, non-empty. Events valid for what the webhook is attached to. |
| `headers`, `query` | Arrays of `{ "name", "value", "secret" }`. Omit `value` on an existing secret to keep the stored one. |
| `payload` | `{ "mode": "all" }`, `{ "mode": "none" }`, or `{ "mode": "selected", "fields": ["title", "slug"] }`. Sites cannot use `selected`. |
| `active` | Defaults to `true`. `false` pauses the webhook. |
The response returns the saved array with secret values as `null` and `"value_set": true`. A model’s or form’s webhooks are also included, masked the same way, in `GET /api/v1/models/{model_id}` or `GET /api/v1/forms/{form_id}`. Updating the model itself with `PUT /api/v1/models/{model_id}` ignores any `webhooks` key, so round-tripping a model read cannot overwrite them.
Validation errors are `422` with `vars.index` naming the webhook: `webhook_name_required`, `webhook_url_invalid`, `webhook_url_requires_https`, `webhook_events_empty`, `webhook_event_unknown`, `webhook_header_name_invalid`, `webhook_header_reserved`, `webhook_query_name_invalid`, `webhook_field_unknown`, `webhook_payload_mode_invalid`.
Webhooks are not included in `plenary metadata pull` exports, so they are not part of [models as code](/guides/models-as-code/). An import leaves existing webhooks in place.
## The request Plenary sends
[Section titled “The request Plenary sends”](#the-request-plenary-sends)
```http
POST /api/plenary-webhook?token=… HTTP/1.1
Content-Type: application/json
User-Agent: Plenary
X-Plenary-Event: entry.published
X-Plenary-Webhook-Id: 4fd822a7-d09b-48bc-841a-3895adf8604f
X-Plenary-Delivery-Id: 52a2ec34-f4ea-4c34-a0af-3af34aabe612
X-Plenary-Attempt: 1
X-Plenary-Secret: YOUR_SHARED_SECRET
```
Your custom headers are added after Plenary’s. They cannot override `Content-Type`, `User-Agent`, any `X-Plenary-*` header, or the transport headers `Host`, `Content-Length`, `Connection`, `Transfer-Encoding`, and `Upgrade`; the webhook is rejected at save time with `webhook_header_reserved` if you try. Configured query parameters are merged into the URL’s existing query string.
The body is JSON. An entry event looks like this (trimmed; see [Webhook events](/reference/webhook-events/) for every field):
```json
{
"event": "entry.published",
"delivery_id": "52a2ec34-f4ea-4c34-a0af-3af34aabe612",
"occurred_at": "2026-10-07T09:15:56.878Z",
"webhook": { "id": "4fd822a7-d09b-48bc-841a-3895adf8604f", "name": "Revalidate site" },
"model": { "id": "ebdad6b3-cdca-4e2f-9aa0-714afaa36dfd", "key": "event" },
"entry": {
"id": "a57b9776-9300-4eae-82d6-86660b3b0466",
"site_key": "default",
"locale": "en-us",
"slug": "cafe-night",
"path": "/",
"status": "published",
"created_at": "2026-10-07T09:15:35.829Z",
"updated_at": "2026-10-07T09:15:56.877Z",
"published_at": "2026-10-07T09:15:56.877Z"
},
"actor": { "type": "user", "id": "6063d721-3d78-4f06-b983-0aed7300408b", "label": "editor@example.com" },
"changed": ["published_at", "status"],
"revision_id": "94a6df68-d2c9-41d6-888e-35a6669e6dea",
"data": { "title": "Café Night", "price": 15 }
}
```
`data` holds the stored values, not resolved ones: a reference arrives as its stored reference object and an image as its media id, never a URL.
## Delivery and retries
[Section titled “Delivery and retries”](#delivery-and-retries)
Webhooks are delivered by a background worker, never inside the request that made the change. The editor’s save returns first, the delivery is queued, and the worker picks it up on its next sweep (every 10 seconds by default). By the time your endpoint receives a webhook, the change is already readable through the API.
| Your endpoint’s answer | Plenary’s outcome |
| ------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| Any `2xx` | **Delivered.** The body is read (up to 2 KB) and ignored. |
| `400`–`499`, except `408` and `429` | **Failed**, no retry. The same request would get the same answer. |
| `408`, `429`, any `5xx`, a connection error, or no answer within **10 seconds** | **Retried** on the schedule below. |
| After failed attempt | Next attempt in |
| -------------------- | ----------------------------------- |
| 1 | 30 seconds |
| 2 | 2 minutes |
| 3 | 10 minutes |
| 4 | 1 hour |
| 5 | 6 hours |
| 6 | none; the delivery is marked failed |
That is six attempts over a little more than seven hours. The URL, headers, and query parameters are read from the webhook at each attempt, so fixing a wrong URL or rotating a secret repairs pending retries. The body is fixed when the event happens, so a retry describes the event as it was, not the entry as it is now.
### At-least-once delivery
[Section titled “At-least-once delivery”](#at-least-once-delivery)
Plenary can send the same delivery more than once, for example if the worker stops after your endpoint answered but before the result was recorded. Every attempt of one delivery carries the same `X-Plenary-Delivery-Id` (also in the body as `delivery_id`), and every delivery has a different one, even when one event fans out to several webhooks. Deduplicate on it.
### Ordering
[Section titled “Ordering”](#ordering)
By default several deliveries are sent at once, so two quick edits to the same entry can arrive in either order. Compare `occurred_at` against the last value you stored for that entry and ignore older events. An operator who needs strict order can set the instance to deliver one at a time, oldest first:
plenary.yaml
```yaml
webhooks:
delivery: ordered # concurrent (default) | ordered
delivery_retention: 720h # how long delivery records are kept; 0 keeps them forever
sweep_interval: 10s # how often the worker looks for due deliveries
```
In `ordered` mode one slow endpoint delays every webhook on the instance. The per-attempt timeout and the retry schedule are fixed.
## Secrets
[Section titled “Secrets”](#secrets)
Mark a header or query parameter **Secret** for anything that is a credential. A secret value:
* is never returned by any API: reads show `null` with `"value_set": true`, and the console offers **Replace** rather than showing it;
* is replaced in revision history by a fingerprint, so history shows that a credential changed and when, without showing it;
* is never written to the delivery log, which records header and query parameter names only.
Marking a value secret after it was saved does not remove it from revisions already recorded. Secret values are stored in plain text in Plenary’s database, like other outbound credentials.
## Verify that a request came from Plenary
[Section titled “Verify that a request came from Plenary”](#verify-that-a-request-came-from-plenary)
Plenary does not sign webhook requests: there is no HMAC signature header. Authenticate deliveries with a shared secret instead:
1. Generate a long random string, for example with `openssl rand -hex 32`.
2. Add it to the webhook as a header (for example `X-Plenary-Secret`) or a query parameter (for example `secret`), with **Secret** turned on.
3. In your endpoint, compare the received value to your copy in constant time and answer `401` if it does not match.
`@plenary/client` does this for you. `parseWebhookRequest` checks the method, compares the `x-plenary-secret` header (or the `secret` query parameter) in constant time, and shape-checks the body. It throws a `PlenaryWebhookError` whose `status` is the code to answer with (`405`, `401`, or `400`), so a bad request fails fast instead of being retried for seven hours. If the secret you pass is empty, for example an unset environment variable, it rejects every request with `500`, and deliveries keep retrying until the secret is set.
app/api/plenary-webhook/route.ts
```ts
import {
isEntryWebhookPayload,
parseWebhookRequest,
PlenaryWebhookError,
} from "@plenary/client";
// Deliveries already handled, keyed by X-Plenary-Delivery-Id. Use a database
// or cache with a TTL in production; a module-level Set is per-process only.
const seen = new Set();
export async function POST(request: Request) {
const secret = process.env.PLENARY_WEBHOOK_SECRET;
if (!secret) {
return Response.json({ error: "PLENARY_WEBHOOK_SECRET is not set" }, { status: 500 });
}
let payload;
try {
// Checks POST, compares the x-plenary-secret header (or ?secret=) in
// constant time, and shape-checks the JSON body.
payload = await parseWebhookRequest(request, { secret });
} catch (err) {
if (err instanceof PlenaryWebhookError) {
return Response.json({ error: err.message }, { status: err.status });
}
throw err;
}
if (seen.has(payload.delivery_id)) {
return Response.json({ duplicate: true });
}
seen.add(payload.delivery_id);
if (isEntryWebhookPayload(payload)) {
console.log(payload.event, payload.model.key, payload.entry.id, payload.changed);
} else {
console.log(payload.event, payload.form.key, payload.form_entry.id);
}
// Answer quickly; queue slow work instead of doing it here.
return Response.json({ received: true });
}
```
Use other header or parameter names with `parseWebhookRequest(request, { secret, secretHeader: "x-my-header", secretQuery: "token" })`. For Next.js cache revalidation, `@plenary/next` builds on this; see the [revalidation example](/examples/revalidation/).
## Write a reliable receiver
[Section titled “Write a reliable receiver”](#write-a-reliable-receiver)
A correct endpoint:
1. **Answers within 10 seconds.** Queue slow work (reindexing, sending email) and return `2xx` immediately.
2. **Answers `2xx` only when it accepted the event.** A `200` that dropped the payload is invisible in the delivery log.
3. **Deduplicates on `X-Plenary-Delivery-Id`.**
4. **Tolerates reordering** by comparing `occurred_at`.
5. **Authenticates** with the shared secret.
6. **Answers `4xx` for requests it will never accept**, so the delivery fails at once and shows up in the log, rather than retrying for seven hours.
## Test a webhook and read the delivery log
[Section titled “Test a webhook and read the delivery log”](#test-a-webhook-and-read-the-delivery-log)
There is no “send test” button. To test a webhook, make a change it subscribes to: create or edit an entry, or submit the form. During development, point the URL at a request inspector or a tunnel to your machine (with `dev_mode: true` on the instance, plain `http` URLs are allowed).
Then open the webhook’s **Deliveries** drawer. It lists the 50 most recent deliveries, newest first, each with its status (**Queued**, **Sending**, **Delivered**, **Failed**), attempt number, response code or error, duration, and next attempt time. Expand a row to see the exact payload sent and the names of the headers and query parameters that went with it; values are never shown. The webhooks list shows each webhook’s last delivery at a glance.
The same data is available from the API:
| Path | Returns |
| ---------------------------------------------------------------- | ------------------------------- |
| `GET /api/v1/models/{model_id}/webhooks/{webhook_id}/deliveries` | The 50 most recent deliveries |
| `GET /api/v1/models/{model_id}/webhooks/health` | The latest delivery per webhook |
Forms use `/api/v1/forms/{form_id}/…` and sites `/api/v1/sites/{site_key}/webhooks/…` with the same suffixes. A delivery record:
```json
{
"id": "079e17ec-a910-4665-bb42-9296a4554b50",
"webhook_id": "d58e835b-cd59-4f13-ad61-a271802a3a2d",
"entry_id": "5659896a-9736-4834-9a1c-b460cdee2349",
"event": "form.submitted",
"status": "pending",
"attempt": 1,
"header_names": ["X-Plenary-Secret"],
"query_names": [],
"error": "Post \"https://hooks.example.com/plenary\": dial tcp: connect: connection refused",
"payload": { "event": "form.submitted", "delivery_id": "079e17ec-a910-4665-bb42-9296a4554b50" },
"created_at": "2026-10-07T09:13:47.24Z",
"next_attempt_at": "2026-10-07T09:14:21.02Z"
}
```
`status` is `pending`, `delivering`, `succeeded`, or `failed`; `status_code`, `duration_ms`, and `completed_at` appear once there is a response. Delivery records are deleted after 30 days by default (`webhooks.delivery_retention`).
## What webhooks do not do
[Section titled “What webhooks do not do”](#what-webhooks-do-not-do)
* They cannot block or modify a change. A non-2xx answer only affects retries.
* They do not reshape the body. Use field selection to send less; transform it on your side.
* They do not fire for model or schema changes, form entry status changes, media, or users.
## Related
[Section titled “Related”](#related)
* [Webhook events reference](/reference/webhook-events/): every event, payload, header, and retry rule
* [Revalidation example](/examples/revalidation/): Next.js cache invalidation from webhooks
* [`@plenary/client` webhook helpers](/sdk/client/)
* [Transformers](/guides/transformers/): change data before it is saved
# Plenary
> A hybrid CMS — structured content, a visual page builder, and an API-first core. Your front end renders it.
Model your content
Define [content models](/guides/content-models/) and [fields](/guides/fields/), then write, schedule, and translate entries in the console.
Build pages visually
Editors compose pages from your own components in the [Page Builder](/guides/page-builder/), with [live preview](/guides/live-preview/) of your real site.
Read it from anywhere
Fetch published content over the [Content API](/reference/content-api/), or with the [TypeScript SDK](/sdk/overview/) in Next.js and React.
Run it your way
Start on [Plenary Cloud](/getting-started/cloud/), or run the single Docker image [on your own infrastructure](/getting-started/self-hosted/).
Advanced features
Collect visitor input with [forms](/guides/forms/), notify other systems with [webhooks](/guides/webhooks/), and reshape data on save with [transformers](/guides/transformers/).
Building with an AI agent?
Point your agent at [`/llms.txt`](/llms.txt) for an index of every page, and read [Building with AI Agents](/getting-started/ai-agents/).
# Authentication
> How API callers authenticate to Plenary, with public and private API keys, user access and refresh tokens, two-factor sign-in, passkeys, token lifetimes, and authentication errors.
Every Plenary API request needs a credential. A site or integration uses an **API key**; a person (in the console, or through the CLI) uses a **user session**, a short-lived access token renewed with a refresh token. This page covers both at the level you need to call the API. For what each credential may do once authenticated, see [Permissions](/reference/permissions/).
## Credentials at a glance
[Section titled “Credentials at a glance”](#credentials-at-a-glance)
| Credential | Looks like | Send it as | Use it for |
| ----------------- | ----------- | ----------------------------------- | ------------------------------------------------------------------------------------------ |
| Public API key | `pln_pub_…` | `X-API-KEY` header | Reading published content and submitting forms from a site, app, or browser. |
| Private API key | `pln_prv_…` | `X-API-KEY` header | Server-side integrations: preview builds, imports, automation. Never ship it to a browser. |
| User access token | A JWT | `Authorization: Bearer ` | Acting as a signed-in person. Lasts 15 minutes by default. |
| Refresh token | `plr_rt_…` | JSON body of `/api/v1/auth/refresh` | Getting a new access token. Lasts 30 days by default. |
Create and manage API keys in the console under **Access Management → API Keys**. See [API keys](/guides/api-keys/) for the console steps.
## Send an API key
[Section titled “Send an API key”](#send-an-api-key)
Put the key in the `X-API-KEY` header:
```bash
curl -s "https://your-instance.plenarycms.io/api/v1/content/post?site_key=default&locale=en-us" \
-H "X-API-KEY: $PLENARY_API_KEY"
```
```ts
import { createClient } from "@plenary/client";
// The client sends apiKey as the X-API-KEY header on every request.
export const plenary = createClient({
baseUrl: process.env.PLENARY_BASE_URL!,
apiKey: process.env.PLENARY_API_KEY!,
siteKey: process.env.PLENARY_SITE_KEY ?? "default",
locale: process.env.PLENARY_LOCALE ?? "en-us",
});
```
The server also accepts the key as an `api_key` query parameter, for places that cannot set headers. The header wins when both are present. Query strings end up in logs and browser history, so prefer the header.
Caution
`Authorization: Bearer pln_pub_…` does **not** work. The `Authorization` header is only for user access tokens; an API key sent there is ignored and the request fails with `401 authentication_required`.
A value in `X-API-KEY` that does not start with `pln_pub_` or `pln_prv_` is not treated as a key at all, which also gives `401 authentication_required`.
## Public and private keys
[Section titled “Public and private keys”](#public-and-private-keys)
| | Public key (`pln_pub_…`) | Private key (`pln_prv_…`) |
| -------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------ |
| Access comes from | A fixed rule: read published content on the key’s site | The key’s own grants, like a role’s |
| Can hold grants | No | Yes, `content:*` capabilities only |
| Scoped by | The one **Site** chosen on the key | The key’s site, if it has one, and the model filters on its grants |
| Reads drafts | Only with **Include draft content** turned on | With `content:entries:read` |
| Sees private models and private fields | No | Yes, with `content:entries:read` |
| Writes | Form submissions only | Whatever its grants allow within `content:*` |
| Safe in a browser or mobile app | Yes | No |
| Value shown again after creation | Yes, from the key’s panel in the console | No, shown once; only a hash is stored |
**A public key** reaches the content read endpoints, the public form definition and form submission endpoints, and `GET /api/v1/media/{media_id}` for public assets. Every other endpoint returns `403 permission_denied`. Its exact read rules are in [Content API: public key restrictions](/reference/content-api/#public-key-restrictions).
**A private key** carries allow-only grants from the `content:` domain (entries, models, media, forms, form entries, webhooks, transformers, revisions). An `admin:*` grant is refused when the key is saved, with `422 api_key_grant_not_allowed`. Instance administration (users, roles, keys, settings) is done by people, not keys. See [Permissions](/reference/permissions/) for the capability list.
Use a public key for anything that renders content. Use a private key on a server when you need drafts, private fields, or writes, and keep it out of client bundles. In Next.js, a variable without the `NEXT_PUBLIC_` prefix stays on the server.
## Per-key restrictions
[Section titled “Per-key restrictions”](#per-key-restrictions)
Every key can carry these optional restrictions. They are checked during authentication, before the request reaches any endpoint.
| Setting (console label) | Effect | Refusal |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| **Expiry** | The key stops working after this date. Public keys default to no expiry. | `401 api_key_invalid` |
| **Allowed origins** | Only browser requests whose `Origin` matches may use the key. Entries are `scheme://host[:port]`; `https://*.example.com` admits every subdomain. Empty means any origin. | `403 api_key_origin_not_allowed` |
| **Rate limit (requests per minute)** | Requests over the limit in a rolling minute are refused. Empty means unlimited. | `429 rate_limited` |
| **Include draft content** | Public keys only: also read unpublished entries, for preview builds. | Not applicable |
Allowed origins only constrain browsers. Server-to-server requests send no `Origin` header and are never refused on origin grounds, so protect a server key by keeping it secret and limiting its grants.
Revoking a key in the console stops it immediately; requests with it then fail with `401 api_key_invalid`.
## Identify the current credential
[Section titled “Identify the current credential”](#identify-the-current-credential)
`GET /api/v1/auth/me` returns who the request is authenticated as. It works for any credential.
```bash
curl -s "https://your-instance.plenarycms.io/api/v1/auth/me" -H "X-API-KEY: $PLENARY_API_KEY"
```
```json
{
"principal": "api_key",
"key_id": "baa0bb46-45b8-4c13-96e6-b01d4b6b4b56",
"key_type": "public",
"name": "Website",
"grants": [],
"site_key": "default"
}
```
For a private key, `grants` lists the key’s grants (each with `"source": "key"`); `site_key` is `""` for an instance-wide key. For a user, `principal` is `"user"` and the body carries `user_id`, `role`, `role_name`, the resolved `grants` (each with `"source": "role"` or `"user"`), the `sites` the user can work in, and `sms_enabled`.
## User sessions
[Section titled “User sessions”](#user-sessions)
People authenticate with a username or email and a password, optionally followed by a one-time code; with a [passkey](#passkeys); or through the instance’s [single sign-on](#single-sign-on) provider. The result is the same token pair every way:
* An **access token**: a signed JWT, sent as `Authorization: Bearer `. It expires after 15 minutes by default.
* A **refresh token**: an opaque `plr_rt_…` string that mints new pairs. It expires after 30 days by default and is rotated on every use.
Most integrations never need a user session; use an API key instead. User sessions matter when you build a tool that acts as a specific person. The `plenary` CLI uses one and stores only the refresh token. See [CLI](/reference/cli/).
All `/api/v1/auth/*` endpoints below are unauthenticated: they issue or revoke credentials rather than consume them. Bodies are JSON.
### Sign in
[Section titled “Sign in”](#sign-in)
`POST /api/v1/auth/login`
```bash
curl -s -X POST "https://your-instance.plenarycms.io/api/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{"identifier": "jane@example.com", "password": "correct-horse-battery"}'
```
| Field | Description |
| ------------ | ------------------------------------------------------ |
| `identifier` | Email address or username, matched case-insensitively. |
| `password` | The password. |
Without two-factor authentication the response is the token pair:
```json
{
"status": "success",
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…",
"refresh_token": "plr_rt_Z9AcC…"
}
```
### Two-factor sign-in
[Section titled “Two-factor sign-in”](#two-factor-sign-in)
When the user has two-factor authentication turned on, `login` returns a challenge instead of tokens. `status` tells you what happened:
| `status` | Meaning | Next step |
| -------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `otp_sent` | Only one delivery method is available, and a code was sent to it. | Ask for the code, then call `/auth/login/otp/verify`. |
| `otp_required` | Several methods are available. | Let the user choose, call `/auth/login/otp/send`, then `/auth/login/otp/verify`. |
```json
{
"status": "otp_required",
"challenge_id": "a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
"otp_methods": { "email": "j***@example.com", "sms": "+1 *** *** 7890" }
}
```
The `otp_methods` values are masked. `sms` is offered only when an SMS provider is configured. The challenge expires after 10 minutes.
`POST /api/v1/auth/login/otp/send` with `{"challenge_id": "…", "otp_method": "email"}` (or `"sms"`) sends a code and answers `{"status": "otp_sent", "otp_method": "email"}`. Call it again to resend.
Text-message codes are budgeted per account: one a minute and five an hour, across every sign-in and challenge. A refused send answers `429` with `otp_sms_cooldown` or `otp_sms_throttled` and `vars.retry_after`, the seconds to wait (also in the `Retry-After` header); show it as a countdown and keep the resend control disabled until it reaches zero. When SMS is the only method and the budget is spent, `login` answers `otp_required` instead of `otp_sent` and sends nothing. An administrator can reset the budget from User Management. Email codes are not budgeted.
`POST /api/v1/auth/login/otp/verify` with `{"challenge_id": "…", "otp_code": "482910"}` completes sign-in and returns the same token pair as a direct login. Codes are 6 digits and expire 10 minutes after they are sent. Too many wrong codes lock the challenge; start a new login.
### Single sign-on
[Section titled “Single sign-on”](#single-sign-on)
A licensed instance can sign people in through one OpenID Connect or SAML 2.0 identity provider. The browser leaves for the provider from `GET /api/v1/auth/sso/{key}/start` (`key` is `oidc` or `saml`), comes back to Plenary’s callback, and is redirected to the console with a one-time login code. The console exchanges the code for the ordinary token pair:
```bash
curl -s -X POST "https://your-instance.plenarycms.io/api/v1/auth/sso/exchange" \
-H "Content-Type: application/json" \
-d '{"code": "plsc_…"}'
```
The response is the same `{"status": "success", "access_token": …, "refresh_token": …}` as a password sign-in. The code lasts 60 seconds, works once, and only from the IP address that received it. No two-factor code is asked for: the identity provider handles its own. `GET /api/v1/auth/sso/providers` (unauthenticated) says whether a provider is enabled and whether single sign-on is required; when it is, a password sign-in by anyone but a super user is refused with `403 sso_required`. The full flow, the settings, and every provider’s setup are on [Single sign-on](/reference/single-sign-on/).
### Passkeys
[Section titled “Passkeys”](#passkeys)
A person who has enrolled a passkey (Touch ID, Face ID, Windows Hello, a security key, or a passkey synced by a password manager) can sign in with it alone: no identifier, no password, and no one-time code, because the authenticator’s own unlock is the second factor. Passkeys are available on every plan and on Plenary Cloud, and there is no setting that turns them off. People enrol them for themselves in **Account Settings → Passkeys**; see [Users & Permissions](/guides/users-and-permissions/#passkeys).
A passkey sign-in is two calls around the browser’s WebAuthn prompt. First, fetch the challenge:
```bash
curl -s -X POST "https://your-instance.plenarycms.io/api/v1/auth/passkey/options" \
-H "Content-Type: application/json" \
-d '{}'
```
```json
{
"session_id": "4e6b3c1a-9d2f-4c7e-8a1b-2f3e4d5c6b7a",
"options": {
"challenge": "qK3…",
"timeout": 300000,
"rpId": "your-instance.plenarycms.io",
"userVerification": "required"
}
}
```
`options` is a standard `PublicKeyCredentialRequestOptions` in JSON form. Hand it to the browser, then post what comes back together with the `session_id`:
passkey-sign-in.ts
```ts
import { startAuthentication } from '@simplewebauthn/browser'
const base = 'https://your-instance.plenarycms.io/api/v1'
const { session_id, options } = await fetch(`${base}/auth/passkey/options`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: '{}',
}).then((r) => r.json())
// Opens the browser's passkey prompt. Throws if the person dismisses it.
const credential = await startAuthentication({ optionsJSON: options })
const tokens = await fetch(`${base}/auth/passkey/verify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ session_id, credential }),
}).then((r) => r.json())
// { status: "success", access_token: "…", refresh_token: "…" }
```
`POST /api/v1/auth/passkey/verify` takes `{"session_id": "…", "credential": {…}}`, where `credential` is the `PublicKeyCredential` the browser produced, serialised with `toJSON()` (which is what `startAuthentication` returns). The response is the same token pair as a password sign-in, and never a two-factor challenge.
The `session_id` is valid for 5 minutes and for one attempt: a failed `verify` spends it, so start again from `options`. Every verification failure answers `401 passkey_invalid` without saying why. When the instance requires single sign-on, a passkey sign-in by anyone but a super user is refused with `403 sso_required`, like a password sign-in.
Passkeys are bound to the instance’s public address: a passkey enrolled at `https://your-instance.plenarycms.io` works only from pages on that origin. An instance whose configuration has no `server.public_url` cannot offer them and answers `400 passkey_unsupported` on every passkey route.
### Refresh
[Section titled “Refresh”](#refresh)
`POST /api/v1/auth/refresh` exchanges a refresh token for a new pair.
```bash
curl -s -X POST "https://your-instance.plenarycms.io/api/v1/auth/refresh" \
-H "Content-Type: application/json" \
-d '{"refresh_token": "plr_rt_Z9AcC…"}'
```
```json
{
"status": "success",
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…",
"refresh_token": "plr_rt_hQ41x…"
}
```
The refresh token you sent is revoked and a new one is returned. Store the new one immediately. If a refresh token that was already used is presented again, Plenary treats it as stolen: it revokes every token descended from the same sign-in, and the user must sign in again.
If several processes share one session, let only one of them refresh, or they will race and trip this protection.
### Sign out
[Section titled “Sign out”](#sign-out)
`POST /api/v1/auth/logout` with `{"refresh_token": "…"}` revokes the refresh token. It always answers `{"status": "success"}`, even for an unknown or already revoked token. Discard the access token on the client too.
### Token lifetimes
[Section titled “Token lifetimes”](#token-lifetimes)
| Token | Default lifetime | Configuration key |
| ----------------- | ---------------- | ---------------------------- |
| Access token | 15 minutes | `auth.jwt.access_token_ttl` |
| Refresh token | 30 days | `auth.jwt.refresh_token_ttl` |
| Sign-in challenge | 10 minutes | Fixed |
| One-time code | 10 minutes | Fixed |
| Passkey challenge | 5 minutes | Fixed |
The lifetimes are set in the instance’s configuration file on self-hosted installs. See [Self-hosted install](/getting-started/self-hosted/).
An access token’s claims include `sub` (the user ID), `exp`, and an `x-plenary-claims` object with a profile snapshot for display. Do not use the claims for authorization decisions: permissions are checked on the server on every request, and a role change takes effect on the user’s next request.
### Sign-in rate limits
[Section titled “Sign-in rate limits”](#sign-in-rate-limits)
Counting happens before the password is checked, so a failed attempt costs the same as a successful one.
| Endpoint | Limit |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/auth/login` | 20 per IP per 15 minutes, and 10 per identifier per 15 minutes |
| `/auth/login/otp/send` | 3 per challenge per hour, 5 per user per 10 minutes, 5 per destination per 10 minutes; text messages also 1 per account per minute and 5 per account per hour |
| `/auth/refresh` | 60 per IP per 15 minutes |
| `/auth/passkey/options`, `/auth/passkey/verify` | 20 per IP per 15 minutes, each |
| `/auth/sso/{key}/start`, the OIDC callback, the SAML ACS | 60 per IP per 15 minutes, shared |
| `/auth/sso/exchange` | 60 per IP per 15 minutes |
An instance running with `dev_mode: true` turns these limits off, except the per-account text-message budget, which is stored with the account and also survives a restart.
## Errors
[Section titled “Errors”](#errors)
Errors use the standard envelope, `{ "error": { "code": "…" } }`.
**On any authenticated endpoint:**
| Status | Code | Cause |
| ------ | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `401` | `authentication_required` | No credential; an `X-API-KEY` value that is not a Plenary key; an API key sent as `Authorization: Bearer`; or the user’s account no longer exists or is inactive. |
| `401` | `api_key_invalid` | The API key is unknown, inactive, revoked, or expired. |
| `401` | `token_invalid` | The access token is malformed, has a bad signature, or has expired. Refresh and retry. |
| `403` | `api_key_origin_not_allowed` | The browser `Origin` is not in the key’s allowed origins. |
| `403` | `permission_denied` | Authenticated, but this credential may not do this. A public key gets this on every endpoint outside its fixed access. |
| `429` | `rate_limited` | The key’s per-minute limit is used up. |
**On the sign-in endpoints:**
| Status | Code | Endpoint | Cause |
| ------ | ------------------------------------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `400` | `invalid_request` | login, otp/verify | Missing or malformed body fields. |
| `401` | `invalid_credentials` | login | Unknown user, wrong password, or inactive account. |
| `403` | `sso_required` | login | Single sign-on is required and the identifier is not a super user’s. Sign in through the identity provider. |
| `429` | `rate_limited` | login, refresh, passkey/\* | Rate limit exceeded. |
| `400` | `otp_method_required` | otp/send | Missing `challenge_id` or `otp_method`. |
| `400` | `otp_method_invalid` | otp/send | `otp_method` is not `email` or `sms`. |
| `400` | `otp_challenge_invalid` | otp/send, otp/verify | `challenge_id` is not a valid UUID. |
| `400` | `otp_email_unavailable` | otp/send | The user has no verified email address. |
| `400` | `otp_sms_unavailable` | otp/send | The user has no verified phone number, or SMS is not configured. |
| `400` | `otp_not_sent` | otp/verify | No code has been sent for this challenge yet. |
| `401` | `otp_session_expired` | otp/send, otp/verify | Challenge not found, or the account became inactive. |
| `401` | `otp_challenge_expired` | otp/send, otp/verify | Challenge expired, already used, or cancelled. |
| `401` | `otp_challenge_locked` | otp/send, otp/verify | Too many wrong codes. Start a new login. |
| `401` | `otp_expired` | otp/verify | The code expired. Send a new one. |
| `401` | `otp_invalid` | otp/verify | Wrong code. |
| `429` | `otp_rate_limited` | otp/send | Send limit exceeded. |
| `429` | `otp_sms_cooldown` | otp/send | A text message went out less than a minute ago. `vars.retry_after` is the seconds to wait. |
| `429` | `otp_sms_throttled` | otp/send | Five text messages in the last hour. `vars.retry_after` is the seconds to wait; an administrator can reset it. |
| `500` | `otp_send_failed` | otp/send | The email or SMS could not be delivered. |
| `400` | `passkey_unsupported` | passkey/\* | The instance has no `server.public_url` to bind passkeys to. |
| `400` | `passkey_session_invalid` | passkey/verify | Missing `session_id` or `credential`, or a session that is unknown, older than 5 minutes, or already spent. Start again from `options`. |
| `401` | `passkey_invalid` | passkey/verify | The passkey could not be verified, or the account is inactive. The response does not say which. |
| `403` | `sso_required` | passkey/verify | Single sign-on is required and the account is not a super user’s. |
| `400` | `refresh_token_required` | refresh, logout | Missing `refresh_token`. |
| `401` | `refresh_token_invalid` | refresh | Unknown refresh token. |
| `401` | `session_revoked` | refresh | The token was already used or revoked. The whole session is now revoked. |
| `401` | `session_expired` | refresh | The refresh token has expired. Sign in again. |
| `401` | `sso_code_invalid` | sso/exchange | The login code is unknown, used, expired, or from another IP address. |
| `401` | `sso_user_inactive` | sso/exchange | The account was deactivated after the provider callback. |
| `403` | `license_feature_sso` | sso/\* | Single sign-on is not included in the Free plan. |
| `404` | `sso_provider_not_found`, `sso_provider_disabled` | sso/{key}/start | No such provider, or the connection is switched off. |
The SDK throws `PlenaryForbiddenError` for `403` and `PlenaryError` for `401` and `429`, each with `status` and `code`.
## Related
[Section titled “Related”](#related)
* [API keys](/guides/api-keys/): creating, restricting, and revoking keys in the console.
* [Permissions](/reference/permissions/): capabilities and grants.
* [Single sign-on](/reference/single-sign-on/): OpenID Connect and SAML sign-in.
* [Content API](/reference/content-api/): what a key can read.
* [Errors](/reference/errors/): every error code.
# CLI
> Complete reference for @plenary/cli, the `plenary` command - installation, configuration and credentials, every command and flag, output formats, and exit codes.
`@plenary/cli` installs the `plenary` command, a client for the Plenary HTTP API that runs from a terminal, a script, or a CI job. Use it to keep model YAML in step with an instance, automate content and media work, manage API keys, and call any endpoint directly. It works against any instance you hold a credential for, Plenary Cloud included.
Everything the CLI does goes through the API, so it is attributed to your credential, limited by its grants, and recorded in revision history like any other client.
## Install
[Section titled “Install”](#install)
Node.js 20 or later is required.
```bash
# In a project (recommended): pinned with your other dependencies
npm install --save-dev @plenary/cli
npx plenary --help
# Or globally
npm install -g @plenary/cli
plenary --help
```
`plenary --version` (or `-v`) prints the installed version.
Note
Plenary’s server source also has a separate Go program named `plenary` that only inspects license tokens offline (`plenary license show|verify`); see [Licensing](/reference/licensing/#verify-a-license-offline). It is unrelated to this npm package, which has no license commands.
## Configuration
[Section titled “Configuration”](#configuration)
The CLI needs a base URL (the instance origin, without `/api/v1`), usually a site key, and a credential. Settings resolve in this order, highest first:
1. A command-line flag.
2. A process environment variable.
3. A `.env` file next to `plenary.json` (or in the working directory when there is no `plenary.json`). Only `PLENARY_*` lines are read.
4. `plenary.json`, found by searching upward from the working directory.
### Global options
[Section titled “Global options”](#global-options)
These go before or after the command name and apply to every command.
| Flag | Environment variable | `plenary.json` key | Meaning |
| ------------------ | ---------------------- | ------------------ | ------------------------------------------------------------------------------------------ |
| `--base-url ` | `PLENARY_BASE_URL` | `baseUrl` | Instance URL, such as `https://your-instance.plenarycms.io`. A trailing `/` is removed. |
| `--api-key ` | `PLENARY_CLI_API_KEY` | none | API key to authenticate content commands with. |
| `--site ` | `PLENARY_SITE_KEY` | `siteKey` | Site key for entry and form-entry commands. |
| `--locale ` | `PLENARY_LOCALE` | `locale` | Locale for entry reads and writes. Defaults to the site’s default locale. |
| none | `PLENARY_METADATA_DIR` | `metadataDir` | Metadata directory for `metadata` commands. Default `plenary`, relative to `plenary.json`. |
| `--config ` | none | none | Use this `plenary.json` instead of searching for one. Exits 2 if the file is missing. |
| `--json` | none | none | Print machine-readable JSON instead of tables. |
| `--debug` | none | none | Print each request (`> GET …`, `< 200`) and full stack traces to stderr. |
| `-h`, `--help` | none | none | Help for any command or subcommand. |
`plenary login` also reads `PLENARY_USERNAME` and `PLENARY_PASSWORD`, and the session store honors `XDG_CONFIG_HOME`.
### plenary.json
[Section titled “plenary.json”](#plenaryjson)
plenary.json
```json
{
"baseUrl": "https://your-instance.plenarycms.io",
"siteKey": "marketing",
"locale": "en-us",
"metadataDir": "plenary"
}
```
Every key is optional and every value is a string. Any other key, including anything that looks like a credential, is rejected with exit code 2, so the file is safe to commit. `plenary init` writes it.
There are no named profiles. To work with several instances, keep a `plenary.json` per project, pass `--config`, or set `PLENARY_BASE_URL` and `PLENARY_CLI_API_KEY` per environment (for example, per CI job).
## Credentials
[Section titled “Credentials”](#credentials)
The CLI uses two kinds of credential for different work.
**An API key** (`PLENARY_CLI_API_KEY` or `--api-key`), sent as `X-API-KEY`. It can do exactly what its grants allow. API keys hold only `content:*` capabilities, so a key can sync models and forms and manage entries and media, but cannot reach roles, API keys, or site management. Use a private key for CI and scripts. See [API Keys](/guides/api-keys/).
The CLI does not read `PLENARY_API_KEY`, the variable your site uses for its public key. The CLI reads the same `.env` that frameworks such as Next.js load, so keeping the names apart stops the CLI’s private key from reaching your site’s runtime.
**A user session** from `plenary login`. It carries your role, so it reaches `admin:*` routes. Only the refresh token is stored, in `$XDG_CONFIG_HOME/plenary/credentials.json` (`~/.config/plenary/credentials.json` by default), readable only by you and keyed by instance URL. Each run exchanges it for a fresh access token and writes the rotated refresh token back. A session the server refuses is deleted, with a message to log in again.
Which credential a command uses:
| Commands | Credential |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `roles`, `api-keys` | The user session, even when an API key is configured. These fail with exit code 2 if you are not logged in. |
| `metadata`, `models`, `forms`, `entries`, `media`, `sites` | The API key if one is configured, otherwise the user session. |
| `api` | The API key if one is configured, otherwise the user session, otherwise no credential. |
| `status` | The health check needs none; the credential line uses whichever is configured. |
Because `metadata` prefers the key, a run with `PLENARY_CLI_API_KEY` set syncs models and forms only. To pull or push roles and sites, unset the key and use a session from `plenary login`. Roles need a super user.
A configured key always wins for content work, so a person’s login never silently becomes the actor of a deploy job that also has a key. `plenary whoami` shows which credential each kind of command will use.
## Output and exit codes
[Section titled “Output and exit codes”](#output-and-exit-codes)
* Tables and reports go to stdout. With `--json`, the API’s JSON response goes to stdout, pretty-printed. `export` commands write NDJSON, one object per line.
* Errors go to stderr as `plenary: (HTTP )`, followed by the error’s `vars`, one per line:
```text
plenary: api_key_grant_not_allowed (HTTP 422)
capabilities: ["admin:api_keys:read"]
```
* Commands that delete something ask for confirmation on a terminal. Without a terminal they need `-y`.
| Exit code | Meaning |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `0` | Success. |
| `1` | The API refused the request (any non-2xx response), the instance was unreachable, a file could not be read, or a batch had failures. |
| `2` | Usage error: unknown command or flag, malformed flag value, missing base URL, missing credential or site key, a confirmation the run could not ask for, or a 2FA login without a terminal. |
## plenary init
[Section titled “plenary init”](#plenary-init)
Writes `plenary.json` in the working directory. Values come from `--base-url`, `--site`, and `--locale` (or their environment variables); on a terminal, anything missing is prompted for.
| Flag | Meaning |
| --------------- | ------------------------------------------------------------------- |
| `--dir ` | Metadata directory, relative to the config file. Default `plenary`. |
| `-f`, `--force` | Overwrite an existing `plenary.json`. |
```bash
npx plenary init --base-url https://your-instance.plenarycms.io --site marketing --locale en-us
```
## plenary login
[Section titled “plenary login”](#plenary-login)
Signs in as a user and stores the session for this instance.
| Flag | Meaning |
| ---------------------------------------- | ---------------------------------------------------------------------- |
| `-u`, `--identifier ` | Who to sign in as. Defaults to `PLENARY_USERNAME`, then a prompt. |
| `--otp-method ` | How to receive a two-factor code when more than one method is offered. |
The password is never a flag. It is prompted for without echo, or read from `PLENARY_PASSWORD` when there is no terminal. With two-factor sign-in on the account, the CLI prompts for the code, which needs a terminal.
```bash
npx plenary login -u jane@example.com
# logged in to https://your-instance.plenarycms.io as jane@example.com (Admin)
```
The login endpoint is rate-limited per IP address. Log in once and let the stored session refresh itself.
## plenary logout
[Section titled “plenary logout”](#plenary-logout)
Revokes the stored session on the server and deletes it locally. The local copy is deleted even if the server call fails. Takes no options.
## plenary whoami
[Section titled “plenary whoami”](#plenary-whoami)
Shows the credentials this run would use and which commands each serves. Takes no options.
```text
API key private "Deploy job" (4 grants), used for content commands
Session jane@example.com (Admin), used for admin commands
```
## plenary status
[Section titled “plenary status”](#plenary-status)
Calls `GET /api/v1/health` and, when a credential is configured, `GET /api/v1/auth/me`. Takes no options.
```text
Instance https://your-instance.plenarycms.io
Version 1.0.0 (on-prem)
Status ok, database ok, license ok
Credential private API key "Deploy job" (4 grants)
Config /srv/site/plenary.json
```
Exits 1 when the instance is unreachable or the credential is refused, so it is a good first step in a CI job.
## plenary metadata
[Section titled “plenary metadata”](#plenary-metadata)
Keeps a directory of YAML files in step with the instance: `models/`, `forms/`, `roles/`, and `sites/` under the metadata directory, one `.yaml` per entity. See [Models as Code](/guides/models-as-code/) for the workflow and [Model YAML](/reference/model-yaml/) for the file format.
**One site’s tree.** With a site configured (`--site`, `PLENARY_SITE_KEY`, or `siteKey` in `plenary.json`, which `plenary init` writes), `pull`, `diff`, and `push` move that site’s tree only: the models, forms, and object models it owns, its roles, and its own `sites/.yaml`. Files in a site’s tree carry no `site_key`. A push may not reach outside the site: a model or role assigned to another site, or another site’s file, fails with `422 metadata_invalid`, and `--prune` deletes only within the site.
**The whole instance.** `--all-sites` moves every site’s models, forms, and site files, and each model file carries its `site_key`. It holds no roles, because every role belongs to a site, so `--only roles` with `--all-sites` is refused. While two sites use the same model key, the instance-wide tree cannot tell those models apart: export fails with `422 model_site_key_required`, naming the keys in `vars.models`, and you work one site at a time instead.
### plenary metadata pull
[Section titled “plenary metadata pull”](#plenary-metadata-pull)
Writes every model, form, role, and site the credential may read into the directory. Kinds the credential may not read are named on stderr. Files on disk that the server did not send are listed and left alone.
| Flag | Meaning |
| ---------------- | ---------------------------------------------------------------------- |
| `--dir ` | Metadata directory for this run. |
| `--only ` | Comma list of `models`, `forms`, `roles`, `sites`, or `all` (default). |
| `--all-sites` | Pull the whole instance instead of the configured site. |
```text
wrote 28 files to /srv/site/plenary
```
### plenary metadata diff
[Section titled “plenary metadata diff”](#plenary-metadata-diff)
Validates the whole directory and prints what `push` would do, without writing anything.
| Flag | Meaning |
| ---------------- | ---------------------------------------------------------- |
| `--dir ` | Metadata directory for this run. |
| `--only ` | Limit to some kinds. |
| `--all-sites` | Work on the whole instance instead of the configured site. |
| `--prune` | Include what `push --prune` would delete. |
| `--verbose` | List unchanged entities too. |
```text
delete form old_survey
create collection event
update collection post (+subtitle ~title settings)
skipped role marketing/admin (system-owned)
Plan: 1 to create, 1 to update, 1 to delete, 1 skipped, 25 unchanged.
```
In each detail, `+` is a field added, `~` a field changed, `-` a field removed, `settings` a model attribute changed, and `transformers` a script changed. With nothing to do it prints `No changes: 28 unchanged.`
### plenary metadata push
[Section titled “plenary metadata push”](#plenary-metadata-push)
Applies the directory: creates and updates entities to match it, and deletes only with `--prune`.
| Flag | Meaning |
| ---------------- | ---------------------------------------------------------------------------------------------- |
| `--dir ` | Metadata directory for this run. |
| `--only ` | Limit to some kinds. |
| `--all-sites` | Work on the whole instance instead of the configured site. |
| `--prune` | Also delete entities missing from the directory, only within the kinds the directory contains. |
| `-y`, `--yes` | Do not ask before pruning. Required for `--prune` without a terminal. |
| `--dry-run` | Same as `diff`. |
| `--verbose` | List unchanged entities too. |
```text
create collection event
Applied: 1 to create, 0 to update, 0 unchanged.
```
A site’s Admin role is never changed or deleted and is reported as `skipped`; roles are named `/` in the plan. A tree with no `roles/` directory cannot delete a role. If the credential may not make any one change, the whole push is refused with `403 permission_denied` naming the entities, and nothing is written. An invalid file fails with `422 metadata_invalid` and its path.
Models and forms work with an API key or a session. Roles and sites need a session from `plenary login`, with no API key configured for the run.
## plenary models
[Section titled “plenary models”](#plenary-models)
| Command | Does |
| --------------------------------- | ----------------------------------------------------------------------------------- |
| `plenary models list` | Table of every model: key, kind, name, field count, and `inactive` when applicable. |
| `plenary models get ` | One model by key or id, with its fields. |
| `plenary models get --yaml` | The model as the YAML file the `metadata` commands use. |
```text
KEY KIND NAME FIELDS
blog_post collection Blog Post 4
obj_address object Address 5
```
## plenary forms
[Section titled “plenary forms”](#plenary-forms)
| Command | Does |
| ------------------------------------- | ----------------------------------------------------- |
| `plenary forms list` | Table of every form. |
| `plenary forms get ` | One form by key or id. `--yaml` prints its YAML file. |
| `plenary forms entries list