Hooks for document changes to trigger custom logic and automation

7 replies
Last updated: Nov 29, 2025
Hey, does anyone know if there is a way to hook into document content changes and run custom logic before/after they happen? For example, if a boolean field is changed on one document, I'd like to detect that change in a hook that allows me to automate the creation of another type of document?
AI Update

Yes! Sanity provides exactly what you're looking for through Sanity Functions - a serverless compute environment that lets you hook into document content changes and run custom logic in response to those events.

How it works

Sanity Functions allow you to create event-driven workflows that react to document changes (create, update, delete, publish, etc.). You can:

  1. Listen to specific events - React when documents are created, updated, deleted, or published
  2. Filter which documents trigger your function - Use GROQ queries to only run logic for specific document types or conditions
  3. Access full document context - Read and write to your dataset with full Sanity API access
  4. Automate document creation - Create new documents based on changes to other documents

Your use case: Boolean field triggers new document creation

Here's how you'd implement your specific scenario:

Example: When a boolean field changes on a document, automatically create another document

// functions/auto-create-doc/index.ts
import { type DocumentEventHandler } from "@sanity/functions";
import { createClient } from "@sanity/client";

interface MyDocData {
  _id: string;
  myBooleanField: boolean;
}

export const handler: DocumentEventHandler<MyDocData> = async ({
  context,
  event,
}) => {
  const client = createClient({
    ...context.clientOptions,
    apiVersion: "2025-01-01",
  });

  // Check if the boolean field was changed to true
  if (event.data.myBooleanField === true) {
    // Create a new document of another type
    await client.create({
      _type: 'anotherDocumentType',
      title: `Auto-created from ${event.data._id}`,
      sourceDocument: {
        _type: 'reference',
        _ref: event.data._id
      },
      createdAt: new Date().toISOString()
    });
    
    console.log(`Created new document triggered by ${event.data._id}`);
  }
};

Configure your function in blueprint.json:

{
  "blueprintVersion": "2024-10-01",
  "resources": [
    {
      "displayName": "auto-create-on-boolean-change",
      "name": "auto-create-doc",
      "src": "functions/auto-create-doc",
      "type": "sanity.function.document",
      "event": {
        "on": ["update", "publish"],
        "filter": "_type == 'myDocType' && defined(myBooleanField)",
        "projection": "{_id, myBooleanField}"
      }
    }
  ]
}

Getting started

  1. Initialize a Blueprint (Sanity's infrastructure-as-code config):

    npx sanity@latest blueprints init
  2. Add a function:

    npx sanity@latest blueprints add function
  3. Deploy:

    npx sanity@latest blueprints deploy

Why Functions over Webhooks?

While webhooks are also available, Sanity Functions are the modern, recommended approach because they:

  • Run natively within Sanity (no external hosting needed)
  • Have built-in access to your Sanity client and dataset
  • Scale automatically
  • Are easier to set up and maintain
  • Have better security (no need to expose public endpoints)

Check out the complete guide in the blog post and official documentation for more details!

Show original thread
7 replies

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?