Skip to content

@plenary/client

@plenary/client is the framework-free Plenary API client. It reads content, reads and submits forms, looks up media, and verifies incoming webhooks. It has no framework dependency and uses the global fetch, so it runs in Node, browsers, and edge runtimes. Every method maps to one HTTP request; there is no hidden caching or batching.

Terminal window
npm install @plenary/client

This page documents version 1.0.x. Everything listed is exported from the package root.

function createClient(config: ClientConfig): PlenaryClient;
lib/plenary.ts
import { createClient } from "@plenary/client";
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",
});
Option Type Required Description
baseUrl string Yes Instance origin, for example https://your-instance.plenarycms.io. Do not include /api/v1. A trailing slash is fine.
apiKey string Yes API key, sent as the X-API-KEY header on every request. Use a public key (pln_pub_…) unless you need drafts, private fields, or private models.
siteKey string Yes Site to read from, sent as site_key on every request.
locale string Yes Default locale, sent as locale on every content read.
fetch typeof fetch No fetch implementation to use. Defaults to globalThis.fetch. Pass one to add caching options, logging, or retries, or use createTaggedFetch from @plenary/next.

The client object is stateless, so create it once and share it.

Method HTTP request
listEntries(modelKey, opts?) GET /api/v1/content/{modelKey}
getEntry(modelKey, slugOrId, opts?) GET /api/v1/content/{modelKey}/{slugOrId}
getSingleton(modelKey, opts?) GET /api/v1/content/{modelKey}
getForm(formKey) GET /api/v1/forms/{formKey}
submitForm(formKey, data, opts?) POST /api/v1/forms/{formKey}/entries?site_key=…
getMedia(mediaId) GET /api/v1/media/{mediaId}
graphql(query, variables?, opts?) POST /api/v1/graphql?site_key=…

Every method returns a promise that rejects with a PlenaryError for any non-2xx response.

listEntries<TData = Record<string, unknown>>(
modelKey: string,
opts?: ListOptions,
): Promise<ListResult<TData>>;

Lists entries of a collection model. Returns { items, total? }; total is set only when opts.count is true (read from the X-Total-Count header).

interface PostData {
title: string;
excerpt?: string;
published_date: string;
}
const { items, total } = await plenary.listEntries<PostData>("post", {
where: { "data.published_date": { $gte: "2026-01-01" } },
sort: { "data.published_date": "desc" },
exclude: ["data.body"],
limit: 10,
offset: 0,
count: true,
});
for (const post of items) {
console.log(post.slug, post.data.title);
}

Throws PlenaryNotFoundError when the model does not exist (or is private, for a public key). An empty result is { items: [] }, not an error.

Calling listEntries on a singleton model returns the singleton entry object as items rather than an array. Use getSingleton for singletons.

getEntry<TData = Record<string, unknown>>(
modelKey: string,
slugOrId: string,
opts?: ReadOptions,
): Promise<Entry<TData>>;

Fetches one entry by slug or by UUID. A slug is matched in the client’s locale (or opts.locale); a UUID ignores locale.

import { PlenaryNotFoundError } from "@plenary/client";
import { plenary } from "./plenary";
export async function findPost(slug: string) {
try {
return await plenary.getEntry<{ title: string; body?: string }>("post", slug);
} catch (err) {
if (err instanceof PlenaryNotFoundError) return null;
throw err;
}
}

Throws PlenaryNotFoundError with code entry_not_found when nothing matches, and with model_not_found when the model does not exist.

getSingleton<TData = Record<string, unknown>>(
modelKey: string,
opts?: ReadOptions,
): Promise<Entry<TData>>;

Fetches the one entry of a singleton model for the client’s site and locale.

const settings = await plenary.getSingleton<{ announcement?: string }>("site_settings");
console.log(settings.data.announcement);

Throws PlenaryNotFoundError (entry_not_found) when the singleton has no entry in this site and locale. Calling it on a collection model returns an array at runtime, so do not.

getForm(formKey: string): Promise<PublicFormDefinition>;

Fetches a form’s render-safe definition: its fields, in order, with no IDs, private fields, or hidden fields. A public key may call it. The response includes a ts anti-spam token to send back with the submission.

