How AI is powering better personalization in e-commerce [with Vercel]. Sign up now

Patch API: append to empty array fails, but prepend works

1 replyLast updated: Nov 30, 2025

I assume this is normal behavior, but I found that when trying to use the mutations API to patch (https://www.sanity.io/docs/http-patches#insertion-febxf6Fk ) a new reference into an array, the “append” does not work if the array is empty.
{
  "insert": {
    "after": "some.array[-1]",
    "items": ["a"]
  }
}
Prepend works on an empty array, though.

{
  "insert": {
    "before": "some.array[0]",
    "items": ["a"]
  }
}

AI Update

You're right to notice this behavior, and yes, it's expected! When you use insert with after: "some.array[-1]" on an empty array, it fails because there's no element at position [-1] (the last element) to insert after. The position reference doesn't exist yet.

However, before: "some.array[0]" works on an empty array because the mutation can conceptually insert "before the first position" even when that position is empty.

The JavaScript client documentation shows the proper pattern for appending to arrays that might be empty:

client
  .patch('document-id')
  // First ensure the array exists
  .setIfMissing({reviews: []})
  // Then append using insert after [-1]
  .insert('after', 'reviews[-1]', [{
    _key: 'unique-key',
    title: 'Great bike!',
    stars: 5
  }])
  .commit()

The key is using .setIfMissing() first to ensure the array exists before trying to append. This creates an empty array if one doesn't exist, then the insert after [-1] works as expected.

Alternative: Use the append() method

Even better, the client provides dedicated append() and prepend() methods that handle empty arrays gracefully:

client
  .patch('document-id')
  .setIfMissing({reviews: []})
  .append('reviews', [{
    _key: 'unique-key',
    title: 'Great bike!',
    stars: 5
  }])
  .commit()

The append() method is more readable and explicitly designed for this use case. It's essentially a convenience wrapper around the insert after [-1] pattern.

Why prepend works but append doesn't

So your observation is correct - this is normal behavior based on how array position references work in the Sanity mutations API. Always use setIfMissing() before attempting to append to an array that might not exist, or use the append() method which is designed to handle this pattern more elegantly.

Show original thread
1 reply

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.

Related contributions