Reading
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>
<script setup lang="ts">
const route = useRoute();
const { data: post } = await useTenon().findOne("posts", () => ({
where: { slug: String(route.params.slug) },
}));
if (!post.value) throw createError({ statusCode: 404 });
</script>
<template>
<h1>{{ post?.title }}</h1>
</template>
import { createFileRoute, notFound } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/react-start";
import cms from "../../../tenon.config";
const getPost = createServerFn()
.validator((slug: string) => slug)
.handler(async ({ data: slug }) => {
const post = await cms.findOne("posts", { where: { slug } });
if (!post) throw notFound();
return post;
});
export const Route = createFileRoute("/posts/$slug")({
loader: ({ params }) => getPost({ data: params.slug }),
component: Post,
});
function Post() {
const post = Route.useLoaderData();
return <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.useTenon() is auto-imported. It has the read methods find, findOne, findById and getGlobal, and returns the result of useAsyncData.
- Pass the options as a getter when they depend on the route. A reused page then reads again on navigation.
- During server rendering, the read stays in the process. On client-side navigation, it calls the HTTP API.
- For writes and other methods, a server route imports the instance from
#tenon/config.
tenon.config.ts. A server function always runs on the server.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
whereis equal.nullmatches an empty or missing field. A key set toundefinedadds 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).
createdByandupdatedByhold user ids. limitMUST 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.
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:
selectlists the fields to return.populatepicks 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 select | Result |
|---|---|
a field: true | The value of the field |
a group: true | The whole group |
a group: { … } | Only the listed fields of the group |
a relation or join: true | The 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 listed | Left out |
idalways comes back.createdAt,updatedAt,createdBy,updatedBy,publishedAt,hasDraft,permalinkandalternatescome back only when you list them.select: {}returns onlyid.afterReadhooks still see whole documents.selecttrims 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.
withSession() for you. Astro.locals.tenon is already bound to the request.useTenon() reads with the cookies of the request, so it shows drafts in the preview without extra code.Call withSession() with the request in the server function:
import { getRequest } from "@tanstack/react-start/server";
const getPost = createServerFn()
.validator((slug: string) => slug)
.handler(async ({ data: slug }) => {
const tenon = await cms.withSession(getRequest());
const post = await tenon.findOne("posts", { where: { slug } });
if (!post) throw notFound();
return post;
});
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.
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:
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.
Related resources
- Writing and drafts: create, update, publish and delete.
- Relations: load related documents with
populate. - HTTP API and client: the same reads from the browser or another service.
- Local API: every method and option.