API

Local API

Every method of the cms instance on the server, its options and what it returns.

The local API is the cms that tenon.config.ts exports, and the cms that hooks, tasks and plugin routes get. It runs on the server only. For the same methods over HTTP, see the client.

import cms from "../tenon.config";

const posts = await cms.find("posts", { where: { category: "news" }, limit: 5 });

Which cms you get

WhereAccess rulesUserReads
The imported instanceSkippedNonePublished
cms.withDrafts()Like its parentLike its parentDrafts
await cms.withSession(request)AppliedThe request's user or API keyDrafts in preview, else published
A hookSkippedThe operation's userLike the operation
A task, seed, onInit, afterErrorSkippedNonePublished
A plugin's routesAppliedThe session userDrafts in preview, else published
A plugin's publicRoutes, sitemap.entries, robots.rulesAppliedNonePublished
An admin page's load, an action's runAppliedThe signed-in userThe user's view
  • A hook's cms shares the transaction, the locale and the context of its operation. See Hooks.
  • Only the imported instance and its withDrafts() and withSession() copies have users, withSession(), jobs.run(), sitemap(), fetch() and the instance properties.

Reads

MethodReturns
find(collection, options?)The matching documents, newest first
findOne(collection, options)The first match, or undefined
findById(collection, id, options?)The document, or undefined. Also undefined outside the read rule
getGlobal(name, options?)The global. Never undefined: fields that were never saved are missing
alternatesAt(url, options?)The URL of the same page in every language, or null

alternatesAt() matches url against the permalink of every localized collection. It returns { en: "/about", de: "/de/ueber-uns", "x-default": "/about" }, or null without localization or without a match. See Localization.

Read options

Only find() and findOne(). A document matches when every key is equal. null matches an empty or missing field. undefined adds no filter. Groups, arrays, blocks, rich text, links and fields with many cannot be filtered.Only find() and findOne(). MUST be a positive whole number.false returns relations as ids. An object resolves only the paths it names. Default: every relation, populate.depth hops deep. See Relations.How many hops populate resolves. Default: populate.depth, 2. The local API has no limit.The fields to return, like { title: true, seo: { title: true } }. id always comes back. createdAt, updatedAt, createdBy, updatedBy, publishedAt, hasDraft, permalink and alternates come back only when listed. Hooks still see the whole document.The language to read. Default: the default locale.Read a missing value in the default locale. Default: localization.fallback.Adds permalink, the public URL in the read's locale, or null. Collections only.Adds alternates, the URL of the document in every language. Localized collections with a permalink only.

There is no sort, offset or pagination yet. find() always returns the newest documents first.

Writes

MethodReturns
create(collection, data, options?)The stored document. Relations are ids
update(collection, id, data, options?)The document, or undefined when it does not exist
delete(collection, id, options?)Nothing. A missing document is no error
publish(collection, id, options?)The document, or undefined
unpublish(collection, id, options?)The document, or undefined
discard(collection, id, options?)The published document, or undefined when it was never published and is now deleted
duplicate(collection, id)The copy, as a draft, or undefined

See Writing and drafts.

Write options

create() and update(): save a draft and keep the published data. Throws with drafts: false.The language to write. Default: the default locale.update(), publish() and unpublish(): the updatedAt you read. When the document changed since, the write throws a ConflictError with the code CHANGED.delete() and discard(): delete even when links in other documents point to this one. Without it, the delete throws a LinkedContentError.discard(): drop the drafts of every language at once. locale is ignored then.

Globals

MethodReturns
setGlobal(name, data, options?)The global
publishGlobal(name, options?)The global
unpublishGlobal(name, options?)The global
discardGlobal(name, options?)The published global

They take the same draft, locale, updatedAt and all options as the collection methods.

Languages

MethodWhat it does
copyLocale(collection, id, { from, to })Copies one language into another. It replaces the draft of to
removeLocale(collection, id, locale)Deletes one language. The default locale and the last language stay
copyGlobalLocale(name, { from, to })The same for a global
removeGlobalLocale(name, locale)The same for a global
setSyncStructure(collection, id, sync, options?)Keeps the lists of a document the same in every language, or stops it. sync is true, false or "default"
setGlobalSyncStructure(name, sync, options?)The same for a global
applySyncStructure(collection, options?)Applies the structure of the default locale to every document

{ dryRun: true } makes the sync methods count the items they would add and remove, without a write. See Localization.

Scheduling

MethodReturns
schedule(collection, id, options){ id } of the job, or undefined when the document does not exist
scheduleGlobal(name, options){ id } of the job

options is { action: "publish" | "unpublish", at, locale? }. at takes a Date, a number or an ISO string. See Scheduled publishing.

Media

cms.media exists only while the media library is on. Read files with cms.find("media").

MethodReturns
upload(data, { filename, mimeType, folder?, size? })The new file. A taken name gets a number, like hero-1.jpg. A stream needs size
update(id, { alt?, filename?, folder? })The file, or undefined
renameFolder(from, to){ moved, failed }. Run it again to move the files that failed
delete(id, options?)Nothing. The file leaves the storage after the commit
regenerate(id?, { force? }){ rendered, removed }. Without id, every file
setThumbnail(id, data)The file. A WebP or JPEG of at most 200 KB, without media.images

Jobs

MethodReturns
jobs.queue(task, payload?, options?){ id } of the job
jobs.run(){ ran, next }. One tick of the clock

queue() takes runAt, maxAttempts, key and merge. See Queue jobs and The clock.

Email

email.send({ to, subject, text?, html?, replyTo? }) sends at once and resolves when the server accepts the message. Without email, it throws. See Email.

Users

cms.users is for server code and the CLI. On a withSession() copy, every method throws 403.

MethodWhat it does
hasUsers()true once a user exists
list()Every user, oldest first
roles()Every role, with its label
create({ email, name, role?, password? })Creates a user. The first one becomes an admin
invite({ email, role, url? })Creates an invite and emails it when email is set. Returns { invite, link, sent }
signInLink(email, { origin })A sign-in link that works once, for an hour. Returns { link, sent }
deactivate(email), reactivate(email)Ends the user's sessions and blocks sign-in, or lets them sign in again. The last admin stays
remove(email)Deletes a user. Their content keeps the id. This cannot be undone

See tenon users.

Export and import

MethodReturns
export(options?)A ZIP as a ReadableStream. { media, scope }: default { media: true, scope: "content" }
exportSummary(options?)The number of rows and files an export would hold
import(archive, options?)The counts of what it wrote. { mode, dryRun }: mode is "replace", "merge" (default) or "missing"

An import runs no hooks, no validation and no webhooks. afterImport runs after it. See Backup and restore.

Scopes

MethodReturns
withDrafts()A copy that reads drafts. Writes do not change
withSession(request)A copy for the user or API key of the request, with their access rules

See Reading and Access rules.

Instance properties

MemberWhat it is
schemaThe schema, with presets and plugins merged in
site{ url, name }
localizationThe localization options with their defaults, or undefined
populate{ depth, maxDepth }
adminPathThe path of the admin, or undefined with admin: false
auth()The better-auth instance
sitemap()The sitemap entries, read as a visitor
fetch(request)Answers /_tenon/*, /sitemap.xml and /robots.txt. Adapters call it

Errors

Every method throws these:

  • An unknown collection or global: an Error.
  • An unknown locale, or any locale without localization: a ValidationError.
  • A write to the media collection outside cms.media: a ValidationError.
  • An access rule that denies: a ForbiddenError, 401 without a user and 403 with one.

See Errors and types.