How to Debug Gatsby Build Errors and Fix Common Configuration Issues
Enable verbose debug output with DEBUG=gatsby:*, guard browser-only APIs with typeof window !== "undefined", and clear the cache with gatsby clean to resolve most Gatsby build failures.
When your Gatsby site crashes during gatsby build, the error typically stems from server-side rendering (SSR) incompatibilities, misconfigured plugins, or stale caches. Understanding how the gatsbyjs/gatsby source code handles the build pipeline allows you to pinpoint exactly where the process fails and apply the correct fix.
Understanding SSR vs. Browser Environments
Gatsby generates static HTML at build time using Node.js, not a browser. This architectural distinction means global browser APIs like window and document do not exist during the SSR phase. Code that references these objects at the top level of a module will throw ReferenceError: window is not defined when the render-html.ts worker attempts to generate page markup.
Common Gatsby Build Error Categories
HTML Build (SSR) Failures
The most frequent build error occurs in packages/gatsby/src/utils/worker/child/render-html.ts, where Gatsby renders React components to static HTML. If your component or a third-party library accesses browser APIs during this phase, the build crashes.
Fix: Guard browser-only code:
if (typeof window !== "undefined") {
// Client-only code here
require("some-browser-library")
}
For third-party modules that cannot be modified, use a null loader to ignore them during SSR, as documented in the debugging HTML builds guide.
Plugin Lifecycle Errors
Errors inside gatsby-node.js or plugin hooks like onCreateNode and createPages halt the build before page generation begins. The packages/gatsby/src/utils/flags.ts file defines a diagnostic flag that provides detailed mutation logs.
Enable diagnostic mode:
gatsby develop --debug
This activates the debug flag at line 125 of flags.ts, exposing detailed information about node mutations and plugin activity.
GraphQL Schema and Query Failures
When queries reference fields that no longer exist in the schema, Gatsby throws GraphQLError during the query extraction phase. The schema is cached in .cache/schema.graphql.
Resolution steps:
- Run
gatsby cleanto delete.cacheandpublic - Run
gatsby developto regenerate the schema - Inspect
.cache/schema.graphqlto verify field availability
Webpack and Babel Configuration Issues
Custom webpack or Babel configurations can conflict with Gatsby's internal setup defined in packages/gatsby/src/utils/webpack.config.js. When the build fails with "Module build failed" or "Unexpected token," the webpack config itself may be the culprit.
Debug webpack configuration:
DEBUG=gatsby:webpack-config gatsby build
This environment variable triggers debug logging in webpack.config.js (lines 12-71), printing the final resolved configuration to the console.
Image Processing and Sharp Binary Errors
Gatsby relies on the sharp library for image transformations. Missing or incompatible native binaries cause "Failed to process image" errors.
Fix sharp issues:
npm rebuild sharp
For debugging image processing without minification overhead, use the --no-uglify flag:
gatsby build --no-uglify
This flag is documented in the Gatsby CLI reference.
Step-by-Step Debugging Workflow
When you encounter a build failure, follow this systematic approach:
-
Enable verbose logging
DEBUG=gatsby:* gatsby build --verboseThis activates all internal debug namespaces including
gatsby:query-watcherandgatsby:worker. -
Identify the failing page Look for "Failed building HTML for …" messages. Check
.cache/production-html/page-data.jsonfor the raw stack trace. -
Add strategic logging Inject
reporter.info("checkpoint")ingatsby-node.jsor components. Thereporterutility inpackages/gatsby/src/reporter/reporter.tsprovides structured logging with timestamps. -
Enable Node inspector
gatsby develop --inspectThis activates the mutation-tracking flag and allows debugging with Chrome DevTools or VS Code.
-
Isolate plugins Disable plugins one-by-one in
gatsby-config.jsto identify the culprit. -
Enable SSR in development
// gatsby-config.js module.exports = { flags: { DEV_SSR: true }, }This catches SSR errors during
gatsby developrather than at build time. -
Clean and rebuild
gatsby clean && gatsby build
Configuration Pitfalls to Avoid
Avoid these common mistakes that break Gatsby builds:
-
Using
windowordocumentat the top level of components Why it breaks: Node.js has no DOM during SSR. Fix: Move code insideuseEffector guard withtypeof window !== 'undefined'. -
Missing
sharpbinary Why it breaks: Native dependencies fail to load. Fix: Runnpm rebuild sharpor reinstallgatsby-plugin-image. -
Custom Babel config excluding
node_modulesWhy it breaks: Gatsby's internal transforms fail. Fix: Extend the default config rather than replacing it entirely. -
Over-aggressive webpack minification Why it breaks: Source maps disappear, hiding error locations. Fix: Use
--no-uglifyduring debugging. -
Incorrect
StaticQueryusage Why it breaks: Queries execute at build time without runtime context. Fix: Move queries to page components or useuseStaticQuerycorrectly. -
Out-of-date GraphQL schema Why it breaks: Queries reference deleted fields. Fix: Run
gatsby cleanto rebuild the schema cache. -
Missing
gatsby-plugin-react-helmetWhy it breaks:<Helmet>components render nothing. Fix: Install and configure the plugin ingatsby-config.js.
Essential Debugging Commands and Environment Variables
Keep these commands ready when troubleshooting:
# Maximum verbosity with all debug namespaces
DEBUG=gatsby:* gatsby build --verbose
# Debug webpack configuration specifically
DEBUG=gatsby:webpack-config gatsby build
# Start development with Node inspector for breakpoint debugging
gatsby develop --inspect
# Enable diagnostic mode for node mutation tracking
gatsby develop --debug
# Build without minification for clearer stack traces
gatsby build --no-uglify
# Clean cache and public folders
gatsby clean
# Rebuild sharp binaries
npm rebuild sharp
Summary
- Guard browser APIs with
typeof window !== "undefined"to prevent SSR crashes inpackages/gatsby/src/utils/worker/child/render-html.ts. - Enable verbose logging using
DEBUG=gatsby:*and--verboseto expose internal operations including webpack config and query watching. - Use diagnostic flags like
--debugand--inspectdefined inpackages/gatsby/src/utils/flags.tsto track node mutations and enable breakpoint debugging. - Clean the cache with
gatsby cleanwhen facing GraphQL schema errors or non-deterministic failures. - Isolate plugins by disabling them one-by-one in
gatsby-config.jsto identify lifecycle errors ingatsby-node.jshooks.
Frequently Asked Questions
Why do I get "window is not defined" during gatsby build?
This error occurs because Gatsby renders your components in a Node.js environment during the static HTML generation phase, where browser APIs like window do not exist. The error originates in packages/gatsby/src/utils/worker/child/render-html.ts when the SSR worker attempts to execute browser-specific code. Fix this by wrapping browser-only code in a conditional check: if (typeof window !== "undefined") { ... } or moving the logic inside a useEffect hook.
How do I enable detailed logging for Gatsby builds?
Set the DEBUG environment variable to gatsby:* when running your build command: DEBUG=gatsby:* gatsby build --verbose. This activates all internal debug namespaces defined in the Gatsby source, including gatsby:webpack-config, gatsby:query-watcher, and gatsby:worker. For webpack-specific debugging, use DEBUG=gatsby:webpack-config to see the final resolved configuration from packages/gatsby/src/utils/webpack.config.js.
What should I do if a plugin crashes during the build?
First, enable diagnostic mode by running gatsby develop --debug to see detailed logs from the plugin lifecycle. This flag, defined in packages/gatsby/src/utils/flags.ts, exposes node mutation tracking that can reveal which plugin is corrupting the data layer. Next, disable plugins one-by-one in gatsby-config.js to isolate the culprit. If the error occurs in gatsby-node.js hooks like onCreateNode or createPages, add reporter.info() statements using the reporter utility from packages/gatsby/src/reporter/reporter.ts to trace execution.
How do I fix sharp image processing errors?
Sharp errors typically indicate a missing or incompatible native binary. Run npm rebuild sharp to recompile the binary for your current platform. If builds fail with "Failed to process image," ensure gatsby-plugin-image is properly configured and that you haven't exceeded memory limits. For debugging image processing without the overhead of minification, use gatsby build --no-uglify to preserve source maps and detailed error traces. This flag is documented in the Gatsby CLI reference and helps isolate whether the error occurs during image transformation or the subsequent optimization phase.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →