Working with Content

Reading

Query content from server code, typed from the schema.

Your server code reads content with direct calls on the CMS instance. There is no HTTP in between, and the result types come from your schema.

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

The local API

The local API is the set of methods on the instance that tenon.config.ts exports, like cms.find() and cms.getGlobal(). The methods are the same in every framework. Only the way a page gets the instance differs:

---
export const prerender = false;

const post = await Astro.locals.tenon.findOne("posts", {
  where: { slug: Astro.params.slug },
});
if (!post) return new Response(null, { status: 404 });
---

<h1>{post.title}</h1>
Astro.locals.tenon is the instance for the current request. A page with prerender = false reads on each request. A prerendered page reads once, at build time.

Find documents

Four methods read content:

// Every post, newest first
await cms.find("posts");

// The first match, or undefined
await cms.findOne("posts", { where: { slug: "hello-world" } });

// One document by id, or undefined
await cms.findById("posts", id);

// A global
await cms.getGlobal("footer");

where filters by field values. limit caps the number of documents:

await cms.find("posts", { where: { category: "news", featured: true }, limit: 5 });
  • A document matches when every key in where is equal. null matches an empty or missing field. A key set to undefined adds no filter.
  • You can filter on top-level fields that hold one value, like text, numbers, dates, a select or a single relation (by its id). createdBy and updatedBy hold user ids.
  • limit MUST be a positive integer.
  • A name that is not in the schema is a type error, for collections, globals and fields.
  • A global that was never saved has no field values. Handle missing values in your templates.
Filters match equal values only, and reads always return the newest documents first. There is no sort or offset option.

Add the public URL

permalink: true adds each document's public URL, from the collection's permalink:

const posts = await cms.find("posts", { permalink: true });
// posts[0].permalink is "/posts/hello-world"

The value is null when the collection has no permalink, or when a placeholder in it has no value. In a localized collection, the URL has the locale prefix of the read's locale. See Localization.

Pick fields and relations

By default, a read returns every field and loads related documents two levels deep. Two options change that:

  • select lists the fields to return.
  • populate picks which relations to load. See Relations.
const posts = await cms.find("posts", {
  populate: { author: true },
  select: { title: true, slug: true, author: { name: true } },
});

Each post is now { id, title, slug, author: { id, name } }. The result type follows the options, so posts[0].body is a type error.

The value of each key in select decides what comes back:

In selectResult
a field: trueThe value of the field
a group: trueThe whole group
a group: { … }Only the listed fields of the group
a relation or join: trueThe value as populate leaves it: ids or documents
a relation or join: { … }The loaded documents, with only the listed fields
a field that is not listedLeft out
  • id always comes back. createdAt, updatedAt, createdBy, updatedBy, publishedAt, hasDraft, permalink and alternates come back only when you list them.
  • select: {} returns only id.
  • afterRead hooks still see whole documents. select trims the result after them.

Drafts

Reads return published content. A document that was never published is missing, and a pending draft does not show.

The admin's live preview needs to show drafts on your real pages. For that, read through cms.withSession(request). It returns an instance for the user of the request:

  • With a session and the preview cookie that the admin sets, its reads return drafts.
  • For everyone else, its reads return published content.
  • It applies the access rules for that user. The instance you import skips them.
The integration calls withSession() for you. Astro.locals.tenon is already bound to the request.

Every document also has publishedAt (null when it was never published) and hasDraft.

cms.withDrafts() returns an instance whose reads always see drafts. Use it in scripts and server code that is never public.

Do not use withDrafts() to render public pages. Every visitor would see unpublished content.

Result types

Components that receive content need a type for their props. DocumentOf from tenoncms/client types a document as a read returns it, with the same options. Keep the options in one place and use them for the read and the type:

src/content/posts.ts
import type { DocumentOf } from "tenoncms/client";

export const cardOptions = {
  select: { title: true, slug: true, cover: true },
} as const;

export type PostCard = DocumentOf<"posts", typeof cardOptions>;
const posts = await cms.find("posts", cardOptions);

Two more helpers work the same way:

  • GlobalOf<"footer"> types a global.
  • BlockOf<Page["content"]> types the items of a blocks field. BlockOf<Page["content"], "hero"> narrows it to one block type.

Image, File and LinkRead from tenoncms type a loaded image, file and link field.

The helpers use the type of your CMS instance. Astro and Nuxt register it for you. On other frameworks, see Types without an adapter.