Error when trying to create a dynamic query using Gatsby + Sanity
Based on the error you're seeing, it looks like you're trying to use GraphQL queries directly with Sanity's API, but Sanity actually uses GROQ (Graph-Relational Object Queries) as its query language, not GraphQL.
Here's what's happening: While Gatsby's source plugin for Sanity (gatsby-source-sanity) automatically converts your Sanity schema into a GraphQL layer that Gatsby can use for static queries, when you try to fetch data directly from Sanity using fetch or axios, you need to use GROQ syntax instead.
The Solution
You need to rewrite your query in GROQ format. Here's how to make a direct API call to Sanity using the Query API:
const query = `*[_type == "post"]{
_id,
title,
slug
}`
const projectId = 'your-project-id'
const dataset = 'production'
const apiVersion = 'v2021-06-07'
fetch(`https://${projectId}.api.sanity.io/${apiVersion}/data/query/${dataset}?query=${encodeURIComponent(query)}`)
.then(res => res.json())
.then(data => console.log(data.result))Key Differences
GraphQL (what Gatsby uses):
{
allSanityPost {
nodes {
id
title
slug
}
}
}GROQ (what Sanity's API uses):
*[_type == "post"]{
_id,
title,
slug
}Using the Sanity Client (Recommended)
Instead of using fetch or axios directly, I'd recommend using the Sanity JavaScript client, which handles the API calls and encoding for you:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'production',
useCdn: true,
apiVersion: '2021-06-07'
})
client.fetch(`*[_type == "post"]{_id, title, slug}`)
.then(posts => console.log(posts))You can test your GROQ queries in the Vision plugin in your Sanity Studio to make sure they work before using them in your code. The "expected '}' following object body" error you're getting is because the Sanity API is trying to parse your GraphQL query as GROQ and failing at the syntax differences.
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.