Recipes

Build a Headless Site with Next.js

A Next.js site that reads from a standalone Tenon CMS, with drafts, the admin bar and the live preview.

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.

The finished code is in examples/headless-nextjs. It uses tenoncms from npm, so you can copy the folder and run it.
Headless use is experimental. Expect gaps and changes. See the limits.

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

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:

cms/collections/posts.ts
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:

tenon.config.ts
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:

.env
TENON_SITE_URL=http://localhost:3000
TENON_CMS_URL=http://localhost:3200
  • site.url is the site. The CMS allows CORS from its origin, and the admin opens permalinks on it.
  • auth.baseURL is 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

The site imports only tenoncms/client, tenoncms/preview and tenoncms/react. No CMS server code ends up in its bundle.

Set the CMS origin

.env.local
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:

lib/cms.ts
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 the cookie header 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 calls cmsClient() render per request.
  • import type puts no CMS code in the site. It types the collections and their fields.
A request client belongs to one request. Never keep one in a module variable, or one visitor reads with the cookies of another.

List the posts

app/page.tsx
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>
  );
}
app/loading.tsx
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:

app/posts/[slug]/page.tsx
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.

  • Image renders an <img> with src, width, height and alt, and srcset when 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 answers 200 with a noindex tag. 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:

app/tenon-preview.tsx
"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:

app/layout.tsx
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>
  );
}
  • admin is the full URL of the admin. The live preview trusts only its origin. If the CMS sets another admin.path, change it here too.
  • Without a session, preview() does nothing, and the code of the admin bar does not load.

Try it

  1. Start the site with npm run dev in site, and open http://localhost:3000. It lists the post you published.
  2. Sign in at http://localhost:3200/admin, then open http://localhost:3000 again. The admin bar shows at the bottom. Two ports on localhost share cookies, so the site sees your session.
  3. 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.
  4. 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:

tenon.config.ts
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.