@gluhar/sanity
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.
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&slug | the routed document; null → 404, a failed read throws → 503 |
GET /api/globals | globalsQuery + pageSlugsByUid, one read |
POST /api/revalidate | the Sanity webhook (below) |
/api/__sitemap__/urls | added 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/sanity | perspective: "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 edge | bypassToken; noindex on non-indexable builds, isr.noindex paths and _payload.json (plus in-function, where @nuxtjs/robots would replace it); 308 for trailing slashes |
| Composables | useSinglePage<T>(), useGlobals<T>(), contentRoutes (also on the server) |
| Server utils | getPage, getGlobals, fetchPublished, fetchDrafts, fetchContentPaths, isPreviewRequest, hasPreviewSession |
| Build guards | VERCEL_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:normallargeh2h3h4blockquoteulollistrongemunderlinestrike-throughhighlightlinkfigureimgfigcaptionvideoembedtablethtd.components:@portabletext/vuecomponents merged over the defaults, per key.image-sizes: thesizesattribute for images (default100vw).
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