const form = await plenary.getForm("contact");
// { key: "contact", name: "Contact", fields: [{ key: "email", name: "Email", type: "email", required: true }, …], ts: "MTc5…" }

Throws PlenaryNotFoundError (form_not_found) for an unknown or inactive form. See Forms and the Forms API.

submitForm(
formKey: string,
data: Record<string, unknown>,
opts?: FormSubmitOptions,
): Promise<FormSubmitResult>;

Submits a form entry. The request body is { data, website?, ts? }, and site_key comes from opts.siteKey or the client’s site. A public key may call it. Resolves to { ok: true, id } on success.

const form = await plenary.getForm("contact");
const result = await plenary.submitForm(
"contact",
{ email: "jane@example.com", message: "Hello" },
{ ts: form.ts, website: "" },
);
Option Type Description
siteKey string Override the client’s site for this call.
website string The honeypot value. Render a hidden website input and send its value verbatim, normally "". A non-empty value marks the entry as spam.
ts string The ts token from getForm, sent back unchanged.

Validation failures throw PlenaryValidationError (status 422) with the field named in vars. See Contact form for a complete build, and the Forms API for every error code.

getMedia(mediaId: string): Promise<MediaDetail>;

Fetches a media asset’s details: type, dimensions, original URL, thumbnail, and generated variants. A public key can read public assets; a private asset returns 404 to a public key. URLs in the response are paths on your instance, such as /media/{id}/original.jpg; prefix them with your base URL.

const media = await plenary.getMedia("ce221afb-0ef2-4fc6-94d6-8c3da0cc391e");
const src = new URL(media.original_url, process.env.PLENARY_BASE_URL).toString();

You do not need getMedia to render an image field: an image value from the Content API already includes its variant URLs (see Images). @plenary/react calls getMedia for you when it renders Page Builder images.

graphql<TData = Record<string, unknown>>(
query: string,
variables?: Record<string, unknown>,
opts?: { operationName?: string; tags?: string[] },
): Promise<TData>;

Runs one operation against the GraphQL API and resolves with the response’s data. The site goes on the URL as for every read. In GraphQL the locale is a field argument rather than a URL parameter, so when the document declares a $locale variable that variables leaves unset, the client’s locale fills it; a document without one reads the site’s default locale. operationName picks one of several operations in the document. tags is sent as next.tags on the fetch call for Next.js caching; see createTaggedFetch.

const query = `
query Posts($locale: String, $limit: Int) {
post(locale: $locale, limit: $limit, sort: [PUBLISHED_AT_DESC]) {
items { slug title data { summary } }
total
}
}
`;
const { post } = await plenary.graphql<{ post: { items: Post[]; total: number } }>(query, { limit: 3 });

Any errors in the response reject with a PlenaryGraphQLError, at 200 when one root field failed beside others that resolved (its data holds the rest), or at 400 when the document was refused before it ran. Type TData by hand or generate it: plenary graphql schema > schema.graphql saves the SDL and a generator such as GraphQL Code Generator turns your documents into the operation types.

Accepted by every content read (getEntry, getSingleton, listEntries).

Option Type Query parameter Description
locale string locale Override the client’s locale for this call.
siteKey string site_key Override the client’s site for this call.
include string[] include Return only these properties, for example ["slug", "data.title"].
exclude string[] exclude Leave these properties out, for example ["data.body"].
hydrate Hydrate hydrate:<field> Expand reference fields: { "data.author": "*" } or { "data.author": ["title", "data.name"] }.

Passing both include and exclude throws an Error before any request is sent.

ListOptions extends ReadOptions with:

Option Type Query parameter Description
where Where where:<field>.<op> Flat AND filter. See where.
filters FilterTree filters JSON filter tree with $and and $or.
sort Sort sort:<field> { "data.published_date": "desc" }. Keys apply in insertion order.
limit number limit Page size. Server default 100, maximum 500.
offset number offset Matches to skip.
count boolean count=true Return the total match count as total.

Passing both where and filters throws an Error before any request is sent. The full semantics of every parameter, including which operators each field type accepts, are in the Content API reference.

where maps a field path to a bare value (meaning $eq) or a condition object. Model fields are prefixed data.; intrinsic properties such as slug, status, and path are not.

