Working with Content

HTTP API and Client

Read and write content from the browser or another service.

Browser code and other services reach your content over HTTP, under /_tenon. The client from tenoncms/client wraps it with the same methods and types as the local API.

import { createClient } from "tenoncms/client";

const client = createClient();
const posts = await client.find("posts", { where: { featured: true }, limit: 3 });

The client

createClient() returns a client with the methods of the local API: find, findOne, findById and getGlobal to read, and create, update, delete and setGlobal to write. They take the same options. A few return null or throw a 404 where the local API returns undefined. See Differences to the local API.

Use it in code that runs in the browser, like islands, client components and admin pages. On the server, call the CMS instance directly. It skips HTTP.

A failed request throws a CmsError, also from tenoncms/client. Its status is the HTTP status, and its body the parsed response. For invalid data, body.errors holds one message per field, keyed by its path, like text or seo.title.

Options

createClient() takes these options:

The origin of the site that runs Tenon, like https://example.com. Default: the current origin.An API key, sent as the x-api-key header. The client then acts as the key, within its permissions. For server code only.The fetch function to use, for example one that forwards cookies. Default: the global fetch.

Call from another service

A script, a build or the server of another app can use the API with an API key. Admins create keys in the admin under Manage → API keys and pick what each key may do.

scripts/sync-products.ts
import { createClient } from "tenoncms/client";

const client = createClient({
  baseUrl: "https://example.com",
  apiKey: process.env.TENON_API_KEY,
});

await client.create("products", { name: "Chair", sku: "CH-1" });
An API key MUST NOT reach a browser. Anyone who has the key can do everything its permissions allow.

A browser on another origin can only call the content routes and the routes of the admin bar, and only from the origin of site.url. Other routes send no CORS headers, so a browser on another origin cannot read their answers. For a frontend on another origin, or Tenon without a site, see Headless.

Types without an adapter

The client is typed from your schema. Astro and Nuxt register the type of your CMS instance, so createClient() needs no type argument. On TanStack Start and other frameworks, add this to tsconfig.json:

tsconfig.json
{
  "compilerOptions": {
    "types": ["tenoncms/register"],
    "paths": { "#tenon/config": ["./tenon.config.ts"] }
  }
}

createClient<typeof cms>() with import type cms from "./tenon.config" works too, and overrides the registered type.

What is public

The HTTP API applies the access rules for the caller of each request. Without rules of your own:

RequestWho may send it
Read published contentEveryone, without a session
Read draftsSigned-in users, inside the live preview
Create, update, publish and deleteSigned-in users, and API keys with the permission
Users, API keys, jobs and other settingsSigned-in users. Some routes need the admin role
  • Reads are public because your site renders that content anyway.
  • A write without a session or an API key answers 401. A signed-in user whom a rule denies gets 403.
  • Fields with private: true are left out of responses for callers without a session.
  • A filter on a field that is not in the schema, or that the caller may not read, answers 400.

Write from the site

A form on your site can create documents. This example lets visitors post comments.

Allow anyone to create comments

create: true replaces the default rule, so the API accepts a create without a session:

cms/collections/comments.ts
import { defineCollection } from "tenoncms";

export const comments = defineCollection({
  access: { create: true },
  fields: {
    post: { type: "relation", collection: "posts", required: true, onDelete: "cascade" },
    name: { type: "text", required: true, maxLength: 80 },
    text: { type: "textarea", required: true, maxLength: 2000 },
  },
});

Add it to collections in tenon.config.ts.

Send the form with the client

---
const { postId } = Astro.props;
---

<form id="comment-form">
  <input type="hidden" name="post" value={postId} />
  <input name="name" required />
  <textarea name="text" required></textarea>
  <button>Send</button>
</form>

<script>
  import { createClient } from "tenoncms/client";

  const client = createClient();
  const form = document.querySelector<HTMLFormElement>("#comment-form")!;

  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    const data = new FormData(form);
    await client.create("comments", {
      post: String(data.get("post")),
      name: String(data.get("name")),
      text: String(data.get("text")),
    });
    form.reset();
  });
</script>

The API validates the input like every other write. Invalid input throws a CmsError with status 400, and error.body.errors holds the message for each field. A new comment is published at once, so everyone can read it.

create: true lets anyone write to the collection. Keep its fields few, and set required and maxLength on them. Tenon does not limit how often a visitor can send the form.

Review comments before they show

To show only the comments an editor approved, add a read rule and an approved field that visitors cannot set:

cms/collections/comments.ts
export const comments = defineCollection({
  access: {
    create: true,
    // Visitors read approved comments. Signed-in users read all of them.
    read: ({ user }) => (user ? true : { approved: true }),
  },
  fields: {
    // ...
    approved: { type: "boolean", default: false, access: { create: ["admin", "editor"] } },
  },
});

A visitor's value for approved is dropped, so a new comment waits. Editors approve it in the admin.

Without the client

The client only builds requests to the HTTP API. You can send them yourself:

GET /_tenon/collections/posts?category=news&limit=5
GET /_tenon/collections/posts/:id
GET /_tenon/globals/footer
POST /_tenon/collections/comments
PUT /_tenon/collections/posts/:id
DELETE /_tenon/collections/posts/:id
  • Query parameters are equality filters, like where. ?category=null matches an empty or missing field.
  • limit, populate, depth, select, locale, fallback, alternates and permalink are options, not filters. You cannot filter on fields with these names over HTTP.
  • populate and select take dot paths, separated by commas: ?populate=author&select=title,author.name.
  • Writes send the data as JSON. PUT changes only the fields it sends.
  • An error answers JSON with a message. A 400 for invalid data adds errors, the messages by field path.