@gluhar/sanity

中文文档
6.4.1发布于 2026/11/16MITTypeScriptES Module近 30 天下载 3060

Gluhar Sanity package. Configures @nuxtjs/sanity under the hood. Provides composables, etc. Depends on @gluhar/i18n for localization of fields.

原始使用文档
文档目录6 节
  1. Installation
  2. Sanity Config
  3. Usage
  4. ISR, preview and visual editing ( isr )
  5. Rich text
  6. Contribution

@gluhar/sanity

npm version npm downloads License Nuxt

Gluhar Sanity package. Configures @nuxtjs/sanity under the hood. Provides composables, etc.

Depends on @gluhar/i18n for localization of fields, so you need to install and configure @gluhar/i18n in order to use the sanity module.

✨  Release Notes

Installation

Install the module to your Nuxt application with one command:

npx nuxi module add @gluhar/sanity

Sanity Config

In your /config folder create a sanity.config.ts to configure the gluhar module and @nuxtjs/sanity used behind-the-scenes.

Update id to point to your project and apiVersion to today's date.

export default {
  projectId: "8m33196t",
  apiVersion: "2024-04-01",
  dataset: "production",
};

The package automatically loads this file and does the rest. If you need more custom config you can use the module key gluharSanity.

Usage

You can import multiple types from @gluhar/sanity/types such as SanityDocument, SanityImage, SanityPage.

Most frequently used queries are provided from @gluhar/sanity/query like imageWithAsset

ISR, preview and visual editing (isr)

On-demand ISR on Vercel with Sanity preview, lifted from optic-com (production-checked) and cosmosthrace. Turn it on with a content registry and two queries:

// nuxt.config.ts
gluhar: {
  sanity: {
    isr: { noindex: ["/internal/**"] }, // or `isr: true`
  },
},
// config/content.config.ts — shared with the Studio, plain data only
import { defineContentRegistry } from "@gluhar/routes";

export default defineContentRegistry({
  types: [
    { type: "page", homeSlug: "/" },
    { type: "article", prefix: "news", prefixUid: "news" },
  ],
  aggregators: ["/", "/news"],
  globalTypes: ["header", "footer", "settings", "defaultSeo"],
  appPaths: ["/login"],
});
// groq/index.ts
export const queryForType = (type: ContentDocumentType) => QUERY_BY_TYPE[type]; // $slug param
export const globalsQuery = groq`{ "header": *[_id == "header"][0]{ ... }, ... }`;
<!-- app.vue -->
<script setup lang="ts">
const { data: globals } = await useGlobals<Globals>();
</script>

<!-- pages/[...slug].vue -->
<script setup lang="ts">
const { page, status, upstreamFailed } = await useSinglePage<Page | Article>();
</script>
<template>
  <NotFound v-if="!page && status !== 'pending'" :code="upstreamFailed ? 503 : 404" />
  <Sections v-else-if="page?._type === 'page'" :sections="page.sections" />
  <ArticleDetail v-else-if="page?._type === 'article'" :article="page" />
</template>

What it sets up:

