All posts

Gatsby Error Handling Patterns for Production Sites

Implement error handling in Gatsby with error boundaries, build-time validation, GraphQL error management, and runtime error tracking.

Gatsby Error Handling Patterns for Production Sites

Gatsby sites can fail at build time or runtime. Both need dedicated error handling strategies.

Build-Time Error Handling

Gatsby builds fail silently when data is missing. Validate in gatsby-node.js:

exports.createPages = async ({ graphql, actions, reporter }) => {
  const result = await graphql(`
    query {
      allMarkdownRemark {
        nodes {
          frontmatter { slug, title }
        }
      }
    }
  `);

  if (result.errors) {
    reporter.panicOnBuild('GraphQL query failed', result.errors);
    return;
  }

  result.data.allMarkdownRemark.nodes.forEach(node => {
    if (!node.frontmatter.slug) {
      reporter.warn(`Missing slug for: ${node.frontmatter.title}`);
      return;
    }
    actions.createPage({
      path: `/blog/${node.frontmatter.slug}`,
      component: require.resolve('./src/templates/blog-post.js'),
      context: { slug: node.frontmatter.slug },
    });
  });
};

React Error Boundaries

Wrap dynamic sections with error boundaries:

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error('Component error:', error, errorInfo);
    // Report to Bugsly or your error tracking service
  }

  render() {
    if (this.state.hasError) {
      return <div>Something went wrong. Please refresh.</div>;
    }
    return this.props.children;
  }
}

Handle Missing Data Gracefully

Gatsby's GraphQL can return null for optional fields:

const BlogPost = ({ data }) => {
  const post = data?.markdownRemark;
  if (!post) return <NotFound />;

  return (
    <article>
      <h1>{post.frontmatter.title}</h1>
      {post.frontmatter.featuredImage && (
        <GatsbyImage image={getImage(post.frontmatter.featuredImage)} />
      )}
    </article>
  );
};

Runtime Considerations

  • Client-side navigation errors — Gatsby's router can fail on corrupted cache; clear localStorage gracefully
  • Service worker issues — stale cache can serve outdated pages; implement cache-busting strategies
  • Third-party script failures — load external scripts async with error callbacks

For production Gatsby sites, Bugsly captures client-side runtime errors that you'd otherwise never see in your static build pipeline.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free