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:
1 npm install gatsby-plugin-sentry
In your gatsby-config.js add:
1 {
2 resolve: 'gatsby-plugin-sentry',
3 options: {
4 dsn: process.env.SENTRY_DSN,
5 },
6},
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:
1import React from 'react'
2import Sentry from 'gatsby-plugin-sentry'
3
4class ErrorBoundary extends React.Component {
5 constructor(props) {
6 super(props)
7 this.state = { error: null }
8 }
9
10 componentDidCatch(error, errorInfo) {
11 this.setState({ error })
12 Sentry.configureScope((scope) => {
13 Object.keys(errorInfo).forEach((key) => {
14 scope.setExtra(key, errorInfo[key])
15 })
16 })
17 Sentry.captureException(error)
18 }
19
20 render() {
21 if (this.state.error) {
22 // render fallback UI
23 return <h1>Something went wrong!</h1>
24 } else {
25 // when there's not an error,
26 //render children untouched
27 return this.props.children
28 }
29 }
30}
31
32export default ErrorBoundary
And finally, wrap around Layout component:
1const Layout = (props) => (
2 <ErrorBoundary>
3 <React.Fragment>
4 <Helmet>
5 <body className="bg-white mid-gray" />
6 </Helmet>
7 <Navbar />
8 {props.children}
9 <Footer />
10 </React.Fragment>
11 </ErrorBoundary>
12 )
Now you can see all error in your project:

You can add more parameters editing config for example:
1{
2 resolve: "gatsby-plugin-sentry",
3 options: {
4 dsn: process.env.SENTRY_DSN,
5 release:process.env.APP_VERSION,
6 environment: process.env.SENTRY_ENV,
7 }
8},
You can find all possibilities in official documentation.