Issue with fetching data from Sanity API in Next.js project
The HTTP 404 error you're seeing is happening because your Sanity client configuration is missing the required apiVersion property. This is a mandatory field that tells Sanity which version of the API you want to use.
Here's the fix for your sanity.js file:
import { createClient, createImageUrlBuilder } from "next-sanity";
const config = {
dataset: "production",
projectId: "****************",
apiVersion: "2024-01-01", // ADD THIS LINE
useCdn: process.env.NODE_ENV === "production",
};
export const urlFor = (source) => createImageUrlBuilder(config).image(source);
export const sanityClient = createClient(config);The apiVersion should be set to today's date or the date you're developing your project (in YYYY-MM-DD format). This ensures your queries work consistently as Sanity's API evolves.
Additional recommendations:
- Use environment variables instead of hardcoding your projectId. Create a
.env.localfile:
NEXT_PUBLIC_SANITY_PROJECT_ID=your-project-id NEXT_PUBLIC_SANITY_DATASET=production
Then update your config:
const config = {
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || "production",
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
apiVersion: "2024-01-01",
useCdn: process.env.NODE_ENV === "production",
};Verify your dataset exists: Double-check that you actually have a "production" dataset in your Sanity project. You can verify this in your Sanity management console or by running
sanity dataset listin your terminal.Make sure your schema is deployed: Ensure you've started your Sanity Studio (
sanity dev) so your "post" schema is available, or if you're using a separate Studio, make sure it's been deployed.
Once you add the apiVersion, your 404 error should be resolved and your queries will work properly!
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.