WebpackError: Configuration must contain `projectId`
This is a classic environment variable issue during the Gatsby build process. The error means that process.env.SANITY_PROJECT_ID is undefined when Gatsby runs your build, even though it works fine in development.
The Problem
Gatsby has specific requirements for environment variables. In Gatsby, environment variables need to be:
- Prefixed with
GATSBY_to be available in browser/build code - Properly loaded from
.envfiles
Your current setup uses process.env.SANITY_PROJECT_ID, but Gatsby isn't making this available during the build process.
The Solution
Option 1: Use Gatsby-prefixed environment variables (Recommended)
Rename your environment variables in your .env file:
GATSBY_SANITY_PROJECT_ID=your-project-id GATSBY_SANITY_DATASET=your-dataset
Then update your client configuration:
const client = require("@sanity/client");
export const sanityClient = client({
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
dataset: process.env.GATSBY_SANITY_DATASET,
useCdn: false,
});Option 2: Use dotenv with Gatsby's config
If you want to keep your variable names, you can explicitly load them in gatsby-config.js:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
});
module.exports = {
// your gatsby config
};Then make sure you're accessing the variables correctly and they're defined in your .env file at the root of your project.
Additional Tips
- Check your
.envfile location - It should be at the root of your Gatsby project - Restart your development server after changing environment variables
- Don't commit
.envfiles - Add them to.gitignore - Set variables in your hosting platform - For production builds (Netlify, Vercel, etc.), you need to set these environment variables in your hosting platform's dashboard with the
GATSBY_prefix
Note: You have useCdn: false which is fine for builds, but consider setting useCdn: true for production client-side requests to get better performance through Sanity's CDN.
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.