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:

  1. Run gatsby clean to delete .cache and public
  2. Run gatsby develop to regenerate the schema
  3. Inspect .cache/schema.graphql to 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:

  1. Enable verbose logging

    DEBUG=gatsby:* gatsby build --verbose

    This activates all internal debug namespaces including gatsby:query-watcher and gatsby:worker.

  2. Identify the failing page Look for "Failed building HTML for …" messages. Check .cache/production-html/page-data.json for the raw stack trace.

  3. Add strategic logging Inject reporter.info("checkpoint") in gatsby-node.js or components. The reporter utility in packages/gatsby/src/reporter/reporter.ts provides structured logging with timestamps.

  4. Enable Node inspector

    gatsby develop --inspect

    This activates the mutation-tracking flag and allows debugging with Chrome DevTools or VS Code.

  5. Isolate plugins Disable plugins one-by-one in gatsby-config.js to identify the culprit.

  6. Enable SSR in development

    // gatsby-config.js
    module.exports = {
      flags: { DEV_SSR: true },
    }

    This catches SSR errors during gatsby develop rather than at build time.

  7. Clean and rebuild

    gatsby clean && gatsby build

Configuration Pitfalls to Avoid

Avoid these common mistakes that break Gatsby builds:

  • Using window or document at the top level of components Why it breaks: Node.js has no DOM during SSR. Fix: Move code inside useEffect or guard with typeof window !== 'undefined'.

  • Missing sharp binary Why it breaks: Native dependencies fail to load. Fix: Run npm rebuild sharp or reinstall gatsby-plugin-image.

  • Custom Babel config excluding node_modules Why 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-uglify during debugging.

  • Incorrect StaticQuery usage Why it breaks: Queries execute at build time without runtime context. Fix: Move queries to page components or use useStaticQuery correctly.

  • Out-of-date GraphQL schema Why it breaks: Queries reference deleted fields. Fix: Run gatsby clean to rebuild the schema cache.

  • Missing gatsby-plugin-react-helmet Why it breaks: <Helmet> components render nothing. Fix: Install and configure the plugin in gatsby-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 in packages/gatsby/src/utils/worker/child/render-html.ts.
  • Enable verbose logging using DEBUG=gatsby:* and --verbose to expose internal operations including webpack config and query watching.
  • Use diagnostic flags like --debug and --inspect defined in packages/gatsby/src/utils/flags.ts to track node mutations and enable breakpoint debugging.
  • Clean the cache with gatsby clean when facing GraphQL schema errors or non-deterministic failures.
  • Isolate plugins by disabling them one-by-one in gatsby-config.js to identify lifecycle errors in gatsby-node.js hooks.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →