# Nuxt (/docs/getting-started/nuxt)

This sets up a Nuxt site that serves every page entry at its path, shows drafts in the canvas, and lets editors sign in on the site to change it. It uses Nuxt 4's folders: the Vue side in `app/`, the server side in `server/`.

## 1. Start the repository on a space [#1-start-the-repository-on-a-space]

Create a **management token** under **Settings → API tokens**, then run in the site's root:

```sh
export CONTENT_MANAGEMENT_TOKEN=cms_m_…
npx @obelism/content init
```

`init` writes the model file (`content/content-model.json`), an example of what the delivery API answers for every content type (`content/examples/`), installs `@obelism/content`, and adds the token variables to `.env.example`. Add `@obelism/content-vue` for the Vue helpers:

```sh
npm i @obelism/content-vue
```

The tokens stay on the server, in Nuxt's private runtime config:

```ts title="nuxt.config.ts"
export default defineNuxtConfig({
	runtimeConfig: {
		contentDeliveryToken: '',
		// The space and environment it reads (Space settings), so the canvas's
		// token for another space reads nothing here.
		contentSpaceId: '',
		contentEnvironment: 'production',
	},
	routeRules: {
		// Let the CMS frame the site.
		'/**': {
			headers: {
				'Content-Security-Policy':
					"frame-ancestors 'self' https://content.obelism.studio",
			},
		},
	},
})
```

Nuxt fills them from `NUXT_`-prefixed variables. Put them in `.env` (never commit it):

```sh
NUXT_CONTENT_DELIVERY_TOKEN=cms_d_…
NUXT_CONTENT_SPACE_ID=space_…
NUXT_CONTENT_ENVIRONMENT=production
```

## 2. The clients [#2-the-clients]

One client for published content. Drafts come with a token for the person editing: in the canvas the page's URL carries `cms_token`, and an editor [signed in on the site](/docs/guides/site-editing) has a site token in a cookie. Those requests get a client of their own. [Previews and draft mode](/docs/guides/preview) explains the order and why.

```ts title="server/utils/content.ts"
import { ContentClient, readPreviewParams } from '@obelism/content'
import { readSiteToken } from '@obelism/content/site'
import type { H3Event } from 'h3'

let delivery: ContentClient | undefined

export const getDelivery = (event: H3Event) =>
	(delivery ??= new ContentClient({
		token: useRuntimeConfig(event).contentDeliveryToken,
	}))

// Naming the space and environment makes a token someone made for another
// space read nothing here.
const drafts = (event: H3Event, token: string) => {
	const config = useRuntimeConfig(event)
	return new ContentClient({
		token,
		space: config.contentSpaceId,
		environment: config.contentEnvironment,
		init: { cache: 'no-store' },
	})
}

// `cms_preview` alone proves nothing: anyone can add it to a URL.
export const getContent = (event: H3Event) => {
	const preview = readPreviewParams(getRequestURL(event).searchParams)
	if (preview?.token) return drafts(event, preview.token)
	const token = readSiteToken(getRequestHeader(event, 'cookie'))
	if (token) return drafts(event, token)
	return getDelivery(event)
}
```

Nuxt imports `server/utils` in every server route on its own.

## 3. Every page by path [#3-every-page-by-path]

A server route reads the page, so the tokens never reach the browser:

```ts title="server/api/pages/[...path].get.ts"
import { ContentApiError } from '@obelism/content'

import type { PageEntry } from '~~/shared/types/content'

export default defineEventHandler(async (event) => {
	const path = getRouterParam(event, 'path') || 'home'

	const entry = await getContent(event)
		.getPage<PageEntry>(path, { depth: 2 })
		.catch((error: unknown) => {
			// A made-up, expired or other space's `cms_token`: show what's published.
			if (error instanceof ContentApiError && error.status === 401) {
				// Says why, when the canvas shows published content (guides/canvas).
				console.warn('Content refused the draft token:', error.body)
				return getDelivery(event).getPage<PageEntry>(path, { depth: 2 })
			}
			throw error
		})
	if (!entry) throw createError({ statusCode: 404 })

	return entry
})
```

The page passes its own query along, which carries `cms_token` in the canvas:

