@farm.js/sanity

中文文档
0.1.48发布于 2026/11/01MITTypeScriptES Module

Sanity CMS integration for Farm.js

原始使用文档
文档目录8 节
  1. Install
  2. Configure
  3. Read content
  4. Invalidate on publish
  5. Read through the API, not the CDN
  6. Multiple server instances
  7. Options
  8. Bring your own client

@farm.js/sanity

Sanity CMS integration for Farm.js applications. It resolves the Sanity client configuration, validates it at startup, and receives Sanity webhooks so cached content is invalidated the moment an editor publishes.

See Stability and Support for what this package guarantees.

Install

pnpm add @farm.js/sanity @sanity/client

@sanity/client is a peer dependency so the application and the integration share one client.

Configure

import { defineConfig } from "@farm.js/core";
import { sanity } from "@farm.js/sanity";

export default defineConfig({
  integrations: {
    cms: sanity(),
  },
});

With no options, values come from the environment:

VariablePurpose
SANITY_PROJECT_IDProject id. SANITY_STUDIO_PROJECT_ID is also read.
SANITY_DATASETDataset. SANITY_STUDIO_DATASET is also read.
SANITY_API_VERSIONOptional. SANITY_STUDIO_API_VERSION is also read. Defaults to a pinned date.
SANITY_API_READ_TOKENOptional. A Viewer token, needed for private datasets and drafts.
SANITY_WEBHOOK_SECRETRequired once a webhook is configured.

A missing project id or dataset fails at startup rather than at the first request.

Note that a dataset which needs a token returns an empty result to an unauthenticated query, with no error. If content is missing, check the token before anything else.

Read content

The application owns the client. Build it once, use it directly, and hand the same object to the integration so Farm does not construct a second one.

// src/lib/cms.server.ts
import { createSanityClient, resolveSanityConfig } from "@farm.js/sanity";

export const cms = createSanityClient(resolveSanityConfig({ useCdn: false }));
// farm.config.ts
integrations: {
  cms: sanity({ instance: cms }),
}

Wrap queries in createServerQuery so results are cached and can be invalidated by key.

import { createServerQuery } from "@farm.js/core";
import { cms } from "./cms.server";

export const postsQuery = createServerQuery({
  key: () => ["sanity", "post", "list"],
  staleTime: "5m",
  handler: () =>
    cms.fetch(`*[_type == "post"] | order(publishedAt desc) { title, "slug": slug.current }`),
});

Invalidate on publish

Sanity can call your application when a document changes. The integration verifies the request came from Sanity, then asks the application which cache entries the change affects.

sanity({
  instance: cms,
  webhook: {
    onChange(payload) {
      if (payload._type !== "post") return;
      const slug = payload.slug as string;
      return {
        keys: [
          ["sanity", "post", "list"],
          ["sanity", "post", slug],
        ],
        paths: ["/posts", `/posts/${slug}`],
      };
    },
  },
});

keys are server query keys. paths are route paths whose rendered output should be revalidated as well. Return nothing for changes that affect no cached content.

In Sanity, create a webhook under API > Webhooks:

  • URL: https://your-app.example/api/sanity/webhook
  • Trigger on create, update and delete
  • Projection: { _id, _type, "slug": slug.current }
  • Secret: the value of SANITY_WEBHOOK_SECRET

The payload passed to onChange is whatever the projection returns, so include the fields the mapping needs. A document referenced by others can list them, for example "slugs": *[_type == "post" && references(^._id)].slug.current.

Responses follow what Sanity does next: 401 for a bad signature and 400 for a malformed body are not retried, and a 500 from a failing onChange is retried.

Read through the API, not the CDN

Set useCdn: false on the client when the webhook drives invalidation. The webhook fires before Sanity's CDN has updated, so a refetch through the CDN can return the previous content and cache it again for the full staleTime. Farm's cache is the cache in this setup; a second one in front of it only adds that race.

Leave the CDN on for applications that rely on staleTime alone, or for browser side reads.

Multiple server instances

Farm's data cache lives in memory per process unless a distributed adapter is configured. On a serverless platform the webhook reaches one instance and clears only that instance's memory. Use an adapter such as @farm.js/cache-redis so an invalidation reaches every instance.

Options

OptionDefaultNotes
projectIdenv
datasetenv
apiVersionpinned dateExported as DEFAULT_SANITY_API_VERSION.
tokenenvServer only. Never passed to the browser.
useCdntrueSet false with webhook invalidation.
instanceExisting SanityClient. Skips credential validation.
webhook.secretenv
webhook.path/api/sanity/webhook
webhook.onChangeMaps a payload to { keys?, paths? }.
logIntegration lifecycle logger.

Bring your own client

Pass a configured client through instance for options the integration does not expose. The integration uses that object as is.

import { createClient } from "@sanity/client";

sanity({ instance: createClient({ projectId, dataset, apiVersion, perspective: "published" }) });

版本与发布记录

@farm.js/sanity 共发布 61 个版本,首次发布于 2026/09/25;过去 12 个月发布了 61 个版本。

版本发布日期距今
0.1.48latest2026/11/012 天前
0.1.472026/10/313 天前
0.1.462026/10/313 天前
0.1.452026/10/313 天前
0.1.442026/10/313 天前
0.1.432026/10/304 天前

其他发布通道:beta → 0.1.3-beta.0。

关于 @farm.js/sanity 的常见问题

@farm.js/sanity 是什么?

为Farm.js集成的Sanity CMS

如何安装 @farm.js/sanity?

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

@farm.js/sanity 支持 TypeScript 吗?

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

@farm.js/sanity 支持 ESM 还是 CommonJS?

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

@farm.js/sanity 可以商用吗?

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

@farm.js/sanity 还在维护吗?

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