Build a Headless Site with Next.js
This recipe builds a Next.js site that reads its content from a Tenon CMS on another origin. Visitors see published content. A signed-in editor sees drafts, gets the admin bar on the site, and edits the page live in the admin's visual editor.
Next.js is not built on Vite, so Tenon cannot run inside it. The CMS runs as a Standalone project, and the site reads from it over HTTP. The same steps work for any server-rendered JavaScript framework.
examples/headless-nextjs. It uses tenoncms from npm, so you can copy the folder and run it.Before you start
- One folder that holds both projects, so the site can import the CMS types:
my-project/ ├── cms/ the Tenon CMS, on http://localhost:3200 └── site/ the Next.js site, on http://localhost:3000 - Headless explains the origins, the cookies and the limits. This recipe only shows the steps.
File names below are relative to the project of each section: cms/ while you set up the CMS, site/ while you build the site.
Set up the CMS
Create the CMS
In my-project, create a Tenon project in the folder cms. Pick Standalone, then Node:
npm create tenoncms@latest cms
pnpm create tenoncms cms
yarn create tenoncms cms
bun create tenoncms cms
The starter has a posts collection with permalink: "/posts/{slug}". The admin uses the permalink to open a post on the site.
Add a cover image
Add an image field to the collection, so the site can show a picture:
import { defineCollection } from "tenoncms";
export const posts = defineCollection({
titleField: "title",
permalink: "/posts/{slug}",
fields: {
title: { type: "text", required: true },
slug: { type: "slug", from: "title", required: true, unique: true },
cover: { type: "image" },
body: { type: "textarea" },
},
});
Set both origins
The CMS MUST know the site's origin and its own. The standalone starter reads both from the environment. If your tenon.config.ts has no auth.baseURL yet, add it next to site.url:
export default defineCms({
// ...
site: { url: process.env.TENON_SITE_URL, name: "My Site" },
auth: { baseURL: process.env.TENON_CMS_URL },
});
Then set both in .env:
TENON_SITE_URL=http://localhost:3000
TENON_CMS_URL=http://localhost:3200
site.urlis the site. The CMS allows CORS from its origin, and the admin opens permalinks on it.auth.baseURLis the CMS. Sign-in uses it, and media URLs become absolute on it.
Start the CMS
Start the CMS on port 3200:
cd cms
npm run dev -- --port 3200
Open http://localhost:3200/admin and create the first admin. Create a post, give it a cover image and publish it.
Build the site
Create the Next.js app
In my-project, create a Next.js app in the folder site, and install Tenon in it:
npx create-next-app@latest site --app --ts
cd site
npm install tenoncms
pnpm create next-app site --app --ts
cd site
pnpm add tenoncms
yarn create next-app site --app --ts
cd site
yarn add tenoncms
bun create next-app site --app --ts
cd site
bun add tenoncms
The site imports only tenoncms/client, tenoncms/preview and tenoncms/react. No CMS server code ends up in its bundle.
Set the CMS origin
NEXT_PUBLIC_TENON_CMS_URL=http://localhost:3200
The server reads content from this origin, and the browser loads the admin bar from it. It needs the NEXT_PUBLIC_ prefix, because browser code reads it.
- Give the origin only, without a path or a trailing slash.
- Next.js writes the value into the build. Set it before you build.
Create the client
Create one client for each page request:
import { headers } from "next/headers";
import { createRequestClient } from "tenoncms/client";
import type cms from "../../cms/tenon.config";
export async function cmsClient() {
return createRequestClient<typeof cms>(
{ headers: await headers() },
{ baseUrl: process.env.NEXT_PUBLIC_TENON_CMS_URL! },
);
}
createRequestClient()sends thecookieheader of the page request to the CMS. An editor with the preview cookie reads drafts, everyone else reads published content.headers()makes every page that callscmsClient()render per request.import typeputs no CMS code in the site. It types the collections and their fields.
List the posts
import Link from "next/link";
import { cmsClient } from "@/lib/cms";
export default async function Home() {
const cms = await cmsClient();
const posts = await cms.find("posts", { select: { title: true, slug: true } });
return (
<main>
<h1>Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={`/posts/${post.slug}`}>{post.title}</Link>
</li>
))}
</ul>
</main>
);
}
export default function Loading() {
return <p>Loading…</p>;
}
New Next.js apps turn on cacheComponents. A page that reads per request then needs a loading.tsx in its folder, or next build fails. Without cacheComponents, the file is optional.
Render a post
Mark each element that shows a field with edit(). The live preview writes unsaved values into these elements:
import { notFound } from "next/navigation";
import { edit } from "tenoncms/preview";
import { Image } from "tenoncms/react";
import { cmsClient } from "@/lib/cms";
export default async function Post({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const cms = await cmsClient();
const post = await cms.findOne("posts", { where: { slug } });
if (!post) notFound();
return (
<main>
<h1 data-cms={edit("posts", post.id, "title")}>{post.title}</h1>
<Image
image={post.cover}
data-cms={edit("posts", post.id, "cover")}
sizes="(min-width: 720px) 720px, 100vw"
/>
<p data-cms={edit("posts", post.id, "body")}>{post.body}</p>
</main>
);
}
Copy app/loading.tsx to app/posts/[slug]/loading.tsx. Next.js wants a loading state in each dynamic folder.
Imagerenders an<img>withsrc,width,heightandalt, andsrcsetwhen the CMS has an image provider. It works in server components.- The URLs point to the CMS, like
http://localhost:3200/_tenon/media/files/cover.jpg. notFound()in streamed content answers200with anoindextag. That is how Next.js streams; it is not a Tenon setting.
Start the preview runtime
preview() runs in the browser. Put it in a client component:
"use client";
import { useEffect } from "react";
import { preview } from "tenoncms/preview";
export function TenonPreview() {
useEffect(() => preview({ admin: `${process.env.NEXT_PUBLIC_TENON_CMS_URL}/admin` }), []);
return null;
}
Render it once, in the root layout:
import type { Metadata } from "next";
import { TenonPreview } from "./tenon-preview";
export const metadata: Metadata = { title: "My Site" };
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<TenonPreview />
</body>
</html>
);
}
adminis the full URL of the admin. The live preview trusts only its origin. If the CMS sets anotheradmin.path, change it here too.- Without a session,
preview()does nothing, and the code of the admin bar does not load.
Try it
- Start the site with
npm run devinsite, and openhttp://localhost:3000. It lists the post you published. - Sign in at
http://localhost:3200/admin, then openhttp://localhost:3000again. The admin bar shows at the bottom. Two ports onlocalhostshare cookies, so the site sees your session. - In the admin, open the post, switch it to Draft and change the body. The admin saves the draft as you type. Switch the admin bar to Drafts: the page shows the draft. Published shows the live version.
- Select Edit in the admin bar. The admin opens the page in its visual editor. Switch the form to the draft and type: the page follows as you type.
Unsaved values reach only the elements with data-cms. The rest of the page shows the saved content after a reload in the visual editor.
Go to production
On real domains, the site and the CMS MUST be two hosts of one parent domain, like www.example.com and cms.example.com. The editor's cookies then need to live on the parent domain:
export default defineCms({
// ...
site: { url: process.env.TENON_SITE_URL },
auth: {
baseURL: process.env.TENON_CMS_URL,
advanced: { crossSubDomainCookies: { enabled: true, domain: "example.com" } },
},
});
- Deploy the CMS like any standalone project, on Node or Vercel. Deploy the site wherever Next.js runs.
- Build the site with
NEXT_PUBLIC_TENON_CMS_URL=https://cms.example.com. - Serve both over HTTPS.
The production checklist lists every step, and explains what sharing the session cookie means for security.
Related resources
examples/headless-nextjs: the finished code of this recipe.- Headless: origins, cookies, CORS, writes and limits.
- Standalone: the CMS project and its files.
- Live preview: what
edit()marks and how the visual editor uses it. - Components:
Image,Richtext,Blocksand the other React components. - Rebuild on publish: build a static site again when an editor publishes.