Nuxt headless CMS
Use Spunto CMS as the headless CMS of a Nuxt site — server routes that keep the API key on the server, a client typed from the public OpenAPI spec, block rendering in Vue components, images relayed by Nitro, and a cache emptied by a webhook on every publication.
This guide builds a blog with Nuxt whose posts are written in a Spunto workspace. Editors work in lists and cards; the site's server routes read the published cards over REST, keep them in Nitro's cache, and a webhook empties that cache each time someone publishes.
There is no export and no second store in between — the card an editor
publishes is the record the site reads. Everything below runs against
https://cms.spunto.net on a free account, and was run end to end on Nuxt 4.6
(Nitro 2.13).
1. Model the content
The Templates gallery (/w/{workspaceId}/templates, for an admin of the
workspace — a new workspace shows it on its overview) has a Blog template:
Use makes a list Blog posts (prefix BLOG) with a slug property, a
Published on date and Tags, and three example posts. To do it by hand
instead: a list, then a text property named Slug under Properties
(/w/{workspaceId}/settings/proprietes) — check that its key reads slug.
Then publish the posts that should appear: the Publish button in a card's header. Every card is a draft until it is published, and this site only ever reads the published version. An editor can keep rewriting a published post; the site keeps the last published text until the card is published again.
Two identifiers come from the address bar of the list,
/w/{workspaceId}/c/{collectionId}. Then mint an API key with the viewer
role under API keys (/w/{workspaceId}/settings/api, details).
A site only reads; a key that can write is a key you have to protect harder.
NUXT_SPUNTO_TOKEN=spk_...
NUXT_SPUNTO_WORKSPACE_ID=...
NUXT_SPUNTO_COLLECTION_ID=...
NUXT_SPUNTO_WEBHOOK_SECRET=...The fourth one comes in step 6. A NUXT_* variable overrides the
runtimeConfig key of the same name (NUXT_SPUNTO_TOKEN → spuntoToken).
nuxt dev and nuxt build read .env; the built server does not — in
production, set the variables on your host.
2. A typed client in two commands
Start from the minimal template, then add the client:
npm create nuxt@latest my-blog -- --template minimal
cd my-blog
npm install openapi-fetch
npm install -D openapi-typescript typescript@5 vue-tsc @types/node
npx openapi-typescript https://cms.spunto.net/openapi.json -o shared/spunto-api.d.tsRe-run the last command whenever you want the types of a newer API. Fields
are only ever added to responses as optional, so an old generated file keeps
working against a newer server. The file goes in shared/ because both halves
of the app use it: the server routes for the client, the Vue components for the
block types.
TypeScript 5
typescript@latest on npm is 7. Neither openapi-typescript (its peer range is
^5) nor vue-tsc, which nuxt typecheck runs, starts on it: the first stops
on ts.factory being undefined, the second on a package path that TypeScript 7
no longer exports. Install 5 explicitly.
The token belongs on the server. Declare it, with the rest, in runtimeConfig
— not under runtimeConfig.public, which is sent to the browser:
export default defineNuxtConfig({
compatibilityDate: "2025-07-15",
// Server-only: nothing here is under `public`, so none of it reaches the
// browser. Each key is overridden at runtime by its NUXT_* variable.
runtimeConfig: {
spuntoApiUrl: "https://cms.spunto.net/api",
spuntoToken: "",
spuntoWorkspaceId: "",
spuntoCollectionId: "",
spuntoWebhookSecret: "",
},
})<template>
<NuxtPage />
</template>Everything that talks to Spunto lives in server/utils/, which Nuxt never
bundles for the browser. Its exports are auto-imported in every server route:
import createClient from "openapi-fetch"
import type { components, paths } from "#shared/spunto-api"
type Item = components["schemas"]["Item"]
type ItemDetail = components["schemas"]["ItemDetail"]
type ViewDefinition = components["schemas"]["ViewDefinition"]
function spunto() {
const config = useRuntimeConfig()
const cms = createClient<paths>({
baseUrl: config.spuntoApiUrl,
headers: { Authorization: `Bearer ${config.spuntoToken}` },
})
return { cms, workspaceId: config.spuntoWorkspaceId, collectionId: config.spuntoCollectionId }
}
const definition: ViewDefinition = {
sort: [{ field: { fieldId: "sys:created_at" }, direction: "desc" }],
includeSecondaryLists: false,
}
// `version: "published"`: only published cards, as they were when published.
// What an editor is still typing never reaches the site.
async function page(cursor: string | null) {
const { cms, workspaceId, collectionId } = spunto()
const { data, error } = await cms.POST(
"/workspaces/{workspaceId}/collections/{collectionId}/query",
{
params: { path: { workspaceId, collectionId } },
body: { definition, version: "published", cursor, limit: 200 },
},
)
if (error) throw createError({ statusCode: 502, statusMessage: `Spunto: ${error.error}` })
return data
}
// Cached by Nitro under `spunto:` — the webhook of step 6 empties that prefix.
export const listPublished = defineCachedFunction(
async (): Promise<Item[]> => {
const rows: Item[] = []
let cursor: string | null = null
do {
const { rows: more, nextCursor } = await page(cursor)
rows.push(...more)
cursor = nextCursor
} while (cursor)
return rows
},
{ group: "spunto", name: "posts", maxAge: 60 * 60 },
)
// A page of results never carries bodies; one card does.
export const getPost = defineCachedFunction(
async (itemId: string): Promise<ItemDetail> => {
const { cms, workspaceId } = spunto()
const { data, error } = await cms.GET("/workspaces/{workspaceId}/items/{itemId}", {
params: { path: { workspaceId, itemId }, query: { version: "published" } },
})
if (error) throw createError({ statusCode: 502, statusMessage: `Spunto: ${error.error}` })
return data
},
{ group: "spunto", name: "post", maxAge: 60 * 60, getKey: (itemId: string) => itemId },
)
export async function forgetContent() {
const cache = useStorage("cache")
for (const key of await cache.getKeys("spunto")) await cache.removeItem(key)
}
// Attachments have no public URL: the site relays them (step 5).
export async function fileContent(fileId: string) {
const { cms, workspaceId } = spunto()
const { response } = await cms.GET("/workspaces/{workspaceId}/files/{fileId}/content", {
params: { path: { workspaceId, fileId } },
parseAs: "stream",
})
return response
}
export function slugOf(item: Item): string {
return String(item.properties.slug ?? item.id)
}Three things the API does that this code relies on:
- reading is a
POST, because a view definition — filter tree, sorts — is a body (querying). This one has no filter: theversionalready restricts it to published cards; - pages are keyset cursors: loop until
nextCursorisnull. There is no page number to compute. The loop calls apage()function rather thancms.POSTinline: inline, TypeScript cannot infer the type ofcursorand stops on TS7022; - the published version is a read option, not a status. A card's status
(
To do,In progress…) is about the team's work; whether it is online is its publication. Moving a card on a board does not take it offline.
Types and defaults
ViewDefinition is typed from the response side of the spec, where fields that
have a default are required: write sort and includeSecondaryLists out, or
the file does not compile.
3. Server routes and pages
The pages never see the token: they call two routes of the site itself, and only those routes call Spunto.
export default defineEventHandler(async () => {
const rows = await listPublished()
return rows.map((row) => ({
slug: slugOf(row),
title: row.title,
icon: row.icon ?? null,
publishedOn: (row.properties.published_on as string | undefined) ?? null,
}))
})export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, "slug")
const row = (await listPublished()).find((item) => slugOf(item) === slug)
if (!row) throw createError({ statusCode: 404, statusMessage: "Post not found" })
const post = await getPost(row.id)
return {
title: post.title,
icon: post.icon ?? null,
publishedOn: (post.properties.published_on as string | undefined) ?? null,
tags: (post.properties.tags as string[] | undefined) ?? [],
blocks: post.blocks.blocks,
mentions: post.mentions ?? [],
}
})A post is found by its slug in the cached list, so an unpublished slug is a
404 without a request to Spunto. Property values are read by their key
(slug, published_on, tags) in properties; a filter, should you add one,
names a property by its fieldId instead. Mixing the two is the classic
400 (limits).
<script setup lang="ts">
const { data: posts } = await useFetch("/api/posts")
useHead({ title: "Blog" })
</script>
<template>
<main>
<h1>Blog</h1>
<ul>
<li v-for="post in posts" :key="post.slug">
<NuxtLink :to="`/blog/${post.slug}`">{{ post.icon }} {{ post.title }}</NuxtLink>
</li>
</ul>
</main>
</template><script setup lang="ts">
import { tree } from "#shared/blocks"
const route = useRoute()
const { data: post, error } = await useFetch(`/api/posts/${route.params.slug}`)
if (error.value) {
throw createError({ statusCode: error.value.statusCode ?? 500, statusMessage: error.value.statusMessage, fatal: true })
}
useHead({ title: () => post.value?.title })
</script>
<template>
<article v-if="post">
<h1>{{ post.icon }} {{ post.title }}</h1>
<time v-if="post.publishedOn" :datetime="post.publishedOn">{{ post.publishedOn }}</time>
<Blocks :nodes="tree(post.blocks)" :mentions="post.mentions" />
</article>
</template>useFetch is typed from the route it calls: post.title is checked against
what [slug].get.ts returns, which is itself checked against the generated
spec. During server rendering the call does not leave the process; after
hydration, a NuxtLink fetches the same route over HTTP. fatal: true is what
shows the error page on a client-side navigation too, not only on the first
render.
4. Render the body
A body is a flat list of typed blocks, and a block's text is a list of
spans — a string plus marks (page bodies).
The format cannot carry HTML, so there is nothing to sanitise: the components
below build elements, and there is no v-html anywhere.
Two things need grouping first — consecutive list items become one list, and a
toggle owns the blocks that follow it with a greater indent. The helper lives
in shared/, next to the types:
import type { components } from "./spunto-api"
export type Block = components["schemas"]["Block"]
export type Span = NonNullable<Block["text"]>[number]
export type Mention = components["schemas"]["MentionedItem"]
export type Node =
| { kind: "list"; ordered: boolean; items: Block[] }
| { kind: "toggle"; block: Block; children: Node[] }
| { kind: "block"; block: Block }
export function tree(blocks: Block[]): Node[] {
const out: Node[] = []
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i]!
if (block.type === "toggle") {
let end = i + 1
while (end < blocks.length && blocks[end]!.indent > block.indent) end++
out.push({ kind: "toggle", block, children: tree(blocks.slice(i + 1, end)) })
i = end - 1
} else if (block.type === "bulleted" || block.type === "numbered") {
const items: Block[] = []
while (blocks[i]?.type === block.type) items.push(blocks[i++]!)
i--
out.push({ kind: "list", ordered: block.type === "numbered", items })
} else {
out.push({ kind: "block", block })
}
}
return out
}
// Outermost first: <a><s><em><strong><code>text…
export const MARKS = ["link", "strike", "italic", "bold", "code"] as const
export type Mark = (typeof MARKS)[number]The ! after blocks[i] are there because Nuxt's generated tsconfig turns
on noUncheckedIndexedAccess.
Marks nest — a bold link is <a><strong>…</strong></a> — so a span is rendered
by a component that wraps one mark per level and calls itself for the rest. A
Vue single-file component can use itself by its file name:
<script setup lang="ts">
import type { Mark, Span } from "#shared/blocks"
// One mark per level, then the same component for the rest.
const props = defineProps<{ span: Span; marks: Mark[] }>()
const TAGS = { link: "a", strike: "s", italic: "em", bold: "strong", code: "code" } as const
const mark = computed(() => props.marks[0])
</script>
<template>
<template v-if="!mark">{{ span.text }}</template>
<component :is="TAGS[mark]" v-else :href="mark === 'link' ? span.link : undefined">
<BlockMarks :span="span" :marks="marks.slice(1)" />
</component>
</template><script setup lang="ts">
import { MARKS, type Mention, type Span } from "#shared/blocks"
const props = defineProps<{ spans?: Span[]; mentions: Mention[] }>()
// A mention: the API resolves it in `mentions`. Missing (deleted,
// unpublished) → something neutral, never the title the span remembers.
function mentioned(id: string) {
const card = props.mentions.find((m) => m.id === id)
return card ? `${card.key} ${card.title}` : "unavailable card"
}
</script>
<template>
<template v-for="(span, i) in spans ?? []" :key="i">
<span v-if="span.mention" class="mention">{{ mentioned(span.mention) }}</span>
<BlockMarks v-else :span="span" :marks="MARKS.filter((mark) => span[mark])" />
</template>
</template><script setup lang="ts">
import type { Mention, Node } from "#shared/blocks"
defineProps<{ nodes: Node[]; mentions: Mention[] }>()
const headings = ["h2", "h3", "h4"] as const
const hostname = (url: string) => new URL(url).hostname
</script>
<template>
<template v-for="(node, i) in nodes" :key="i">
<component :is="node.ordered ? 'ol' : 'ul'" v-if="node.kind === 'list'">
<li v-for="item in node.items" :key="item.id">
<BlockText :spans="item.text" :mentions="mentions" />
</li>
</component>
<details v-else-if="node.kind === 'toggle'">
<summary><BlockText :spans="node.block.text" :mentions="mentions" /></summary>
<Blocks :nodes="node.children" :mentions="mentions" />
</details>
<component :is="headings[(node.block.level ?? 1) - 1]" v-else-if="node.block.type === 'heading'">
<BlockText :spans="node.block.text" :mentions="mentions" />
</component>
<p v-else-if="node.block.type === 'paragraph'">
<BlockText :spans="node.block.text" :mentions="mentions" />
</p>
<blockquote v-else-if="node.block.type === 'quote'">
<BlockText :spans="node.block.text" :mentions="mentions" />
</blockquote>
<aside v-else-if="node.block.type === 'callout'">
<BlockText :spans="node.block.text" :mentions="mentions" />
</aside>
<p v-else-if="node.block.type === 'todo'">
<input type="checkbox" :checked="!!node.block.checked" disabled>
<BlockText :spans="node.block.text" :mentions="mentions" />
</p>
<pre v-else-if="node.block.type === 'code'"><code :data-language="node.block.language">{{ node.block.code }}</code></pre>
<hr v-else-if="node.block.type === 'divider'">
<img v-else-if="node.block.type === 'image'" :src="`/cms-files/${node.block.fileId}`" :alt="node.block.alt ?? ''" loading="lazy">
<!-- `embedUrl` is rebuilt by the API from an allowlist: never use `url` here. -->
<iframe
v-else-if="node.block.type === 'embed'"
:src="node.block.embedUrl"
:title="node.block.provider"
loading="lazy"
sandbox="allow-scripts allow-same-origin allow-popups allow-presentation"
/>
<a v-else-if="node.block.type === 'bookmark'" class="bookmark" :href="node.block.url">
{{ node.block.title ?? hostname(node.block.url!) }}
</a>
<!-- A type this renderer doesn't know yet: its text if it has any.
`type` is an open string — a new block type won't break the page. -->
<p v-else-if="node.block.text">
<BlockText :spans="node.block.text" :mentions="mentions" />
</p>
</template>
</template>Headings start at h2 because the post title is the page's h1. hostname()
is a function of the component because a Vue template only sees a short list of
globals, and URL is not in it. Three things to keep when you adapt it:
- Always keep a last branch for unknown types.
Block.typeis an open string in responses: the API adds block types over time, and a site deployed today must render tomorrow's body — degraded, not broken. - An embed's iframe takes
embedUrl, neverurl. The API recomputes it on every write from an allowlist (YouTube, Vimeo, Loom, Figma, Google Docs, Sheets and Slides, CodeSandbox, CodePen);urlis the page a reader would open. - A mention is resolved by the API, not by you.
mentionscarries the current key and title of every card the body cites. Read withversion=published, a card that is not published is not in it: render something neutral, never the span'stext.
5. Serve the images
An image block carries a fileId, never a URL. Attachments have no public
address in Spunto: the API serves the bytes itself, behind the same bearer
token as everything else (files). So the site relays them
through a route of its own, which keeps the token on the server. Under
server/routes/ rather than server/api/, its address has no /api prefix:
export default defineEventHandler(async (event) => {
const response = await fileContent(getRouterParam(event, "fileId")!)
if (!response.ok) throw createError({ statusCode: 404 })
return new Response(response.body, {
headers: {
"content-type": response.headers.get("content-type") ?? "application/octet-stream",
"cache-control": "public, max-age=86400",
},
})
})A file id that is not in your workspace answers 404, like anything else that is not yours. Any file of the workspace is relayed, though, the images of drafts included: the ids are not listed anywhere public, but if that matters, check the id against the blocks of the published posts before relaying it.
The type served is not the type uploaded
Images and PDFs come back with their type. Anything outside that list — an SVG
included — is served as application/octet-stream, on purpose: an SVG is a
scriptable document.
6. Refresh on every publication
The routes of step 3 serve Nitro's cache for an hour. A webhook makes that hour end as soon as someone publishes:
import { createHmac, timingSafeEqual } from "node:crypto"
export default defineEventHandler(async (event) => {
const raw = (await readRawBody(event, "utf8")) ?? ""
const header = getHeader(event, "x-spunto-signature") ?? ""
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")))
const expected = createHmac("sha256", useRuntimeConfig(event).spuntoWebhookSecret)
.update(`${parts.t}.${raw}`)
.digest()
const given = Buffer.from(parts.v1 ?? "", "hex")
const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) < 300
if (!fresh || given.length !== expected.length || !timingSafeEqual(given, expected)) {
throw createError({ statusCode: 401, statusMessage: "invalid signature" })
}
await forgetContent()
setResponseStatus(event, 204)
return null
})Then, under Webhooks (/w/{workspaceId}/settings/webhooks, for an admin
of the workspace), add an endpoint:
- URL:
https://your-site.example/api/revalidate; - Subscription: Publications only —
item.publishedanditem.unpublished.
Its signing secret is shown once: put it in NUXT_SPUNTO_WEBHOOK_SECRET.
Not Cards (item.*): the editor saves a draft about once a second while
someone types, and every save is an item.updated. None of that changes what
the site shows. With publications only, the cache is emptied when someone
presses Publish or Unpublish, and at no other time.
- The signature is computed over the raw body, which is why the route reads
readRawBodyand notreadBody: a re-serialised JSON object is not the string that was signed. - The timestamp is inside the signature (
t.body), so a captured delivery cannot be replayed later — that is what the five-minute window checks. - A failed delivery is retried five times over about an hour and a quarter.
Until one gets through, the site serves what it had — for an hour at most,
the
maxAgeof step 2. - Each publication is one delivery. Publishing ten posts in a row empties the cache ten times, which costs ten re-reads of the list on the next visits, not ten builds.
forgetContent() throws away the whole blog: the list and every post read
since. That is the right default for a blog, and the simplest thing that is
never stale. A larger site can parse the payload ({ kind: "event", event }),
read event.resource.id, and remove only spunto:post:<id>.json and the list.
One process, one cache
Nitro's cache storage is in memory by default with the Node server: it
lives in the process that served the page. On one server, that is all there is
to it. With several instances, or on serverless functions, each one has its
own, and the webhook only reaches one of them: mount cache on a shared
Nitro storage (Redis, a KV store)
in nitro.storage so that one call empties it for all.
This caches data rather than pages. Nuxt's routeRules can also cache whole
pages (swr, isr), but on Vercel or Netlify isr is kept by the host's CDN,
so emptying it goes through the host rather than through your code. Caching the
two functions that call Spunto keeps the invalidation in one route of your
site, and a page renders from the cache without a request to Spunto.
Already in Notion?
What changes when a site stops reading from the Notion API, point by point, is in Notion as a headless CMS. The import route and how to make it replayable are in imports you can run twice.
What this guide does not cover
- Previews of drafts. A key that can read a workspace can read its drafts:
a preview is the same routes without
version: "published", on a deployment only your team can open. - A fully static site.
nuxt generatewould need every image written as a file of the build, and a rebuild on each publication through your host's build hook — that is the shape of the Astro guide. - Search over published post bodies. Workspace search covers bodies, but it searches drafts, not the published version, and it is a members' tool rather than a visitor's. Build your own index, over what you publish, if your site needs one.
- Rate limits. There are none today, which is not a promise. The cache of step 2 keeps the request count low anyway.
Every route used here is in the API reference, generated from the same specification your types came from.
Astro headless CMS
Use Spunto CMS as the headless CMS of an Astro site — a content collection loaded over REST, typed from the public OpenAPI spec, block rendering in .astro components, images copied at build time, and a rebuild on every publication.
Notion as a headless CMS
What you run into when a website reads its content from the Notion API — rate limits, nested blocks, expiring file URLs, id-only webhooks — and how Spunto CMS handles each one.