Querying data in NextJS using GraphQL in Sanity - fetch request format not clear

15 replies
Last updated: Jun 4, 2022
Hello there - I wonder if someone is able to point me in the right direction. I am attempting to query my data in NextJS using GraphQL in Sanity. Doing things the way I know how yields an error from NextJS.
Sanity seems to have some pretty clear docs on how to execute a query using GROQ [
https://www.sanity.io/docs/connect-your-content-to-next-js ], but I haven’t been able to find any docs, or even a code snippet that suggests how the fetch request should be made. It’s very likely that I’m just looking in the wrong places. Can anyone help me out?
AI Update

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 deploy

This 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;
}

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.

what error?
What Austin asked: what error do you have?
You typically want to use the Sanity JS client in
getStaticProps
and
getStaticPaths
to query your data.
object
("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.`
You need to await that promise so it gets resolved.
I’m mostly looking for the right way to format the fetch request to the graphQL api in NextJS which the docs don’t appear to detail… It was an async function.
This is how my request looks

export async function getStaticProps() {
  const graphQlQuery = `
    query {
      allPost (sort: {publishDate: DESC}) {
        _id
        title
        publishDate
        readTime
        slug {current}
        contentRaw 
      }
    }
  `;

  const allPostsData = await fetch(
    '<https://xxxxxxxx.api.sanity.io/v1/graphql/production/default>',
    {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        query: graphQlQuery,
        variables: {},
      }),
    }
  )
    .then((res) => res.json())
    .then((data) => console.log(data));
  return {
    props: {
      allPostsData,
    },
  };
}
That results in the above error.
Thanks for the help. I took a look at the thread and made an adjustment. The serialization error went away, but I’m not able to get a log of any response data irrespective of where I try to get that out of the promise.
That’s because your log.
That’s because of your log. You’re mixing promises and async/await. Right now, your promise chain eventually returns
undefined
, because it returns a console log.
Right your promise chain eventually return
undefined
, because it returns a console log.
I’d recommend rewriting it like this.
const response = await fetch(…)
const data = await response.json()

console.log(data)
Thanks

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.

Was this answer helpful?