Querying data in NextJS using GraphQL in Sanity - fetch request format not clear
I can help you with that! While Sanity's documentation focuses heavily on GROQ (which is their native query language), you can absolutely use GraphQL with Next.js. Here's what you need to know:
Setting Up GraphQL
First, you need to deploy a GraphQL API for your Sanity project. Run this command in your Sanity project directory:
sanity graphql deployThis creates a GraphQL endpoint for your dataset.
GraphQL Endpoint URL Format
Once deployed, your GraphQL endpoint will be:
https://<projectId>.api.sanity.io/v1/graphql/<dataset>/default
Replace <projectId> with your actual project ID and <dataset> with your dataset name (usually "production").
Making Fetch Requests in Next.js
Here's how to query your Sanity GraphQL API using fetch in Next.js:
async function fetchSanityData() {
const query = `
query {
allPost {
title
slug {
current
}
}
}
`;
const response = await fetch(
`https://${process.env.NEXT_PUBLIC_SANITY_PROJECT_ID}.api.sanity.io/v1/graphql/${process.env.NEXT_PUBLIC_SANITY_DATASET}/default`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Only needed if your dataset is private:
// 'Authorization': `Bearer ${process.env.SANITY_API_TOKEN}`,
},
body: JSON.stringify({ query }),
}
);
const { data } = await response.json();
return data;
}Using with Apollo Client (Recommended)
For a better GraphQL experience in Next.js, consider using Apollo Client with Sanity:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: `https://${process.env.NEXT_PUBLIC_SANITY_PROJECT_ID}.api.sanity.io/v1/graphql/${process.env.NEXT_PUBLIC_SANITY_DATASET}/default`,
cache: new InMemoryCache(),
});
// Then in your component or API route:
const { data } = await client.query({
query: gql`
query {
allPost {
title
}
}
`,
});Important Notes
- The Sanity GraphQL API supports the current version (v2023-08-01) with Perspectives and Content Source Maps
- GraphQL subscriptions are not currently supported - if you need real-time updates, you'll need to use Sanity's JavaScript client with GROQ
- You can use both GraphQL and GROQ in the same project if needed
- The GraphQL schema is auto-generated from your Sanity schema, so you can use GraphQL Playground to explore available queries
Hope this gets you unstuck! Let me know if you hit any other issues.
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.