Commit ecbecb9e authored by Jess Telford's avatar Jess Telford Committed by Tim Neutkens

Fixes for with-sentry example (#6362)

parent 9d7385c3
...@@ -46,4 +46,11 @@ now ...@@ -46,4 +46,11 @@ now
This example show you how to add Sentry to catch errors in next.js This example show you how to add Sentry to catch errors in next.js
You will need a Sentry DSN for your project. You can get it from the Settings of your Project, in **Client Keys (DSN)**, and copy the string labeled **DSN (Public)**. You will need a Sentry DSN for your project. You can get it from the Settings of your Project, in **Client Keys (DSN)**, and copy the string labeled **DSN (Public)**.
The Sentry DSN should then be added as an environment variable when running:
```bash
$ SENTRY_DSN=<dsn-here> npm run dev
```
Note that if you are using a custom server, there is logging available for common platforms: https://docs.sentry.io/platforms/ Note that if you are using a custom server, there is logging available for common platforms: https://docs.sentry.io/platforms/
const webpack = require('webpack') const webpack = require('webpack')
const nextSourceMaps = require('@zeit/next-source-maps')() const nextSourceMaps = require('@zeit/next-source-maps')()
const SENTRY_DSN = ''
module.exports = nextSourceMaps({ module.exports = nextSourceMaps({
webpack: (config, { dev, isServer, buildId }) => { webpack: (config, { isServer, buildId }) => {
if (!dev) {
config.plugins.push( config.plugins.push(
new webpack.DefinePlugin({ new webpack.DefinePlugin({
'process.env.SENTRY_DSN': JSON.stringify(SENTRY_DSN), 'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN),
'process.env.SENTRY_RELEASE': JSON.stringify(buildId) 'process.env.SENTRY_RELEASE': JSON.stringify(buildId)
}) })
) )
}
if (!isServer) { if (!isServer) {
config.resolve.alias['@sentry/node'] = '@sentry/browser' config.resolve.alias['@sentry/node'] = '@sentry/browser'
......
{ {
"name": "with-sentry", "name": "with-sentry",
"version": "1.0.0", "version": "1.1.0",
"scripts": { "scripts": {
"dev": "next", "dev": "node server.js",
"build": "next build", "build": "next build",
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@sentry/browser": "^4.6.1",
"@sentry/node": "^4.6.1",
"@zeit/next-source-maps": "0.0.4-canary.1",
"cookie-parser": "1.4.4",
"js-cookie": "2.2.0",
"next": "latest", "next": "latest",
"@sentry/browser": "^4.0.4", "react": "^16.8.0",
"react": "^16.7.0", "react-dom": "^16.8.0",
"react-dom": "^16.7.0" "sentry-testkit": "^2.1.0",
"uuid": "^3.3.2"
}, },
"license": "ISC" "license": "ISC"
} }
import App from 'next/app' import App from 'next/app'
import * as Sentry from '@sentry/browser' import sentry from '../utils/sentry'
const SENTRY_PUBLIC_DSN = '' const { Sentry, captureException } = sentry({ release: process.env.SENTRY_RELEASE })
export default class MyApp extends App { export default class MyApp extends App {
constructor (...args) { constructor () {
super(...args) super(...arguments)
Sentry.init({ dsn: SENTRY_PUBLIC_DSN }) this.state = {
hasError: false,
errorEventId: undefined
}
}
static async getInitialProps ({ Component, ctx }) {
try {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
} catch (error) {
// Capture errors that happen during a page's getInitialProps.
// This will work on both client and server sides.
const errorEventId = captureException(error, ctx)
return {
hasError: true,
errorEventId
}
}
}
static getDerivedStateFromProps (props, state) {
// If there was an error generated within getInitialProps, and we haven't
// yet seen an error, we add it to this.state here
return {
hasError: props.hasError || state.hasError || false,
errorEventId: props.errorEventId || state.errorEventId || undefined
}
}
static getDerivedStateFromError () {
// React Error Boundary here allows us to set state flagging the error (and
// later render a fallback UI).
return { hasError: true }
} }
componentDidCatch (error, errorInfo) { componentDidCatch (error, errorInfo) {
Sentry.configureScope(scope => { const errorEventId = captureException(error, { errorInfo })
Object.keys(errorInfo).forEach(key => {
scope.setExtra(key, errorInfo[key]) // Store the event id at this point as we don't have access to it within
}) // `getDerivedStateFromError`.
}) this.setState({ errorEventId })
Sentry.captureException(error) }
// This is needed to render errors correctly in development / production render () {
super.componentDidCatch(error, errorInfo) return this.state.hasError ? (
<section>
<h1>There was an error!</h1>
<p>
<a
href='#'
onClick={() => Sentry.showReportDialog({ eventId: this.state.errorEventId })}
>
📣 Report this error
</a>
</p>
<p>
<a
href='#'
onClick={() => { window.location.reload(true) }}
>
Or, try reloading the page
</a>
</p>
</section>
) : (
// Render the normal Next.js page
super.render()
)
} }
} }
const next = require('next') const next = require('next')
const express = require('express') const express = require('express')
const cookieParser = require('cookie-parser') const cookieParser = require('cookie-parser')
const Sentry = require('@sentry/node')
const uuidv4 = require('uuid/v4') const uuidv4 = require('uuid/v4')
const port = parseInt(process.env.PORT, 10) || 3000 const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production' const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev }) const app = next({ dev })
const handle = app.getRequestHandler() const handler = app.getRequestHandler()
require('./utils/sentry') function sessionCookie (req, res, next) {
app.prepare()
.then(() => {
const server = express()
// This attaches request information to sentry errors
server.use(Sentry.Handlers.requestHandler())
server.use(cookieParser())
server.use((req, res, next) => {
const htmlPage = const htmlPage =
!req.path.match(/^\/(_next|static)/) && !req.path.match(/^\/(_next|static)/) &&
!req.path.match(/\.(js|map)$/) && !req.path.match(/\.(js|map)$/) &&
...@@ -36,31 +24,39 @@ app.prepare() ...@@ -36,31 +24,39 @@ app.prepare()
} }
next() next()
}) }
// In production we don't want to serve sourcemaps for anyone const sourcemapsForSentryOnly = token => (req, res, next) => {
if (!dev) { // In production we only want to serve source maps for sentry
const hasSentryToken = !!process.env.SENTRY_TOKEN if (!dev && !!token && req.headers['x-sentry-token'] !== token) {
server.get(/\.map$/, (req, res, next) => {
if (hasSentryToken && req.headers['x-sentry-token'] !== process.env.SENTRY_TOKEN) {
res res
.status(401) .status(401)
.send( .send('Authentication access token is required to access the source map.')
'Authentication access token is required to access the source map.'
)
return return
} }
next() next()
}) }
}
server.get('*', (req, res) => handle(req, res)) app.prepare().then(() => {
// The app.buildId is only available after app.prepare(), hence why we setup
// here.
const { Sentry } = require('./utils/sentry')({ release: app.buildId })
express()
// This attaches request information to sentry errors
.use(Sentry.Handlers.requestHandler())
.use(cookieParser())
.use(sessionCookie)
.get(/\.map$/, sourcemapsForSentryOnly(process.env.SENTRY_TOKEN))
// Regular next.js request handler
.use(handler)
// This handles errors if they are thrown before raching the app // This handles errors if they are thrown before raching the app
server.use(Sentry.Handlers.errorHandler()) .use(Sentry.Handlers.errorHandler())
.listen(port, err => {
server.listen(port, err => { if (err) {
if (err) throw err throw err
}
// eslint-disable-next-line no-console
console.log(`> Ready on http://localhost:${port}`) console.log(`> Ready on http://localhost:${port}`)
}) })
}) })
// NOTE: This require will be replaced with `@sentry/browser` when
// process.browser === true thanks to the webpack config in next.config.js
const Sentry = require('@sentry/node') const Sentry = require('@sentry/node')
const Cookie = require('js-cookie') const Cookie = require('js-cookie')
if (process.env.SENTRY_DSN) { module.exports = ({ release }) => {
Sentry.init({ const sentryOptions = {
dsn: process.env.SENTRY_DSN, dsn: process.env.SENTRY_DSN,
release: process.env.SENTRY_RELEASE, release,
maxBreadcrumbs: 50, maxBreadcrumbs: 50,
attachStacktrace: true attachStacktrace: true
}) }
}
// When we're developing locally
if (process.env.NODE_ENV !== 'production') {
/* eslint-disable-next-line global-require */
const sentryTestkit = require('sentry-testkit')
const { sentryTransport } = sentryTestkit()
// Don't actually send the errors to Sentry
sentryOptions.transport = sentryTransport
// Instead, dump the errors to the console
sentryOptions.integrations = [new Sentry.Integrations.Debug({
// Trigger DevTools debugger instead of using console.log
debugger: false
})]
}
Sentry.init(sentryOptions)
function captureException (err, { req, res, errorInfo, query, pathname }) { return {
Sentry.configureScope(scope => { Sentry,
captureException: (err, { req, res, errorInfo, query, pathname }) => {
Sentry.configureScope((scope) => {
if (err.message) { if (err.message) {
// De-duplication currently doesn't work correctly for SSR / browser errors // De-duplication currently doesn't work correctly for SSR / browser errors
// so we force deduplication by error message if it is present // so we force deduplication by error message if it is present
...@@ -51,13 +72,11 @@ function captureException (err, { req, res, errorInfo, query, pathname }) { ...@@ -51,13 +72,11 @@ function captureException (err, { req, res, errorInfo, query, pathname }) {
} }
if (errorInfo) { if (errorInfo) {
scope.setExtra('componentStack', errorInfo.componentStack) Object.keys(errorInfo).forEach(key => scope.setExtra(key, errorInfo[key]))
} }
}) })
Sentry.captureException(err) return Sentry.captureException(err)
} }
}
module.exports = {
captureException
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment