Created
September 28, 2018 11:53
-
-
Save mcdougal/7bf001417c3dc4b579da224b12776691 to your computer and use it in GitHub Desktop.
Using @sentry/browser with Next.js for client and server-side rendering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Sentry from '@sentry/browser'; | |
import getConfig from 'next/config'; | |
import React from 'react'; | |
const { SENTRY_DSN } = getConfig().publicRuntimeConfig; | |
Sentry.init({ dsn: SENTRY_DSN }); | |
/** | |
* Send an error event to Sentry. | |
* | |
* Server-side: | |
* Next.js captures SSR errors and never passes them to the Sentry | |
* middleware. It does, however, render the _error.js component, so | |
* we can manually fire Sentry events here. | |
* | |
* Client-side: | |
* Unhandled client exceptions will always bubble up to the _error.js | |
* component, so we can manually fire events here. | |
*/ | |
const notifySentry = (err, req, statusCode) => { | |
Sentry.configureScope((scope) => { | |
if (!req) { | |
scope.setTag(`ssr`, false); | |
} else { | |
scope.setTag(`ssr`, true); | |
scope.setExtra(`url`, req.url); | |
scope.setExtra(`params`, req.params); | |
scope.setExtra(`query`, req.query); | |
scope.setExtra(`statusCode`, statusCode); | |
scope.setExtra(`headers`, req.headers); | |
if (req.user) { | |
scope.setUser({ id: req.user.id, email: req.user.email }); | |
} | |
} | |
}); | |
Sentry.captureException(err); | |
}; | |
export default class Error extends React.Component { | |
static async getInitialProps({ req, res, err }) { | |
let statusCode; | |
if (res) { | |
({ statusCode } = res); | |
} else if (err) { | |
({ statusCode } = err); | |
} else { | |
statusCode = null; | |
} | |
notifySentry(err, req, statusCode); | |
return { statusCode }; | |
} | |
render() { | |
const { statusCode } = this.props; | |
return statusCode; | |
} | |
} |
@leerob, could you explain more the part with uploading the source map to sentry (and not providing them publicly)...
I've followed the examples but cannot find a way to properly show the error stack in sentry
(full reference: https://stackoverflow.com/questions/61011281/next-js-source-maps-with-typescript-on-sentry)
@leerob, I've tried your example, but still doesn't seem to report errors on time.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh! I misunderstood what
it
was referring to inThere are still a few issues with it
. In that case your simple example will be really helpful (the complex one didn't even work in the end.. rip).