How to patch Sanity draft documents when syncing from external API?
_idchanging to
drafts.xxxxxwhen there's a draft, so the patch I'm trying to run on the document doesn't do anything, as it's being patched to the regular
_id, not the temporary draft
_id. My question is, what's the best way to patch to a draft? Is it possible? I've looked high and low through the docs but I just can't see it mentioned. Below is the sync function for reference. Thanks very much for taking the time to read this.
Yes, you can patch a draft. A draft is its own document with the ID drafts.<id>, and you patch it by that ID like any other document. The reliable way to sync is to check which of the published document and the draft exist, then patch every one that does, in a single transaction. Patch both because publishing writes the draft's contents onto the published document. If you update only the published document, an editor's next publish overwrites your synced values with the stale draft. If you update only the draft, the change isn't live until someone publishes.
Why patching blindly doesn't work
- The published document (
my-id) and the draft (drafts.my-id) are separate documents that share an identifier. Each write targets one specific ID. Documents in a release also exist asversions.<release-id>.my-id(Actions API guide). - A patch fails if the target document doesn't exist (Mutation API reference). So you can't just patch
drafts.my-idevery time and hope it's a no-op. Find out first which documents exist. - Reading drafts needs an authenticated client. Your sync function already uses a write token, so it can see them.
Sync function pattern
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'YOUR_PROJECT_ID',
dataset: 'YOUR_DATASET',
apiVersion: '2025-12-15',
useCdn: false,
token: process.env.SANITY_API_WRITE_TOKEN, // keep server-side
})
export async function syncCategory(externalCategory) {
const id = `category-${externalCategory.id}`
const draftId = `drafts.${id}`
// Only the fields owned by the external portal.
// Fields edited in Studio (e.g. description) are left alone.
const fields = {
title: externalCategory.name,
externalId: externalCategory.id,
}
// Which of the two documents exist right now?
const existingIds = await client.fetch(
'*[_id in [$id, $draftId]]._id',
{id, draftId}
)
if (existingIds.length === 0) {
// New category: create the published document
await client.createIfNotExists({_id: id, _type: 'category', ...fields})
return
}
// Patch every existing copy atomically
const tx = existingIds.reduce(
(t, docId) => t.patch(docId, (p) => p.set(fields)),
client.transaction()
)
await tx.commit()
}Notes:
- Use
.set()only for the fields that come from the portal. Don't usecreateOrReplace()on documents that already exist: it replaces the whole document and removes any fields you didn't include, such as the description editors add in Studio (client mutations docs). - Transactions are all-or-nothing, so the published document and the draft can't end up out of sync with each other (transactions docs).
- To guard against an editor saving between your fetch and your commit, you can add
.ifRevisionId(rev)to a patch. It then fails instead of overwriting newer changes. - For deletes, remove both IDs, for example
client.transaction().delete(id).delete(draftId). A delete counts as successful even when the document doesn't exist (Mutation API reference).
Alternative: patch by query in one request
The Mutation API also accepts a GROQ query in place of an ID, and only patches the documents that match (mutation patterns):
const {dataset} = client.config()
await client.request({
uri: `/data/mutate/${dataset}`,
method: 'POST',
body: {
mutations: [
{
patch: {
query: '*[_id in [$id, $draftId]]',
params: {id, draftId},
set: fields,
},
},
],
},
})Other things to know
- The Content Lake doesn't check API writes against your Studio validation rules. Your sync code is responsible for writing valid data (client mutations docs).
- If you use Content Releases, a category might also have
versions.<release-id>.<id>copies. Decide whether your sync should update those too. If it should, include their IDs when you look up which documents exist. - Keep your external webhook (for example your Netlify function) as the trigger. Sanity Functions run on content changes inside Sanity, on a schedule, or when another function calls them. They don't receive events from an outside portal, though a scheduled function could poll the portal instead.
Show original thread13 replies
Was this answer helpful?
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.