# Sanity

Publish Sanity documents as docs.

`@vuesho/sanity` publishes the documents in a [Sanity](https://www.sanity.io) Studio. The server reads them while the site runs, and the Studio can preview its drafts on the site.

## Setup [#setup]

### Install the Packages [#install-the-packages-step]

```npm
npm i @vuesho/sanity @sanity/client
```

### Add the Schema to the Studio [#add-the-schema-to-the-studio-step]

In your Studio's project, install `@vuesho/sanity` and `@sanity/code-input`:

```npm
npm i @vuesho/sanity @sanity/code-input
```

Add `schemaTypes` to the Studio, with the pages' document type and their body's blocks:

```ts title="sanity.config.ts"
import { codeInput } from "@sanity/code-input";
import { defineConfig } from "sanity";
import { structureTool } from "sanity/structure";
import { schemaTypes } from "@vuesho/sanity/schema";

export default defineConfig({
  projectId: "...",
  dataset: "production",
  plugins: [structureTool(), codeInput()], // [!code highlight]
  schema: { types: schemaTypes }, // [!code highlight]
});
```

### Store the Credentials [#store-the-credentials-step]

Put the project ID, from [Sanity Manage](https://www.sanity.io/manage), and the dataset name in `.env`:

```ini title=".env"
SANITY_PROJECT_ID=...
SANITY_DATASET=production
```

### Connect the Source [#connect-the-source-step]

Connect the documents in the config:

```ts title="vuesho.config.ts"
import { createClient } from "@sanity/client";
import { createSanity, sanityPlugin } from "@vuesho/sanity";
import { createSite, recommendedPreset } from "vuesho/config";

const sanity = createSanity({
  client: createClient({
    projectId: process.env.SANITY_PROJECT_ID,
    dataset: process.env.SANITY_DATASET,
    apiVersion: "2025-02-19",
    useCdn: true,
  }),
  docType: "docs",
});

export default createSite(sanity.source({ staleTime: 60_000 })).plugins(
  recommendedPreset(),
  sanityPlugin(), // [!code highlight]
);
```

To use the Sanity pages next to the Markdown in `content/`, give their source a `baseDir`, as in [Multiple Collections](/markdown/collections#multiple-collections):

```ts title="vuesho.config.ts"
createSite({
  docs: docs.toSource(),
  sanity: sanity.source({ baseDir: "sanity", staleTime: 60_000 }), // [!code highlight]
}).plugins(recommendedPreset(), sanityPlugin());
```

## Pages [#pages]

Each document of the `docType` type is a page of the site, with its last update date, in search and `llms.txt` like your other pages. Its `slug` sets its URL, where a `/` makes a folder.

`@vuesho/sanity/schema` has the `docs` document type, with a title, a slug, a description and a body, and blocks that render with Vuesho's components: callouts, cards, tabs, accordions, steps, file trees, code blocks highlighted with your [code themes](/markdown/code-blocks), and images from Sanity's CDN.

### Page Data and URLs [#page-data-and-urls]

`page.data` has a document's `title` and `description`, and `data` adds other fields, which the browser receives as JSON. `generatePath` replaces the default path, the slug with `.md`:

```ts title="vuesho.config.ts"
sanity.source({
  data: (document) => ({
    tags: Array.isArray(document.tags) ? document.tags : [],
  }),
  generatePath: (document) => `${document.slug?.current ?? document._id}.md`,
});
```

## Custom Blocks [#custom-blocks]

To add or replace block types, set the [theme's](/theme#views-and-page-bodies) `sanity` body to a component that passes Portable Text `components` to `SanityBody`:

```ts title="src/theme.ts"
import { defineTheme } from "vuesho/theme";
import defaultTheme from "vuesho/theme/default";
import type app from "../vuesho.config";

export default defineTheme<typeof app>({
  extends: defaultTheme,
  bodies: { sanity: () => import("./SanityBody.vue") }, // [!code highlight]
});
```

```vue title="src/SanityBody.vue"
<script setup lang="ts">
import type { SanityBodyProps } from "@vuesho/sanity";
import { SanityBody } from "@vuesho/sanity/theme";
import Video from "./Video.vue";

const props = defineProps<SanityBodyProps>();
</script>

<template>
  <SanityBody v-bind="props" :components="{ types: { video: Video } }" />
</template>
```

To type a block's props, install `@portabletext/vue` and use its `PortableTextComponentProps`:

```npm
npm i @portabletext/vue
```

```vue title="src/Video.vue"
<script setup lang="ts">
import type { PortableTextComponentProps } from "@portabletext/vue";

defineProps<PortableTextComponentProps<{ url: string }>>();
</script>

<template>
  <video :src="value.url" controls />
</template>
```

## Previews [#previews]

The Studio's [Presentation tool](https://www.sanity.io/docs/visual-editing/configuring-the-presentation-tool) shows your drafts on the deployed site.

### Create a Read Token [#create-a-read-token-step]

Create a token with the Viewer role in the project's API settings, and put it in `.env`. The build reads it too:

```ini title=".env"
SANITY_API_READ_TOKEN=sk...
```

### Turn On Previews [#turn-on-previews-step]

Pass the token to `createSanity()`'s `preview`:

```ts title="vuesho.config.ts"
const token = process.env.SANITY_API_READ_TOKEN; // [!code ++]

const sanity = createSanity({
  client: createClient({/* ... */}),
  docType: "docs",
  preview: token ? { token } : undefined, // [!code ++]
});
```

### Add the Presentation Tool [#add-the-presentation-tool-step]

In the Studio, set `presentationTool` to open `/api/sanity/preview`, after the site's [base path](/deploying#base-path) if it has one:

```ts title="sanity.config.ts"
import { codeInput } from "@sanity/code-input";
import { defineConfig } from "sanity";
import { presentationTool } from "sanity/presentation";
import { structureTool } from "sanity/structure";
import { schemaTypes } from "@vuesho/sanity/schema";

export default defineConfig({
  projectId: "...",
  dataset: "production",
  plugins: [
    structureTool(),
    codeInput(),
    // [!code ++:6]
    presentationTool({
      previewUrl: {
        initial: "https://docs.example.com",
        previewMode: { enable: "/api/sanity/preview" },
      },
    }),
  ],
  schema: { types: schemaTypes },
});
```

`/api/sanity/preview` sets a cookie that shows the drafts to that browser. The drafts update as the Studio edits them. The preview ends when the browser closes, when the token changes, or at `/api/sanity/preview/disable`. Readers without the cookie see the published documents.

With previews, every page renders on request, for every reader, since a preview is an [audience](/dynamic-rendering#audiences). With a Nitro `cache` route rule, list `vuesho-sanity-preview` in its `allowCookies`, as [CDNs](/dynamic-rendering#cdns) shows.

## Refreshing Content [#refreshing-content]

The server reads the documents again once `staleTime` passes, or when a webhook calls `revalidateLoader()`, as in [Dynamic Rendering](/dynamic-rendering#refreshing-content).

`live: true` refreshes the open pages when a document is published, through the Sanity [Live Content API](https://www.sanity.io/docs/content-lake/live-content-api):

```ts title="vuesho.config.ts"
const sanity = createSanity({
  client: createClient({/* ... */}),
  docType: "docs",
  live: true, // [!code ++]
});
```

- Add your site's origin to the project's [CORS origins](https://www.sanity.io/docs/content-lake/cors), without credentials.
- On a serverless host with multiple instances, keep a short `staleTime`, since a live update refreshes only the instance that receives it, not the CDN.
- A preview updates live with or without `live`.

A static build queries Sanity once and prerenders every page. It fails with `preview` or `live`, which need a server.

## Options [#options]

### `createSanity()` [#createsanity]

### CreateSanityOptions

| Prop           | Type                                | Description                                                                                                                                                                                                                                                       |
| -------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `client`       | `SanityClient$1`                    | A client for the documents' project and dataset, like `createClient({ projectId, dataset, apiVersion, useCdn: true })` from `@sanity/client`.                                                                                                                     |
| `docType`      | `string`                            | The document type of the pages, like `docs`.                                                                                                                                                                                                                      |
| `preview?`     | `{ token: string; } \| undefined`   | Shows Sanity's drafts in your Studio's Presentation tool: its requests to `/api/sanity/preview` start a preview, which reads the Studio's perspective, like Sanity's drafts.                                                                                      |
| `live?`        | `boolean \| undefined`              | Updates the published pages readers have open when a document changes. Their browsers follow Sanity's Live Content API and ask the `/api/sanity/live` route to query the documents again. The site's origin must be one of the project's CORS origins.            |
| `highlighter?` | `false \| Highlighter \| undefined` | Highlights code blocks on the server with a highlighter from `vuesho/highlight`, like `createHighlights({ themes })`, instead of the site's. `false` renders plain code. Default: ``the site's highlighter, which `highlight` of `markdown` of the config gives`` |

### `sanity.source()` [#sanitysource]

### SanitySourceOptions

| Prop            | Type                                                        | Description                                                                                                                                                                                                                                              |
| --------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `baseDir?`      | `string \| undefined`                                       | The folder for the pages in the site's file tree, which sets their URLs.                                                                                                                                                                                 |
| `data?`         | `((document: SanityListedDocument) => {}) \| undefined`     | Gives more page data from its document, like its tags, merged over its title and description, for a layout to read from `page.data`. It's sent to the browser, so every value must be serializable.                                                      |
| `generatePath?` | `((document: SanityListedDocument) => string) \| undefined` | Gives a page's file path, which sets its URL. Default: `` its `slug`, with `.md` ``                                                                                                                                                                      |
| `staleTime?`    | `number \| undefined`                                       | How long the server keeps the pages it read, in milliseconds. The first request after that queries the documents again. With 0, every request queries them. A preview queries Sanity's drafts on each request. Default: `` until `revalidateLoader()` `` |
