Error querying data from Sanity API in Gatsby component
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!
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.