await plenary.listEntries("post", {
where: {
status: "published", // where:status=published
"data.category": { $in: ["news", "press"] }, // where:data.category.$in=news,press
"data.title": { $ilike: "launch" }, // where:data.title.$ilike=launch
"data.cover": { $is_null: false }, // where:data.cover.$is_null=false
},
});
Condition key Value type Sent as
$eq, $ne, $lt, $lte, $gt, $gte Any scalar String(value)
$in, $nin Array Comma-joined
$like, $ilike string As given (% and _ are wildcards)
$is_null boolean true or false

A condition object is recognized only when every key is one of the operators above. Anything else is sent as a bare value, which matches nothing useful.

await plenary.listEntries("post", {
filters: {
where: {
$or: [
{ "data.category": { $eq: "news" } },
{ $and: [{ "data.featured": { $eq: true } }, { path: { $under: "/blog" } }] },
],
},
},
});

The tree is sent as JSON in the filters parameter. In the tree, $in and $nin take arrays and $under works.

An image field’s value has this shape. The client does not transform it.

{
"media_id": "ce221afb-0ef2-4fc6-94d6-8c3da0cc391e",
"alt": "A blue gradient",
"caption": "Optional caption",
"focal_point": { "x": 0.5, "y": 0.5 },
"variants": {
"card": { "url": "/media/ce221afb-0ef2-4fc6-94d6-8c3da0cc391e/8f3a10a3c8b42f06.webp" }
}
}

variants has one item per variant declared on the field in the model. URLs are instance paths; make them absolute with your base URL:

function mediaUrl(path: string | undefined): string | undefined {
return path ? new URL(path, process.env.PLENARY_BASE_URL).toString() : undefined;
}
const src = mediaUrl(entry.data.cover?.variants?.card?.url);

If the media asset was deleted, the value has "missing": true and no variants.

function buildReadParams(base: QueryBase, opts?: ReadOptions): URLSearchParams;
function buildListParams(base: QueryBase, opts?: ListOptions): URLSearchParams;
interface QueryBase {
siteKey: string;
locale: string;
}

These are the functions the client uses to turn options into a query string. Use them when you need the exact URL, for example to call the API with your own HTTP code or to log requests.

import { buildListParams } from "@plenary/client";
const params = buildListParams(
{ siteKey: "default", locale: "en-us" },
{ where: { slug: { $in: ["a", "b"] } }, sort: { created_at: "desc" } },
);
console.log(params.toString());
// site_key=default&locale=en-us&where%3Aslug.%24in=a%2Cb&sort%3Acreated_at=desc

Every non-2xx response rejects with a subclass of PlenaryError, built from the server’s { "error": { "code", "vars" } } body.

Class Thrown for Typical codes
PlenaryNotFoundError 404 entry_not_found, model_not_found, form_not_found
PlenaryForbiddenError 403 permission_denied, api_key_origin_not_allowed
PlenaryValidationError 400, 422 entry_query_limit_exceeded, entry_locale_invalid, form field errors
PlenaryGraphQLError A GraphQL response with errors, at 200 or 400 graphql_query_invalid, permission_denied, entry_query_limit_exceeded
PlenaryError Any other status (401, 429, 5xx) api_key_invalid, authentication_required, rate_limited
class PlenaryError extends Error {
readonly status: number;
readonly code: string; // server error code, or `http_<status>` when the body had none
readonly vars?: Record<string, unknown>;
}

All subclasses extend PlenaryError, so instanceof PlenaryError catches every API failure. Network failures (DNS, connection refused) reject with the underlying fetch error, not a PlenaryError.

PlenaryGraphQLError adds errors, the response’s whole errors array (each with message, path, locations and extensions), and data, the partial data of a 200. Its code and vars are the first error’s extensions.code and the other extensions keys.

import { PlenaryError, PlenaryNotFoundError, PlenaryValidationError } from "@plenary/client";
import { plenary } from "./plenary";
try {
await plenary.listEntries("post", { limit: 1000 });
} catch (err) {
if (err instanceof PlenaryValidationError) {
console.error(err.code, err.vars); // entry_query_limit_exceeded { limit: 1000, max: 500 }
} else if (err instanceof PlenaryNotFoundError) {
console.error("No such model");
} else if (err instanceof PlenaryError) {
console.error(err.status, err.code);
} else {
throw err;
}
}

