400 Error on Sanity Query Fetching Posts in React Portfolio
Looking at your code, the 400 error is almost certainly caused by a GROQ syntax error in your query. Here's what's wrong and how to fix it:
The Problem
Your query has formatting issues with commas and spacing. Here's the corrected version:
sanityClient.fetch(
`*[_type == "post"]{
title,
slug,
mainImage {
asset->{
_id,
url
}
}
}`
)Key fixes:
- Added comma after
title - Removed the space in
asset->(should beasset->notasset->) - Proper comma placement throughout
Check Your Client Configuration
Since you're following an older tutorial, make sure your client.js file includes the required apiVersion parameter. Your client configuration should look like this:
import sanityClient from '@sanity/client'
export default sanityClient({
projectId: 'your-project-id', // find this at manage.sanity.io
dataset: 'production',
useCdn: true,
apiVersion: '2023-05-03' // THIS IS REQUIRED - use any UTC date
})According to the Sanity documentation on Project ID, the apiVersion is mandatory for modern Sanity client versions, and missing it will cause errors.
Additional Improvements
- Add error handling for missing images:
<img src={post.mainImage?.asset?.url} alt={post.title} />Check the browser console Network tab - click on the failed request to see the exact error message from Sanity, which will tell you specifically what's wrong with your query.
Verify your schema - make sure you have documents with
_type == "post"in your Sanity dataset and that they have amainImagefield.
The 400 error means "Bad Request," which in Sanity almost always points to malformed GROQ syntax. Try the corrected query above first, and if you're still stuck, share the specific error message from the Network tab for more targeted help!
Show original thread6 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.