Mutations API - How does Append work on an Empty Array?
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 recommended approach
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
before: "array[0]"(prepend) works because position[0]is a valid conceptual position even in an empty arrayafter: "array[-1]"(append) fails because[-1]tries to reference "the last element" which doesn't exist in an empty array
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.
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.