errorFromResponse(status: number, body: unknown): PlenaryError builds the right subclass from a status and parsed body. Use it if you make your own requests and want the same error types.

See Errors for every code.

These helpers verify and type the requests Plenary sends to your webhooks. They work with any framework that gives you a Fetch API Request. For Next.js, @plenary/next wraps them in ready-made route handlers; for Nuxt, @plenary/nuxt does the same.

Plenary does not sign webhook requests. You authenticate them with a shared secret that you configure on the webhook as a custom header (or query parameter) marked Secret. The helpers read it from the x-plenary-secret header by default, falling back to a secret query parameter.

function parseWebhookRequest(request: Request, options: ParseWebhookOptions): Promise<WebhookPayload>;
interface ParseWebhookOptions {
secret: string; // the value configured on the webhook
secretHeader?: string; // default "x-plenary-secret"
secretQuery?: string; // default "secret", checked when the header is absent
}

Checks the method, the secret, and the body shape, then returns the typed payload. On failure it throws PlenaryWebhookError with the status your endpoint should answer:

status message When
405 Method not allowed Not a POST.
500 Webhook secret is not configured options.secret is empty or unset, for example a missing environment variable. Nothing is accepted until it is set.
401 Invalid webhook secret Secret missing or wrong.
400 Body is not valid JSON Unparseable body.
400 Not a Plenary webhook payload JSON without event, delivery_id, and entry or form_entry.

A 4xx answer makes Plenary mark the delivery failed immediately instead of retrying it for hours.

webhook-handler.ts
import {
parseWebhookRequest,
PlenaryWebhookError,
isEntryWebhookPayload,
} from "@plenary/client";
export async function handleWebhook(request: Request): Promise<Response> {
const secret = process.env.PLENARY_WEBHOOK_SECRET;
if (!secret) return new Response("PLENARY_WEBHOOK_SECRET is not set", { status: 503 });
let payload;
try {
payload = await parseWebhookRequest(request, { secret });
} catch (err) {
if (err instanceof PlenaryWebhookError) {
return new Response(err.message, { status: err.status });
}
throw err;
}
if (isEntryWebhookPayload(payload)) {
console.log(payload.event, payload.model.key, payload.entry.slug);
} else {
console.log(payload.event, payload.form.key, payload.form_entry.id);
}
return new Response(null, { status: 204 });
}

Always check that the secret is set before calling it. With an empty secret, a request carrying ?secret= would pass.

Export Signature Description
verifyWebhookSecret (provided: string | null | undefined, secret: string) => boolean Constant-time comparison. Use it when you extract the secret yourself. Always false when secret is empty.
parseWebhookPayload (body: unknown) => WebhookPayload Shape-checks an already parsed body. Throws PlenaryWebhookError (400).
isEntryWebhookPayload (p: WebhookPayload) => p is EntryWebhookPayload True for entry.* payloads.
isFormWebhookPayload (p: WebhookPayload) => p is FormWebhookPayload True for form.submitted payloads.
ENTRY_WEBHOOK_EVENTS readonly EntryWebhookEvent[] ["entry.created", "entry.updated", "entry.published", "entry.unpublished", "entry.deleted"]
WEBHOOK_TEST_EVENT "webhook.test" An event name the helpers treat as a test delivery.
PlenaryWebhookError class extends Error { status: number } Thrown by the parsers.
entryUrl (payload: EntryWebhookPayload) => string | null The entry’s default site URL: folder path joined with slug (/blog + spring-sale → /blog/spring-sale); a root-folder entry slugged home is /; null for a slugless entry.
planRevalidation (payload: WebhookPayload, options: RevalidateOptions) => RevalidationPlan Which paths one payload revalidates: { relevant, test, paths }. options takes paths (per model key: a path, a list, or a function of the payload), entryUrl, and events, as documented for @plenary/next and @plenary/nuxt, which both build on it.
type EntryWebhookEvent =
| "entry.created"
| "entry.updated"
| "entry.published"
| "entry.unpublished"
| "entry.deleted";
interface EntryWebhookPayload<TData = Record<string, unknown>> {
event: EntryWebhookEvent | "webhook.test";
delivery_id: string; // stable across retries; deduplicate on it
occurred_at: string;
webhook: { id: string; name?: string };
model: { id: string; key?: string };
entry: WebhookEntryRef;
actor: WebhookActor;
changed: string[]; // e.g. ["data.title", "status"]; empty for created and deleted
revision_id?: string;
data?: TData; // absent when the webhook sends no field data
}
interface WebhookEntryRef {
id: string;
site_key?: string;
locale?: string;
slug?: string;
path?: string; // folder path, without the slug
status?: string;
created_at?: string;
updated_at?: string;
published_at?: string;
}
interface WebhookActor {
type: "user" | "api_key" | "system";
id?: string;
label: string;
}
interface FormWebhookPayload<TData = Record<string, unknown>> {
event: "form.submitted" | "webhook.test";
delivery_id: string;
occurred_at: string;
webhook: { id: string; name?: string };
form: { id: string; key?: string };
form_entry: WebhookFormEntryRef;
data?: TData;
}
interface WebhookFormEntryRef {
id: string;
site_key?: string;
status?: string;
created_at?: string;
source?: { ip?: string; user_agent?: string; referer?: string };
}
type WebhookPayload = EntryWebhookPayload | FormWebhookPayload;

