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
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)**.
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/
const webpack = require('webpack')
const nextSourceMaps = require('@zeit/next-source-maps')()
const SENTRY_DSN = ''
module.exports = nextSourceMaps({
webpack: (config, { dev, isServer, buildId }) => {
if (!dev) {
config.plugins.push(
new webpack.DefinePlugin({
'process.env.SENTRY_DSN': JSON.stringify(SENTRY_DSN),
'process.env.SENTRY_RELEASE': JSON.stringify(buildId)
})
)
}
webpack: (config, { isServer, buildId }) => {
config.plugins.push(
new webpack.DefinePlugin({
'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN),
'process.env.SENTRY_RELEASE': JSON.stringify(buildId)
})
)
if (!isServer) {
config.resolve.alias['@sentry/node'] = '@sentry/browser'
......
{
"name": "with-sentry",
"version": "1.0.0",
"version": "1.1.0",
"scripts": {
"dev": "next",
"dev": "node server.js",
"build": "next build",
"start": "next start"
},
"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",
"@sentry/browser": "^4.0.4",
"react": "^16.7.0",
"react-dom": "^16.7.0"
"react": "^16.8.0",
"react-dom": "^16.8.0",
"sentry-testkit": "^2.1.0",
"uuid": "^3.3.2"
},
"license": "ISC"
}
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 {
constructor (...args) {
super(...args)
Sentry.init({ dsn: SENTRY_PUBLIC_DSN })
constructor () {
super(...arguments)
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) {
Sentry.configureScope(scope => {
Object.keys(errorInfo).forEach(key => {
scope.setExtra(key, errorInfo[key])
})
})
Sentry.captureException(error)
// This is needed to render errors correctly in development / production
super.componentDidCatch(error, errorInfo)
const errorEventId = captureException(error, { errorInfo })
// Store the event id at this point as we don't have access to it within
// `getDerivedStateFromError`.
this.setState({ errorEventId })
}
render () {
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 express = require('express')
const cookieParser = require('cookie-parser')
const Sentry = require('@sentry/node')
const uuidv4 = require('uuid/v4')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
require('./utils/sentry')
app.prepare()
.then(() => {
const server = express()
const handler = app.getRequestHandler()
function sessionCookie (req, res, next) {
const htmlPage =
!req.path.match(/^\/(_next|static)/) &&
!req.path.match(/\.(js|map)$/) &&
req.accepts('text/html', 'text/css', 'image/png') === 'text/html'
if (!htmlPage) {
next()
return
}
if (!req.cookies.sid || req.cookies.sid.length === 0) {
req.cookies.sid = uuidv4()
res.cookie('sid', req.cookies.sid)
}
next()
}
const sourcemapsForSentryOnly = token => (req, res, next) => {
// In production we only want to serve source maps for sentry
if (!dev && !!token && req.headers['x-sentry-token'] !== token) {
res
.status(401)
.send('Authentication access token is required to access the source map.')
return
}
next()
}
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
server.use(Sentry.Handlers.requestHandler())
server.use(cookieParser())
server.use((req, res, next) => {
const htmlPage =
!req.path.match(/^\/(_next|static)/) &&
!req.path.match(/\.(js|map)$/) &&
req.accepts('text/html', 'text/css', 'image/png') === 'text/html'
if (!htmlPage) {
next()
return
}
if (!req.cookies.sid || req.cookies.sid.length === 0) {
req.cookies.sid = uuidv4()
res.cookie('sid', req.cookies.sid)
}
next()
})
// In production we don't want to serve sourcemaps for anyone
if (!dev) {
const hasSentryToken = !!process.env.SENTRY_TOKEN
server.get(/\.map$/, (req, res, next) => {
if (hasSentryToken && req.headers['x-sentry-token'] !== process.env.SENTRY_TOKEN) {
res
.status(401)
.send(
'Authentication access token is required to access the source map.'
)
return
}
next()
})
}
server.get('*', (req, res) => handle(req, res))
.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
server.use(Sentry.Handlers.errorHandler())
server.listen(port, err => {
if (err) throw err
.use(Sentry.Handlers.errorHandler())
.listen(port, err => {
if (err) {
throw err
}
// eslint-disable-next-line no-console
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 Cookie = require('js-cookie')
if (process.env.SENTRY_DSN) {
Sentry.init({
module.exports = ({ release }) => {
const sentryOptions = {
dsn: process.env.SENTRY_DSN,
release: process.env.SENTRY_RELEASE,
release,
maxBreadcrumbs: 50,
attachStacktrace: true
})
}
}
function captureException (err, { req, res, errorInfo, query, pathname }) {
Sentry.configureScope(scope => {
if (err.message) {
// De-duplication currently doesn't work correctly for SSR / browser errors
// so we force deduplication by error message if it is present
scope.setFingerprint([err.message])
}
// 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()
if (err.statusCode) {
scope.setExtra('statusCode', err.statusCode)
}
// Don't actually send the errors to Sentry
sentryOptions.transport = sentryTransport
if (res && res.statusCode) {
scope.setExtra('statusCode', res.statusCode)
}
// Instead, dump the errors to the console
sentryOptions.integrations = [new Sentry.Integrations.Debug({
// Trigger DevTools debugger instead of using console.log
debugger: false
})]
}
if (process.browser) {
scope.setTag('ssr', false)
scope.setExtra('query', query)
scope.setExtra('pathname', pathname)
// On client-side we use js-cookie package to fetch it
const sessionId = Cookie.get('sid')
if (sessionId) {
scope.setUser({ id: sessionId })
}
} else {
scope.setTag('ssr', true)
scope.setExtra('url', req.url)
scope.setExtra('method', req.method)
scope.setExtra('headers', req.headers)
scope.setExtra('params', req.params)
scope.setExtra('query', req.query)
// On server-side we take session cookie directly from request
if (req.cookies.sid) {
scope.setUser({ id: req.cookies.sid })
}
}
Sentry.init(sentryOptions)
if (errorInfo) {
scope.setExtra('componentStack', errorInfo.componentStack)
}
})
return {
Sentry,
captureException: (err, { req, res, errorInfo, query, pathname }) => {
Sentry.configureScope((scope) => {
if (err.message) {
// De-duplication currently doesn't work correctly for SSR / browser errors
// so we force deduplication by error message if it is present
scope.setFingerprint([err.message])
}
Sentry.captureException(err)
}
if (err.statusCode) {
scope.setExtra('statusCode', err.statusCode)
}
module.exports = {
captureException
if (res && res.statusCode) {
scope.setExtra('statusCode', res.statusCode)
}
if (process.browser) {
scope.setTag('ssr', false)
scope.setExtra('query', query)
scope.setExtra('pathname', pathname)
// On client-side we use js-cookie package to fetch it
const sessionId = Cookie.get('sid')
if (sessionId) {
scope.setUser({ id: sessionId })
}
} else {
scope.setTag('ssr', true)
scope.setExtra('url', req.url)
scope.setExtra('method', req.method)
scope.setExtra('headers', req.headers)
scope.setExtra('params', req.params)
scope.setExtra('query', req.query)
// On server-side we take session cookie directly from request
if (req.cookies.sid) {
scope.setUser({ id: req.cookies.sid })
}
}
if (errorInfo) {
Object.keys(errorInfo).forEach(key => scope.setExtra(key, errorInfo[key]))
}
})
return Sentry.captureException(err)
}
}
}
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