Adaptiware Logo
JavaScript

Sentry for Gatsby

SestooSestoo
2 min read
Sentry for Gatsby

Monitoring bugs in production is really useful thing, especially for professional development. Today's industry standard for bug tracking has become Sentry.

Thanks to the great support and big community, there are many ready-made solutions for integration with different frameworks.

Today we will show how to integrate sentry with GatsbyJs static site generator.

Install Packages

Go to your Gatsby project and add gatsby-plugin-sentry:

SHELL
npm install gatsby-plugin-sentry

In your gatsby-config.js add:

JAVASCRIPT
{
  resolve: 'gatsby-plugin-sentry',
  options: {
    dsn: process.env.SENTRY_DSN,
  },
},

I recommend using an environment variable, because you don't want your secret for your project being exposed.

Error Boundary component

This wrapper can catch any errors in our application and use it to send the details to Sentry. It is a good idea to have the same layout component for every page, so we can easily wrap all site.

Create ErrorBoundary.js file for our component:

JAVASCRIPT
import React from 'react'
import Sentry from 'gatsby-plugin-sentry'

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props)
    this.state = { error: null }
  }

  componentDidCatch(error, errorInfo) {
    this.setState({ error })
    Sentry.configureScope((scope) => {
      Object.keys(errorInfo).forEach((key) => {
        scope.setExtra(key, errorInfo[key])
      })
    })
    Sentry.captureException(error)
  }

  render() {
    if (this.state.error) {
      // render fallback UI
      return <h1>Something went wrong!</h1>
    } else {
      // when there's not an error,
      //render children untouched
      return this.props.children
    }
  }
}

export default ErrorBoundary

And finally, wrap around Layout component:

JAVASCRIPT
const Layout = (props) => (
  <ErrorBoundary>
      <React.Fragment>
        <Helmet>
          <body className="bg-white mid-gray" />
        </Helmet>
        <Navbar />
        {props.children}
        <Footer />
      </React.Fragment>
  </ErrorBoundary>
  )

Now you can see all error in your project:

Error example in sentry environmentError example in sentry environment

You can add more parameters editing config for example:

JAVASCRIPT
{
  resolve: "gatsby-plugin-sentry",
  options: {
    dsn: process.env.SENTRY_DSN,
    release:process.env.APP_VERSION,
    environment: process.env.SENTRY_ENV,
  }
},

You can find all possibilities in official documentation.

#javascript#sentry#gatsby#integration#error-tracking
Sestoo

Sestoo

Backend Developer at Adaptiware