See Webhook events for when each event fires and the request headers Plenary sends.

interface Entry<TData = Record<string, unknown>> {
id: string;
site_key: string;
model_key: string;
slug: string | null;
locale: string | null;
title: string | null;
status: string;
published_at: string | null;
publish_at: string | null;
unpublish_at: string | null;
created_at: string;
updated_at: string;
folder_id: string | null;
path: string;
data: TData;
draft?: EntryDraft | null;
}
interface EntryDraft<TData = Record<string, unknown>> {
data: TData;
slug: string | null;
updated_at: string;
}

draft is a published entry’s pending changes, read through a private key; data and slug are the live copy. A public key never sets it, and a public key with Include draft content reads the pending content in data and slug instead.

Pass your own TData to type data. The SDK does not generate types from your models; write an interface per model that mirrors its fields, and mark optional fields optional. With include, properties you did not select are absent at runtime even though the type says otherwise.

interface WhereCondition {
$eq?: unknown;
$ne?: unknown;
$lt?: unknown;
$lte?: unknown;
$gt?: unknown;
$gte?: unknown;
$in?: unknown[];
$nin?: unknown[];
$like?: string;
$ilike?: string;
$is_null?: boolean;
}
type Where = Record<string, unknown | WhereCondition>;
interface FilterTree { where: Record<string, unknown> }
type SortDirection = "asc" | "desc";
type Sort = Record<string, SortDirection>;
type Hydrate = Record<string, "*" | string[]>;
interface ListResult<TData = Record<string, unknown>> {
items: Entry<TData>[];
total?: number;
}
type PublicFormFieldType =
| "text" | "number" | "boolean" | "date" | "time" | "datetime"
| "email" | "url" | "phone" | "select" | "multi_select" | "tags"
| "object" | "list" | "json";
interface PublicFormField {
key: string;
name: string;
type: PublicFormFieldType;
required: boolean;
settings?: Record<string, unknown>; // omitted when empty; select options live here
ui?: Record<string, unknown>;
validation?: Record<string, unknown>;
}
interface PublicFormDefinition {
key: string;
name: string;
description?: string;
fields: PublicFormField[];
ts?: string; // send back on submit
}
interface FormSubmitOptions {
siteKey?: string;
website?: string;
ts?: string;
}
interface FormSubmitResult {
ok: boolean;
id?: string;
}
interface MediaVariant {
status: string; // "ready" once the file exists
url?: string; // empty until ready
}
interface MediaDetail {
media_id: string;
media_type: string; // "image", "video", …
mime_type: string;
file_name: string;
label: string;
description: string;
original_url: string;
thumb_status?: string;
thumb_url?: string;
width?: number;
height?: number;
aspect_ratio?: number;
variants?: Record<string, MediaVariant>;
}

The live response also includes caption, file_size, visibility, folder_id, path, and created_at, which the type does not declare yet.