```vue title="app/pages/[...slug].vue"
<script setup lang="ts">
import type { PageEntry } from '~~/shared/types/content'

const route = useRoute()
const path = computed(
	() => (route.params.slug as string[] | undefined)?.join('/') || 'home',
)

const { data: entry } = await useFetch<PageEntry>(
	() => `/api/pages/${path.value}`,
	{ query: computed(() => route.query) },
)
if (!entry.value) {
	throw createError({ statusCode: 404, statusMessage: 'Page not found', fatal: true })
}
</script>

<template>
	<ContentPage v-if="entry" :entry="entry" />
</template>
```

## 4. Render the entry [#4-render-the-entry]

`useLiveEntry` returns the editor's unsaved version while the page is open in the canvas, and the entry everywhere else. `editable` marks the entry and its blocks, so editors can click them.

```ts title="shared/types/content.ts"
import type { Block, Entry, RichTextNode } from '@obelism/content-vue'

type HeroBlock = Block<{ heading: string | null }, 'hero'>
type TextBlock = Block<{ text: RichTextNode | null }, 'text'>

export type PageEntry = Entry<
	{ title: string | null; body: (HeroBlock | TextBlock)[] | null },
	'page'
>
```

```vue title="app/components/ContentPage.vue"
<script setup lang="ts">
import { editable, RichText, useLiveEntry } from '@obelism/content-vue'

import type { PageEntry } from '~~/shared/types/content'

const props = defineProps<{ entry: PageEntry }>()
const live = useLiveEntry(() => props.entry)
</script>

<template>
	<main v-bind="editable(live)">
		<h1>{{ live.fields.title }}</h1>
		<template v-for="block in live.fields.body ?? []" :key="block._uid">
			<section v-if="block._type === 'hero'" v-bind="editable(block)">
				<h2>{{ block.heading }}</h2>
			</section>
			<section v-else v-bind="editable(block)">
				<RichText :document="block.text" />
			</section>
		</template>
	</main>
</template>
```

The types in `content/examples/` show what each of your content types looks like; adjust `PageEntry` to your own model.

## 5. Start the bridge [#5-start-the-bridge]

```vue title="app/app.vue"
<script setup lang="ts">
import { ContentBridge } from '@obelism/content-vue'
</script>

<template>
	<ContentBridge />
	<NuxtPage />
</template>
```

It does nothing outside the editor. The `frame-ancestors` header from step 1 lets the CMS frame the site; drop `X-Frame-Options: DENY` if anything sets it.

Then set the environment's **preview URL** (Settings) to where the site runs, such as `http://localhost:3000`, and open the **Canvas** ([turned on](/docs/guides/canvas) under Preferences on www).

## 6. Editing on the site [#6-editing-on-the-site]

One server route signs editors in on the site itself, with the site token in an httpOnly cookie that `getContent` reads:

```ts title="server/routes/cms/[...path].ts"
import { createSiteEditing, type SiteEnvironment } from '@obelism/content/site'

let handler: ReturnType<typeof createSiteEditing> | undefined

export default defineEventHandler((event) => {
	const config = useRuntimeConfig(event)
	handler ??= createSiteEditing({
		spaceId: config.contentSpaceId,
		environment: config.contentEnvironment as SiteEnvironment,
	})
	return handler(toWebRequest(event))
})
```

Editors sign in at `/cms/login?return_to=/`. See [editing on the site](/docs/guides/site-editing) for what they get.

## Next steps [#next-steps]

- [Rebuild or revalidate on publish](/docs/guides/webhooks) with a webhook. Pages read Content on every request here; to cache them, cache published reads only, never a request with a draft token.
- `useContentBridgeEvent('published', () => refreshNuxtData())` refetches the page once the editor publishes. See the [Vue SDK](/docs/sdk/vue).
- [Images](/docs/api/images): resized and re-encoded copies with a query on the URL.
- [A/B tests in Content](/docs/guides/ab-tests), with Obelism Improve.
- [Click rates](/docs/guides/canvas#click-rates) on each block in the canvas: load Obelism Numbers' script and add `data-numbers-id={block._uid}` next to `editable(block)`.
