HTTP API and Client
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:
https://example.com. Default: the current origin.x-api-key header. The client then acts as the key, within its permissions. For server code only.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.
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" });
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:
{
"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:
| Request | Who may send it |
|---|---|
| Read published content | Everyone, without a session |
| Read drafts | Signed-in users, inside the live preview |
| Create, update, publish and delete | Signed-in users, and API keys with the permission |
| Users, API keys, jobs and other settings | Signed-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 gets403. - Fields with
private: trueare 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:
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>
<script setup lang="ts">
import { createClient } from "tenoncms/client";
const props = defineProps<{ postId: string }>();
const client = createClient();
const name = ref("");
const text = ref("");
async function send() {
await client.create("comments", { post: props.postId, name: name.value, text: text.value });
name.value = "";
text.value = "";
}
</script>
<template>
<form @submit.prevent="send">
<input v-model="name" required />
<textarea v-model="text" required />
<button>Send</button>
</form>
</template>
import { createClient } from "tenoncms/client";
const client = createClient();
export function CommentForm({ postId }: { postId: string }) {
async function send(data: FormData) {
await client.create("comments", {
post: postId,
name: String(data.get("name")),
text: String(data.get("text")),
});
}
return (
<form action={send}>
<input name="name" required />
<textarea name="text" required />
<button>Send</button>
</form>
);
}
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:
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=nullmatches an empty or missing field. limit,populate,depth,select,locale,fallback,alternatesandpermalinkare options, not filters. You cannot filter on fields with these names over HTTP.populateandselecttake dot paths, separated by commas:?populate=author&select=title,author.name.- Writes send the data as JSON.
PUTchanges only the fields it sends. - An error answers JSON with a
message. A400for invalid data addserrors, the messages by field path.
Related resources
- Access control: roles and rules.
- API keys: create keys and set what they may do.
- Reading:
where,selectandpopulatein detail. - Client and HTTP routes: every method and route.