Adding apiVersion causing breaks in Sanity code
Welcome to the community! This is a common issue when adding an apiVersion for the first time. Let me help you understand what's happening.
When you don't set an apiVersion, Sanity's client defaults to v1 of the API. Once you add an explicit apiVersion (like '2021-03-25' or later), you're upgrading to a newer version that includes several breaking changes.
What Changed Between v1 and Later Versions
According to the official API versioning documentation and GROQ changelog, the most significant breaking changes when moving from v1 to v2021-03-25 include:
1. Correct parent operator (^) behavior
The ^ operator now works correctly in all scopes. Previously in v1, it had buggy behavior where it would return the root of the current scope instead of the parent scope in certain contexts.
2. Three-valued logic for null/undefined handling
The handling of null and undefined values changed significantly. The == operator now always returns true or false (never null), and comparison operators like >, >=, <, <= return null when operands are of different types. This is probably what you're experiencing with properties returning null instead of arrays.
3. Null values are no longer removed in projections
If you have stored null values in your documents, these are no longer automatically removed in projections in newer API versions.
4. Array traversal behavior
Multiple array traversals now work more consistently and correctly.
How to Debug and Migrate
- You can stay on v1 temporarily - Use
apiVersion: 1orapiVersion: 'v1'to explicitly use the old version while you work through issues - Test queries individually - Migrate one query at a time rather than everything at once
- Check for null handling - Based on what you described (properties being arrays in v1 but null with apiVersion set), you likely have queries that need to handle null values differently
- Use the changelog filters to see exactly what changed between versions
Working Around the Null Issue
As mentioned in the community answers, one workaround is to use conditional checks in your GROQ queries:
defined(field) => {field}This ensures fields are only included when they're defined, though it can be tedious to add everywhere.
The good news is that while these are breaking changes, they generally fix bugs and make GROQ more predictable and spec-compliant. Once you update your queries, they'll be more robust going forward. And there's no rush - v1 will continue to be supported for the foreseeable future, though it won't receive new features.
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.