Headless
Tenon is built to run inside your site. It also works as a headless CMS: another frontend, an app or a service reads the content over the HTTP API. A site on another origin can still show drafts to editors, the admin bar and the live preview. This page explains how to set that up, and what does not work yet.
import { createClient } from "tenoncms/client";
const cms = createClient({ baseUrl: "https://cms.example.com" });
const posts = await cms.find("posts", { limit: 10 });
Two setups
You can use Tenon headless in two ways:
- Next to your site. Your Astro, Nuxt or TanStack Start site embeds Tenon as usual. A mobile app, a second site or a script reads from it over HTTP.
- On its own. A small Vite app runs only the API and the admin, without pages. Every frontend reads over HTTP. To create one, run
npm create tenoncms@latestand pick Standalone.
The standalone app has one server entry. It serves the admin page and hands every other request to the CMS:
import html from "#tenon/admin-html";
import cms from "./tenon.config";
const admin = cms.adminPath!;
export default {
fetch(request: Request) {
const { pathname } = new URL(request.url);
if (pathname === admin || pathname.startsWith(`${admin}/`)) {
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
}
return cms.fetch(request);
},
};
tenonAdmin() and Nitro in vite.config.ts build the admin and the server. See Standalone for the full project.
Set the origins
When the site and the CMS run on different origins, tenon.config.ts MUST set both:
export default defineCms({
// ...
site: { url: "https://www.example.com" },
auth: { baseURL: "https://cms.example.com" },
});
site.urlis the public site. CORS allows its origin, and the sitemap,robots.txtand the URLs frompermalinkuse it. The admin opens relative preview URLs on it.auth.baseURLis the origin of the CMS, without a path. Sign-in, invites and every link into the admin use it.
A standalone project from npm create tenoncms reads both from TENON_SITE_URL and TENON_CMS_URL.
With only site.url, sign-in uses the site's origin. Signing in to the admin then fails with INVALID_ORIGIN, and media URLs stay relative.
Set permalink on a collection to the URL pattern of the site, like /blog/{slug}. The sitemap, links in rich text, link fields and the admin's preview then point to the site's pages. A collection that the site does not render gets no permalink.
Share the cookies
Drafts, the admin bar and the live preview need the editor's cookies on the site. The site and the CMS MUST then be two hosts of one parent domain, like www.example.com and cms.example.com. Put the cookies on the parent domain:
export default defineCms({
// ...
site: { url: "https://www.example.com" },
auth: {
baseURL: "https://cms.example.com",
advanced: { crossSubDomainCookies: { enabled: true, domain: "example.com" } },
},
});
- The session cookie, the session hint and the preview cookie then live on
example.com, so the browser sends them to the site too. - Set
domainyourself. Without it, the cookies stay on the CMS host. - Two ports on
localhostneed none of this, because cookies ignore ports. - Serve both over HTTPS. With an
httpsauth.baseURL, the session cookie isSecure, and the browser sends it only to HTTPS pages.
Allow more origins
To allow more origins, like a staging site, set cors. It takes the options of Hono's cors() and replaces the defaults key by key. An origin replaces site.url, so list the site too:
export default defineCms({
// ...
cors: { origin: ["https://www.example.com", "https://staging.example.com"] },
});
Read content
How the site reads depends on where its code runs:
| Where | Use | Reads |
|---|---|---|
| A page rendered per request | createRequestClient(request, options) | Drafts for an editor in preview, else published |
| A build or a script | createClient(options) | Published content |
| Browser code | createClient(options) | Published content |
On each request
createRequestClient() reads with the cookies of the page request. Create one for each request:
import { createRequestClient } from "tenoncms/client";
export const cmsClient = (request: Request) =>
createRequestClient(request, { baseUrl: "https://cms.example.com" });
---
import { cmsClient } from "../../lib/cms";
const post = await cmsClient(Astro.request).findOne("posts", {
where: { slug: Astro.params.slug! },
});
if (!post) return new Response("Not found", { status: 404 });
---
- It sends the request's
cookieheader to the CMS, and to no other origin. No other header travels. - A signed-in editor in preview reads drafts. Everyone else reads published content, as a visitor.
How drafts reach a page:
- The editor signs in at the CMS. The browser keeps the session cookie for the parent domain.
- The Drafts / Published switch of the admin bar, or the admin's visual editor, sets the preview cookie.
- The browser sends both cookies with every page request to the site.
createRequestClient()passes them on to the CMS.- The CMS returns drafts only for a valid session with the preview cookie. Without a session, it returns published content, even with the preview cookie.
At build time
A build has no page request, so it reads published content with createClient():
const posts = await cms.find("posts", {
select: { title: true, slug: true, cover: true },
limit: 10,
});
- Published content is public, so reads need no API key.
- A collection that visitors may not read needs an API key with
readon it. Fields withprivate: truestay hidden, even from a key. - A frontend in another language than JavaScript sends plain HTTP requests:
GET https://cms.example.com/_tenon/collections/posts?limit=10returns JSON. See Without the client. - The helpers from
tenoncms/client, likeseoHead()andswitchTarget(), work in any JavaScript frontend.renderRichtext()fromtenoncms/richtextturns rich text into HTML.
In the browser
The API answers CORS for the origin of site.url. Browser code on the site can call the content routes and the routes of the admin bar, with GET and POST, and with content-type as the only request header.
- A
createClient()in the browser sends no cookies, so it reads published content. To send them, pass your ownfetchwithcredentials: "include". - Sign-in, users, API keys and invites stay closed to other origins.
cors.allowMethodsreplaces the default["GET", "POST"]. List those too when you addPUTorDELETE.- For any other route, add Hono's
cors()yourself aspublicMiddlewareof a plugin. Then you decide what another origin can reach.
Types
The client is typed when the frontend can see the type of your CMS instance:
- In the same repository, import only the type. It puts no CMS code into the site's bundle:src/lib/cms.ts
import { createRequestClient } from "tenoncms/client"; import type cms from "../../../cms/tenon.config"; export const cmsClient = (request: Request) => createRequestClient<typeof cms>(request, { baseUrl: "https://cms.example.com" }); - In another repository, the client has no schema. Collection names are plain strings, and documents are loosely typed.
Admin bar and live preview
Start the preview runtime on every page of the site, with the full URL of the admin:
<script>
import { preview } from "tenoncms/preview";
preview({ admin: "https://cms.example.com/admin", morph: true });
</script>
- The live preview trusts only the origin of
admin. The admin bar calls the API on that origin, with the CMS's cookies. If you changeadmin.path, change it here too. morph: truerenders the page again from the server after each draft save, so content that is not marked updates too.tenoncms/previewneeds no Tenon adapter. Any bundler builds it.
Mark what a field renders with edit(), like on a site with an adapter:
<h1 data-cms={edit("posts", post.id, "title")}>{post.title}</h1>
The visual editor lists the marked documents under On this page, and the live preview writes unsaved values into the marked elements. See Mark the elements.
Images and files
When site.url and auth.baseURL are set to different origins, reads return media URLs absolute on the CMS, like https://cms.example.com/_tenon/media/…. This covers src, every entry of srcset and images in rich text. URLs that are already absolute, from publicUrl or a hosted image provider, stay as they are.
imageAttrs() from tenoncms/components turns an image into the attributes of an <img>. With data-cms, the live preview also swaps the image:
---
import { imageAttrs } from "tenoncms/components";
import { edit } from "tenoncms/preview";
const hero = imageAttrs(post.hero, {
"data-cms": edit("posts", post.id, "hero"),
sizes: "(min-width: 720px) 720px, 100vw",
});
---
{hero && <img {...hero} />}
See Media for storage and image providers.
Write content
A request client writes as the signed-in editor, with the editor's access rules. Writes with a JSON body work, like create() and update().
Writes without a JSON body, like publish(), delete() and media.upload(), answer 403 from a server. The CMS's CSRF check wants an Origin header, and a server sends none. Use a client with an API key for those, on the frontend's server:
export const writer = createClient({
baseUrl: "https://cms.example.com",
apiKey: process.env.TENON_API_KEY,
});
A client with a key acts as the key, also for reads. A key needs read on every collection and global it reads, even on published content. Keep a client without a key for reads.
Rebuild on publish
A static frontend shows the content of its last build. A webhook tells your host to build again when an editor publishes.
The example
The repository has a full headless setup in two examples:
examples/standaloneis the CMS, on port 3200. It readsTENON_SITE_URLandTENON_CMS_URLfrom the environment.examples/headless-siteis an Astro site on port 4324, without the Tenon integration. It imports onlytenoncms/client,tenoncms/previewandtenoncms/components.
Run both from the root of the repository:
cp -n examples/standalone/.env.example examples/standalone/.env
pnpm dev:headless
Open http://localhost:3200/admin, create the first admin and publish a post. Then open http://localhost:4324: the admin bar shows, and Edit opens the page in the visual editor.
Production checklist
- Serve the site and the CMS from one parent domain, like
www.example.comandcms.example.com. - Set
site.urlto the site andauth.baseURLto the CMS. - Set
crossSubDomainCookies, withdomainset to the parent domain. - Serve both over HTTPS.
- Build the site with the CMS origin, without a path or a trailing slash. A build writes it into the browser code.
Limits
Tenon is a proof of concept, and the headless setup has gaps:
- One parent domain. Drafts, the admin bar and the live preview need shared cookies. Unrelated domains do not work, because there is no token flow.
- Admin bar items with browser code are skipped on a site without a Tenon adapter, like an
onClickor amountfromclientRef(). Links and menus still show. - No drafts at build time. A statically built site reads published content only. Use a page that renders per request for the preview.
- No generated types. A frontend in another repository gets an untyped client.
Related resources
- HTTP API and client: the client, its options and the routes.
- Live preview: mark elements and follow unsaved changes.
- API keys: create keys and set what they may do.
- Standalone: create and deploy a standalone project.
- Build a headless site with Next.js: a Next.js site with drafts, the admin bar and the live preview.