Route rules (builds only)/** ISR 24h with allowQuery: []; /api/**, /preview/** uncached; /sitemap.xml ISR. Nothing prerendered
GET /api/page?type&slugthe routed document; null → 404, a failed read throws → 503
GET /api/globalsglobalsQuery + pageSlugsByUid, one read
POST /api/revalidatethe Sanity webhook (below)
/api/__sitemap__/urlsadded to sitemap.sources when @nuxtjs/sitemap is installed: registry types × locales with hreflang
Preview__prerender_bypass on /preview/enable after the secret validates; /preview/disable?redirect= limited to this site; drafts only with the validated sanity-preview-id cookie and ?preview=true
@nuxtjs/sanityperspective: "published" (enforced: "raw" + the server token serves drafts), useCdn: false, a drafts client with stega and a field filter, visualEditing.stega: false (enforced), in-place refresh on Studio edits
Vercel edgebypassToken; noindex on non-indexable builds, isr.noindex paths and _payload.json (plus in-function, where @nuxtjs/robots would replace it); 308 for trailing slashes
ComposablesuseSinglePage<T>(), useGlobals<T>(), contentRoutes (also on the server)
Server utilsgetPage, getGlobals, fetchPublished, fetchDrafts, fetchContentPaths, isPreviewRequest, hasPreviewSession
Build guardsVERCEL_BYPASS_TOKEN present and URL-safe, NUXT_SANITY_STUDIO_URL set and not a *.sanity.studio host (errors on Vercel, warnings elsewhere); empty prerender, payloadExtraction not false (errors everywhere)

Env: NUXT_SANITY_TOKEN (read token; drafts), NUXT_SANITY_STUDIO_URL (the Studio's resolved URL, https://www.sanity.io/@<org>/studio/<appId>), VERCEL_BYPASS_TOKEN (openssl rand -hex 16, needed at build), REVALIDATE_SECRET.

Options: registry (default config/content.config), queries (groq), expiration, noindex, indexable (default site.indexable, else VERCEL_ENV === "production"), stripTrailingSlash, concurrency, stega.logicFields / stega.nonTextFields (added to uid key slug current oldSlug / alt orderRank; any field with options.list is a logic field), and handlers.{page,globals,revalidate,sitemap,preview}: false to keep a project's own.

The webhook (Sanity → API → Webhooks), create / update / delete, drafts off, header x-revalidate-secret: <REVALIDATE_SECRET>:

filter:     _type in [<registry types>, <globalTypes>]
projection: { _type, "slug": slug.current, "oldSlug": before().slug.current }

A change purges the document's URL (and the one it vacated), the aggregators and the sitemap, in every locale, with each page's _payload.json. A global type or a slug change purges every route. Project rules go in a Nitro plugin:

// server/plugins/revalidate.ts
export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook("gluhar:revalidate", (ctx) => {
    if (ctx.doc._type === "promotion" && ctx.doc.accent) ctx.global = true; // add "accent" to the projection
    if (ctx.doc._type === "tvChannel") ctx.paths.add("/tv");
  });
});

None of this is active on the dev server (plain SSR), and none of it can be verified there: check a Vercel deployment (x-vercel-cache, preview from Presentation, a webhook delivery).

useSanityQueryWithPreview (and @gluhar/app's useSanityPage) are deprecated: they fetch in the browser and treat ?preview as preview.

Rich text

<RichText> renders the richtext / paragraphs types from @gluhar/studio. Pass the localised field as is (it calls l()), or a plain array:

<RichText
  :value="article.body"
  :classes="{
    normal: 'mt-5 fl-text-lg leading-relaxed',
    h2: 'mt-10 mb-4 fl-text-2xl font-extrabold',
    highlight: 'bg-amber-100',
    link: 'text-blue-700 underline',
  }"
  image-sizes="(min-width: 75rem) 50vw, 100vw"
/>
  • classes: utility classes per element. A key replaces its default, and "" removes it. Keys: normal large h2 h3 h4 blockquote ul ol li strong em underline strike-through highlight link figure img figcaption video embed table th td.
  • components: @portabletext/vue components merged over the defaults, per key.
  • image-sizes: the sizes attribute for images (default 100vw).

The GROQ needs no asset->: images and files are built from asset._ref.

Contribution

Local development
# Install dependencies
npm install

# Generate type stubs
npm run dev:prepare

# Develop with the playground
npm run dev

# Build the playground
npm run dev:build

# Run ESLint
npm run lint

# Run Vitest
npm run test
npm run test:watch

# Release new version
npm run release

版本与发布记录

@gluhar/sanity 共发布 44 个版本,首次发布于 2025/01/22;过去 12 个月发布了 28 个版本。

版本发布日期距今
6.4.1latest2026/11/16今天
6.4.02026/11/161 天前
6.3.22026/11/161 天前
6.3.12026/11/151 天前
6.3.02026/11/151 天前
6.2.02026/11/151 天前

其他发布通道:dev → 3.0.1-dev.2,next → 6.0.0-next.12。

关于 @gluhar/sanity 的常见问题

@gluhar/sanity 是什么?

Gluhar Sanity package. Configures @nuxtjs/sanity under the hood. Provides composables, etc. Depends on @gluhar/i18n for localization of fields.

如何安装 @gluhar/sanity?

在项目目录运行 npm install @gluhar/sanity,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:nuxt(^4.6.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gluhar/sanity 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gluhar/sanity 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gluhar/sanity 可以商用吗?

@gluhar/sanity 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gluhar/sanity 的下载量有多少?

根据 npm 官方下载统计,@gluhar/sanity 在 2026/10/17 – 2026/11/15 这 30 天内被下载 3,060 次,日均约 102 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gluhar/sanity 还在维护吗?

最新版本 6.4.1 发布于 2026/11/16(今天);至今共发布 44 个版本,其中过去 12 个月发布了 28 个;首次发布于 2025/01/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。