Pages and SEO
A website usually has (nested) pages and needs meta tags in <head>. Additionally you would want a sitemap and robots.txt for search engines. Tenon offers sensible presets and defaults to get you up and running fast. This page shows how to do all that.
The pages preset
pagesPreset() adds a pages collection. Each page has a title, a slug and a parent, and stores its full path:
import { defineCms } from "tenoncms";
import { pagesPreset } from "tenoncms/presets";
export default defineCms({
// ...
presets: [
pagesPreset({
seo: true, // adds a SEO tab with default fields you usually want on a page
blocks: {
hero: { label: "Hero", fields: { title: { type: "text", required: true } } },
text: { label: "Text", fields: { body: { type: "richtext" } } },
},
}),
],
});
blocksadds acontentfield with these sections.seo: trueadds an SEO tab with a title, a description, a share image and "hide from search engines".localized: truegives each page a version per language. See Localization.
Pages lists the fields, all options, and how paths work.
Render pages
One catch-all route renders every page. It reads the page by its path and puts its tags into <head>:
---
import { Blocks, Seo } from "tenoncms/astro/components";
import Hero from "../blocks/Hero.astro";
import Text from "../blocks/Text.astro";
export const prerender = false;
const page = await Astro.locals.tenon.findOne("pages", {
where: { path: `/${Astro.params.path ?? ""}` },
populate: { seo: { image: true } },
});
if (!page) return new Response(null, { status: 404 });
---
<html lang="en">
<head>
<meta charset="utf-8" />
<Seo page={page} />
</head>
<body>
<h1>{page.title}</h1>
<Blocks blocks={page.content} components={{ hero: Hero, text: Text }} />
</body>
</html>
<script setup lang="ts">
import Hero from "~/components/blocks/Hero.vue";
import Text from "~/components/blocks/Text.vue";
const route = useRoute();
const { data: page } = await useTenon().findOne(
"pages",
() =>
({
where: { path: route.path },
populate: { seo: { image: true } },
}) as const,
);
if (!page.value) throw createError({ statusCode: 404, statusMessage: "Page not found" });
await useTenonSeo(page);
</script>
<template>
<main v-if="page">
<h1>{{ page.title }}</h1>
<TenonBlocks :blocks="page.content" :components="{ hero: Hero, text: Text }" />
</main>
</template>
import { createFileRoute, notFound } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/react-start";
import { getRequest } from "@tanstack/react-start/server";
import { seoHead } from "tenoncms/client";
import { Blocks } from "tenoncms/react";
import cms from "../../tenon.config";
import { Hero } from "../blocks/Hero";
import { Text } from "../blocks/Text";
const getPage = createServerFn()
.validator((path: string) => path)
.handler(async ({ data: path }) => {
const tenon = await cms.withSession(getRequest());
const page = await tenon.findOne("pages", {
where: { path },
populate: { seo: { image: true } },
});
if (!page) throw notFound();
const [general, seo] = await Promise.all([tenon.getGlobal("general"), tenon.getGlobal("seo")]);
return { page, general, seo, site: cms.site.url };
});
export const Route = createFileRoute("/$")({
loader: ({ params }) => getPage({ data: `/${params._splat ?? ""}` }),
head: ({ loaderData }) => {
if (!loaderData) return {};
const { title, meta, links } = seoHead(loaderData.page, loaderData);
return { meta: [{ title }, ...meta], links };
},
component: Page,
});
function Page() {
const { page } = Route.useLoaderData();
return (
<main>
<h1>{page.title}</h1>
<Blocks blocks={page.content} components={{ hero: Hero, text: Text }} />
</main>
);
}
- Your other routes, like
/or/posts/[slug], win over the catch-all route. A CMS page at the same path never shows. populate: { seo: { image: true } }loads the share image. Without it, the page has noog:image.- With languages, read the path without the language prefix, in the page's language. See Per framework.
prerender = false reads the page on each request. For prerendered pages, see Prerendered pages and preview routes.useTenonSeo() reads the general and seo settings and site.url itself.withSession() lets the admin's preview read drafts. head() gets the loader data, so read the settings in the same server function.Permalinks
A permalink is the public URL of a document. The pages preset sets it for you. Other collections need it too, so Tenon knows where their documents live:
export const posts = defineCollection({
permalink: "/posts/{slug}",
fields: {
title: { type: "text", required: true },
slug: { type: "slug", from: "title" },
},
});
These features use the permalink:
- the sitemap
- link fields and links in rich text
- the live preview
- the canonical and
hreflangtags - reads with
permalink: true. See Add the public URL.
A placeholder can walk into a group or through one relation, like /{category.slug}/{slug}. A document with an empty value in a placeholder has no URL.
For logic a template cannot express, pass a function. It gets the document and returns the URL, or null for none:
permalink: (doc) => (doc.slug ? `/notes/${doc.slug}` : null),
permalink returns. Tenon does not add routes for them.Head tags
Search engines and social networks read the tags in <head>. The Seo component, useTenonSeo() in Nuxt, and seoHead() fill them from three sources, in this order:
- The document's own SEO fields.
- The title and description templates of its collection.
- The site's
seoandgeneralsettings.
They render these tags:
| Tag | Value |
|---|---|
<title>, og:title | The title template with the placeholders filled. Default {title} · {site.title}. |
description | The document's SEO description, else the description template. Left out when empty. |
og:image | The document's share image, else the site's. An absolute URL when site.url is set. |
og:url, canonical | site.url plus the document's path. For other collections, read with permalink: true. |
hreflang links | The URL of each translation. Needs alternates: true on the read. |
robots | noindex, nofollow when the document or the whole site is hidden from search engines. |
og:site_name | The site title from the general settings. |
To add the tags to a page, see Seo in Components.
Placeholders
Titles and descriptions are templates. Tenon fills them when the page renders, so a page follows changes to its title or to the settings:
| Placeholder | Value |
|---|---|
{title}, {excerpt}, … | A field of the document. A dot walks into a group or relation: {category.title}. |
{site.title}, {site.tagline} | The general settings. |
- An empty placeholder is left out, with the separators around it.
{title} · {site.title}without a site title givesAbout. - An editor's own SEO title fills
{title}.Buy watchesgivesBuy watches · Acme. Use as the full title turns the template off for that page.
Templates per collection
Posts often need other titles than pages. seo() adds the SEO fields to any collection, with its own templates:
import { defineCollection } from "tenoncms";
import { seo } from "tenoncms/presets";
export const posts = defineCollection({
permalink: "/posts/{slug}",
fields: {
title: { type: "text", required: true },
excerpt: { type: "text" },
...seo({ title: "{title} – Blog · {site.title}", description: "{excerpt}" }).fields,
},
});
The admin reads the templates from the schema. Your site MUST pass them too, or it falls back to the site's templates:
---
import { Seo } from "tenoncms/astro/components";
import { posts } from "../../../cms/collections/posts";
---
<Seo page={post} templates={posts.fields.seo.templates} />
<script setup lang="ts">
import { posts } from "~~/cms/collections/posts";
await useTenonSeo(post, { templates: posts.fields.seo.templates });
</script>
import { posts } from "../../../cms/collections/posts";
const { title, meta, links } = seoHead(loaderData.post, {
...loaderData,
templates: posts.fields.seo.templates,
});
Your own templates
seoMeta() returns the values without tags, for a layout that builds <head> itself:
import { seoMeta } from "tenoncms";
const [general, seo] = await Promise.all([cms.getGlobal("general"), cms.getGlobal("seo")]);
const { title, description, image, canonical, alternates, noindex } = seoMeta(page, {
general,
seo,
site: cms.site.url,
});
seoHead() takes the same arguments and returns { title, meta, links }, ready for a framework's head API. Both come from tenoncms. In browser code, import them from tenoncms/client.
What editors see
The SEO tab helps editors write good titles and descriptions:
- A search preview with the URL, the title and the description, as the site renders them.
- Checks for the length of the title (30–60 characters) and the description (120–160), and for a share image.
- An Auto-generate button that copies the default into the field, to edit it from there.
Breadcrumbs
breadcrumbs() builds the trail from the top page down to the current one. Load the parents with populate, one level per level of your tree:
import { breadcrumbs } from "tenoncms";
const page = await cms.findOne("pages", {
where: { path: "/about/team/anna" },
populate: { parent: { parent: true } },
select: {
title: true,
path: true,
parent: { title: true, path: true, parent: { title: true, path: true } },
},
});
breadcrumbs(page);
// [{ title: "About", path: "/about" }, { title: "Team", … }, { title: "Anna", … }]
- The trail starts at the highest parent that
populateloaded. It makes no queries. - For other field names, pass them:
breadcrumbs(doc, { title: "name", path: "url", parent: "up" }).
Sitemap and robots.txt
Tenon serves /sitemap.xml and /robots.txt without any config. Astro and Nuxt add both routes. On TanStack Start, add one route file each. See TanStack Start.
The sitemap lists every published document of each collection with a permalink:
- Each language is its own entry, with
hreflanglinks to the others. lastmodis the date of the last change.- Drafts, documents hidden from search engines, and collections that visitors may not read are left out.
- URLs are absolute, based on
site.url. Set it in production, so the URLs use your public domain.
robots.txt allows the whole site except the API under /_tenon/. Media files stay allowed. It links to the sitemap.
robots.txt blocks the whole site. Turn it off before launch.Add your own routes
sitemap.entries gets the generated entries and returns the list. robots.rules does the same for the rules of robots.txt:
export default defineCms({
// ...
sitemap: {
entries: async ({ cms, entries }) => [
...entries,
{ url: "/contact" },
...(await cms.find("products")).map((p) => ({ url: `/shop/${p.sku}`, lastmod: p.updatedAt })),
],
},
robots: {
rules: ({ rules }) => [...rules, { userAgent: "GPTBot", disallow: ["/"] }],
},
});
- An entry is
{ url, lastmod?, alternates? }. Relative URLs become absolute. cmsreads as a visitor: published content within the access rules.
Turn them off
| To | Set |
|---|---|
| Leave one collection out | sitemap: false on the collection |
| Turn off the sitemap | sitemap: false in defineCms() |
Turn off robots.txt | robots: false in defineCms() |
Use your own route
A route of your own for /sitemap.xml or /robots.txt replaces the built-in one:
- a file in
public/, likepublic/robots.txt - a route file, like
src/pages/sitemap.xml.tsin Astro orserver/routes/sitemap.xml.tsin Nuxt - in Nuxt, the
@nuxtjs/sitemapor@nuxtjs/robotsmodule
Restart the dev server after you add one.
To build on the generated entries, cms.sitemap() returns them, and sitemapXml() writes the XML:
import { sitemapXml } from "tenoncms";
import cms from "../../tenon.config";
export const GET = async () =>
new Response(sitemapXml([...(await cms.sitemap()), { url: "https://example.com/extra" }]), {
headers: { "content-type": "application/xml" },
});
sitemapXml() writes the URLs as you pass them, so pass absolute ones. robotsTxt({ rules, sitemaps }) writes a robots.txt the same way.
Site settings
Every site has two settings globals. Editors find them on the Settings page of the admin:
| Global | Fields |
|---|---|
general | title, tagline, favicon |
seo | title and description templates, share image, "hide from search engines" |
The head tags read both:
- The site title fills
{site.title}, the tagline{site.tagline}. - The
seotemplates apply to every document without a template of its own collection. - The share image applies to every document without its own.
- "Hide from search engines" hides the whole site. See the warning in Sitemap and robots.txt.
A global that nobody saved yet reads as {}. Handle a missing title in your templates.
To add fields, like a phone number, or to remove a global, see Settings. To put your own globals on the Settings page, see The Settings page.
Related resources
- Pages: the fields and options of the pages preset.
- Components: render images, links, blocks and head tags.
- Localization: URLs per language and the language switch.
- Tracking and consent: verification codes and analytics.