GraphQL query works in Sanity playground but fails in Gatsby component
query {
allProject {
title
subtitle
description
mainImage {
asset {
url
}
}
tech
url
dates
}
}const {data} =useStaticQuery(graphql`
query getProjects {
allProject {
title
subtitle
description
mainImage {
asset {
url
}
}
tech
url
dates
}
}
`);“There was an error in your GraphQL query:
Cannot query field “allProject” on type “Query”.
If you don’t expect “allProject” to exist on the type “Query” it is most likely a typo.
However, if you expect “allProject” to exist there are a couple of solutions to common problems:”
This is the code in my Gatsby component. I have made sure to deploy the API and reload my devs server.I am new to development, and I got this structure from other people’s code on the internet. What might be going wrong? I’ve tried to read Sanity’s documentation but I couldn’t really make sense of it.
No worries, this is a common issue when setting up Sanity with Gatsby! The problem is that your GraphQL query works in Sanity's API playground, but Gatsby has its own separate GraphQL layer.
Here's what's happening: Sanity has its own GraphQL API (what you're testing in the playground), but Gatsby creates a completely different GraphQL schema by pulling data from various sources. To get Sanity data into Gatsby's GraphQL layer, you need to use the gatsby-source-sanity plugin.
Here's how to fix it:
- Install the plugin (if you haven't already):
npm install gatsby-source-sanity- Configure it in
gatsby-config.js:
module.exports = {
plugins: [
{
resolve: 'gatsby-source-sanity',
options: {
projectId: 'your-project-id',
dataset: 'production', // or your dataset name
// Optional: for draft preview
token: process.env.SANITY_TOKEN,
watchMode: true, // enables real-time updates in dev
},
},
],
}- Deploy your GraphQL API from your Sanity studio folder:
sanity graphql deploy- Restart your Gatsby dev server (important!):
gatsby clean
gatsby develop- Update your query - Gatsby prefixes Sanity types with
Sanity:
const {data} = useStaticQuery(graphql`
query getProjects {
allSanityProject {
nodes {
title
subtitle
description
mainImage {
asset {
url
}
}
tech
url
dates
}
}
}
`);Notice two changes:
allProjectbecomesallSanityProject(Gatsby adds the "Sanity" prefix)- You need to wrap your fields in
nodes { }for Gatsby's data structure
After these steps, you should be able to access your projects data via data.allSanityProject.nodes in your component. The gatsby-source-sanity plugin is what bridges Sanity's content with Gatsby's GraphQL layer - that's why the query works in Sanity's playground but not directly in Gatsby!
Show original thread3 replies
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.