Local API
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
| Where | Access rules | User | Reads |
|---|---|---|---|
| The imported instance | Skipped | None | Published |
cms.withDrafts() | Like its parent | Like its parent | Drafts |
await cms.withSession(request) | Applied | The request's user or API key | Drafts in preview, else published |
| A hook | Skipped | The operation's user | Like the operation |
A task, seed, onInit, afterError | Skipped | None | Published |
A plugin's routes | Applied | The session user | Drafts in preview, else published |
A plugin's publicRoutes, sitemap.entries, robots.rules | Applied | None | Published |
An admin page's load, an action's run | Applied | The signed-in user | The user's view |
- A hook's
cmsshares the transaction, the locale and thecontextof its operation. See Hooks. - Only the imported instance and its
withDrafts()andwithSession()copies haveusers,withSession(),jobs.run(),sitemap(),fetch()and the instance properties.
Reads
| Method | Returns |
|---|---|
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
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.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.populate resolves. Default: populate.depth, 2. The local API has no limit.{ 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.localization.fallback.permalink, the public URL in the read's locale, or null. Collections only.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
| Method | Returns |
|---|---|
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.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
| Method | Returns |
|---|---|
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
| Method | What 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
| Method | Returns |
|---|---|
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").
| Method | Returns |
|---|---|
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
| Method | Returns |
|---|---|
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.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.
| Method | What 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
| Method | Returns |
|---|---|
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
| Method | Returns |
|---|---|
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
| Member | What it is |
|---|---|
schema | The schema, with presets and plugins merged in |
site | { url, name } |
localization | The localization options with their defaults, or undefined |
populate | { depth, maxDepth } |
adminPath | The 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 anylocalewithout localization: aValidationError. - A write to the
mediacollection outsidecms.media: aValidationError. - An access rule that denies: a
ForbiddenError,401without a user and403with one.
See Errors and types.
Related resources
- Client: the same methods over HTTP.
- Reading and Writing and drafts: the guides behind these methods.