Unverified Commit 6aef4b84 authored by Weston Thayer's avatar Weston Thayer Committed by GitHub

Update with-sentry example to show how to track API routes + bug fixes (#16484)

## New features

- Example of how to use `Sentry.captureException()` in API routes https://github.com/vercel/next.js/commit/5a35982717bc7f916022dd713b3b1f9e0921d503

## Bug fixes

- Server-side source maps now work in Sentry when deployed to Vercel https://github.com/vercel/next.js/commit/629a9ed5048629dc12670ef457fe6efaa2e8d3b6
- If uploading source maps, `Sentry.init()` now sets the `release`, so that exceptions are correctly associated with the source maps in that release

## Open issues

### `_error.js` is unused for `getServerSideProps` errors when deployed to Vercel

Instead of rendering this example's overridden `_error.js` (like it does when testing locally with `NODE_ENV='production'`), when deployed to Vercel and an Error is thrown from `getServerSideProps`, this page is shown:

![Screenshot of Vercel Application Error page](https://user-images.githubusercontent.com/709153/90968889-aa3c3d00-e4a6-11ea-9eff-fafee3d1ff33.png)

This confuses me because the Error is still successfully sent to Sentry, but I would've expected it to be sent by the call to `Sentry.captureException()` in `_error.js`. I'm not sure why it works.

### API test 2 & 3 don't work in the "server" build config

They don't work when deployed to Vercel in the "serverless" config either, but that's expected because there aren't any handlers to flush the Sentry queue. I can't figure out why they don't work in the long-lived "server" config.
parent 5aa7606a
...@@ -4,3 +4,18 @@ NEXT_PUBLIC_SENTRY_DSN= ...@@ -4,3 +4,18 @@ NEXT_PUBLIC_SENTRY_DSN=
# SENTRY_ORG= # SENTRY_ORG=
# SENTRY_PROJECT= # SENTRY_PROJECT=
# SENTRY_AUTH_TOKEN= # SENTRY_AUTH_TOKEN=
#
# For sourcemaps to work with server-side exceptions, the file path of the
# uploaded .map file needs to match the file paths in Error.stack. In Node.js,
# Error.stack file paths are absolute. Since the .map files we upload to Sentry
# have relative paths (~/_next), Error.stack needs to be rewritten to also use
# relative paths, which is handled in Sentry.init via Sentry's RewriteFrames
# integration.
#
# Normally, the root directory could be detected with __dirname, but __dirname
# isn't yet supported in Vercel serverless functions:
# https://github.com/vercel/next.js/issues/8251
#
# To work around this issue, provide the root directory containing Next.js's
# build output here. In the Vercel environment, this is /var/task/.
# NEXT_PUBLIC_SENTRY_SERVER_ROOT_DIR=
...@@ -4,7 +4,8 @@ This is an example showing how to use [Sentry](https://sentry.io) to catch & rep ...@@ -4,7 +4,8 @@ This is an example showing how to use [Sentry](https://sentry.io) to catch & rep
- `_app.js` renders on both the server and client. It initializes Sentry to catch any unhandled exceptions - `_app.js` renders on both the server and client. It initializes Sentry to catch any unhandled exceptions
- `_error.js` is rendered by Next.js while handling certain types of exceptions for you. It is overridden so those exceptions can be passed along to Sentry - `_error.js` is rendered by Next.js while handling certain types of exceptions for you. It is overridden so those exceptions can be passed along to Sentry
- `next.config.js` enables source maps in production for Sentry and swaps out `@sentry/node` for `@sentry/browser` when building the client bundle - Each API route also initializes Sentry, so it can work independently in the "serverless" build config
- `next.config.js` enables source maps in production, uploads them to a new Sentry release, and swaps out `@sentry/node` for `@sentry/browser` when building the client bundle
## Deploy your own ## Deploy your own
...@@ -34,7 +35,7 @@ cp .env.local.example .env.local ...@@ -34,7 +35,7 @@ cp .env.local.example .env.local
Next, Copy your Sentry DSN. You can get it from the settings of your project in **Client Keys (DSN)**. Then, copy the string labeled **DSN** and set it as the value for `NEXT_PUBLIC_SENTRY_DSN` inside `.env.local` Next, Copy your Sentry DSN. You can get it from the settings of your project in **Client Keys (DSN)**. Then, copy the string labeled **DSN** and set it as the value for `NEXT_PUBLIC_SENTRY_DSN` inside `.env.local`
> **Note:** Error tracking is disabled in development mode using the `NODE_ENV` environment variable. To change this behavior, remove the `enabled` property from the `Sentry.init()` call inside your `_app.js` file. > **Note:** Error tracking is disabled in development mode using the `NODE_ENV` environment variable. To change this behavior, remove the `enabled` property from the `Sentry.init()` call inside your `utils/sentry.js` file.
### Step 2. Run Next.js in development mode ### Step 2. Run Next.js in development mode
...@@ -54,7 +55,7 @@ Your app should be up and running on [http://localhost:3000](http://localhost:30 ...@@ -54,7 +55,7 @@ Your app should be up and running on [http://localhost:3000](http://localhost:30
#### Using Vercel #### Using Vercel
You will need to install and configure the [Sentry Vercel integration](https://docs.sentry.io/workflow/integrations/vercel). After you've completed the project linking step, all the needed environment variables will be set in your Vercel project. You will need to install and configure the [Sentry Vercel integration](https://docs.sentry.io/workflow/integrations/vercel). After you've completed the project linking step, all the needed environment variables will be set in your Vercel project, with the exception of `NEXT_PUBLIC_SENTRY_SERVER_ROOT_DIR`, which should be set to `/var/task/`.
> **Note:** A Vercel project connected to a [Git integration](https://vercel.com/docs/v2/platform/deployments#git-integration) is required before adding the Sentry integration. > **Note:** A Vercel project connected to a [Git integration](https://vercel.com/docs/v2/platform/deployments#git-integration) is required before adding the Sentry integration.
...@@ -65,6 +66,7 @@ You will need to install and configure the [Sentry Vercel integration](https://d ...@@ -65,6 +66,7 @@ You will need to install and configure the [Sentry Vercel integration](https://d
3. Save your git provider's commit SHA as either `VERCEL_GITHUB_COMMIT_SHA`, `VERCEL_GITLAB_COMMIT_SHA`, or `VERCEL_BITBUCKET_COMMIT_SHA` environment variable in `.env.local`. 3. Save your git provider's commit SHA as either `VERCEL_GITHUB_COMMIT_SHA`, `VERCEL_GITLAB_COMMIT_SHA`, or `VERCEL_BITBUCKET_COMMIT_SHA` environment variable in `.env.local`.
4. Create an auth token in Sentry. The recommended way to do this is by creating a new internal integration for your organization. To do so, go into **Settings > Developer Settings > New internal integration**. After the integration is created, copy the Token. 4. Create an auth token in Sentry. The recommended way to do this is by creating a new internal integration for your organization. To do so, go into **Settings > Developer Settings > New internal integration**. After the integration is created, copy the Token.
5. Save the token inside the `SENTRY_AUTH_TOKEN` environment variable in `.env.local`. 5. Save the token inside the `SENTRY_AUTH_TOKEN` environment variable in `.env.local`.
6. Set `NEXT_PUBLIC_SENTRY_SERVER_ROOT_DIR` to the absolute path of the folder the Next.js app is running from
> **Note:** Sourcemap upload is disabled in development mode using the `NODE_ENV` environment variable. To change this behavior, remove the `NODE_ENV === 'production'` check from your `next.config.js` file. > **Note:** Sourcemap upload is disabled in development mode using the `NODE_ENV` environment variable. To change this behavior, remove the `NODE_ENV === 'production'` check from your `next.config.js` file.
...@@ -76,7 +78,7 @@ More configurations are available for the [Sentry webpack plugin](https://github ...@@ -76,7 +78,7 @@ More configurations are available for the [Sentry webpack plugin](https://github
- By default, neither sourcemaps nor error tracking are enabled in development mode (see Configuration). - By default, neither sourcemaps nor error tracking are enabled in development mode (see Configuration).
- When enabled in development mode, error handling [works differently than in production](https://nextjs.org/docs/advanced-features/custom-error-page#customizing-the-error-page) as `_error.js` is never actually called. - When enabled in development mode, error handling [works differently than in production](https://nextjs.org/docs/advanced-features/custom-error-page#customizing-the-error-page) as `_error.js` is never actually called.
- The build output will contain warning about unhandled Promise rejections. This is caused by the test pages, and is expected. - The build output will contain warning about unhandled Promise rejections. This is caused by the test pages, and is expected. When deploying to Vercel, "Client Error 1" will actually be sent to Sentry during the build, while that test page is being statically rendered.
- The version of `@zeit/next-source-maps` (`0.0.4-canary.1`) is important and must be specified since it is not yet the default. Otherwise [source maps will not be generated for the server](https://github.com/zeit/next-plugins/issues/377). - The version of `@zeit/next-source-maps` (`0.0.4-canary.1`) is important and must be specified since it is not yet the default. Otherwise [source maps will not be generated for the server](https://github.com/zeit/next-plugins/issues/377).
- Both `@zeit/next-source-maps` and `@sentry/webpack-plugin` are added to dependencies (rather than `devDependencies`) because if used with SSR, these plugins are used during production for generating the source-maps and sending them to sentry. - Both `@zeit/next-source-maps` and `@sentry/webpack-plugin` are added to dependencies (rather than `devDependencies`) because if used with SSR, these plugins are used during production for generating the source-maps and sending them to sentry.
......
...@@ -24,8 +24,11 @@ process.env.SENTRY_DSN = SENTRY_DSN ...@@ -24,8 +24,11 @@ process.env.SENTRY_DSN = SENTRY_DSN
const basePath = '' const basePath = ''
module.exports = withSourceMaps({ module.exports = withSourceMaps({
serverRuntimeConfig: { env: {
rootDir: __dirname, // Make the COMMIT_SHA available to the client so that Sentry events can be
// marked for the release the belong to. It may be undefined if running
// outside of Vercel
NEXT_PUBLIC_COMMIT_SHA: COMMIT_SHA,
}, },
webpack: (config, options) => { webpack: (config, options) => {
// In `pages/_app.js`, Sentry is imported from @sentry/browser. While // In `pages/_app.js`, Sentry is imported from @sentry/browser. While
...@@ -46,6 +49,16 @@ module.exports = withSourceMaps({ ...@@ -46,6 +49,16 @@ module.exports = withSourceMaps({
config.resolve.alias['@sentry/node'] = '@sentry/browser' config.resolve.alias['@sentry/node'] = '@sentry/browser'
} }
// Define an environment variable so source code can check whether or not
// it's running on the server so we can correctly initialize Sentry
config.plugins.push(
new options.webpack.DefinePlugin({
'process.env.NEXT_IS_SERVER': JSON.stringify(
options.isServer.toString()
),
})
)
// When all the Sentry configuration env variables are available/configured // When all the Sentry configuration env variables are available/configured
// The Sentry webpack plugin gets pushed to the webpack plugins to build // The Sentry webpack plugin gets pushed to the webpack plugins to build
// and upload the source maps to sentry. // and upload the source maps to sentry.
......
...@@ -8,10 +8,10 @@ ...@@ -8,10 +8,10 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@sentry/browser": "^5.15.5", "@sentry/browser": "^5.21.3",
"@sentry/integrations": "5.20.1", "@sentry/integrations": "^5.21.3",
"@sentry/node": "^5.15.5", "@sentry/node": "^5.21.3",
"@sentry/webpack-plugin": "^1.11.1", "@sentry/webpack-plugin": "^1.12.1",
"@zeit/next-source-maps": "0.0.4-canary.1", "@zeit/next-source-maps": "0.0.4-canary.1",
"next": "latest", "next": "latest",
"react": "^16.8.6", "react": "^16.8.6",
......
import Error from 'next/error' import Error from 'next/error'
export default function NotFound() { export default function NotFound() {
// Opinionated: do not record an exception in Sentry for 404
return <Error statusCode={404} /> return <Error statusCode={404} />
} }
import * as Sentry from '@sentry/node' import { init } from '../utils/sentry'
import { RewriteFrames } from '@sentry/integrations'
import getConfig from 'next/config'
if (process.env.NEXT_PUBLIC_SENTRY_DSN) { init()
const config = getConfig()
const distDir = `${config.serverRuntimeConfig.rootDir}/.next`
Sentry.init({
enabled: process.env.NODE_ENV === 'production',
integrations: [
new RewriteFrames({
iteratee: (frame) => {
frame.filename = frame.filename.replace(distDir, 'app:///_next')
return frame
},
}),
],
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
})
}
export default function App({ Component, pageProps, err }) { export default function App({ Component, pageProps, err }) {
// Workaround for https://github.com/vercel/next.js/issues/8592 // Workaround for https://github.com/vercel/next.js/issues/8592
......
...@@ -7,6 +7,7 @@ const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => { ...@@ -7,6 +7,7 @@ const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => {
// https://github.com/vercel/next.js/issues/8592. As a workaround, we pass // https://github.com/vercel/next.js/issues/8592. As a workaround, we pass
// err via _app.js so it can be captured // err via _app.js so it can be captured
Sentry.captureException(err) Sentry.captureException(err)
// Flushing is not required in this case as it only happens on the client
} }
return <NextErrorComponent statusCode={statusCode} /> return <NextErrorComponent statusCode={statusCode} />
...@@ -35,13 +36,13 @@ MyError.getInitialProps = async ({ res, err, asPath }) => { ...@@ -35,13 +36,13 @@ MyError.getInitialProps = async ({ res, err, asPath }) => {
// Boundary. Read more about what types of exceptions are caught by Error // Boundary. Read more about what types of exceptions are caught by Error
// Boundaries: https://reactjs.org/docs/error-boundaries.html // Boundaries: https://reactjs.org/docs/error-boundaries.html
if (res?.statusCode === 404) {
// Opinionated: do not record an exception in Sentry for 404
return { statusCode: 404 }
}
if (err) { if (err) {
Sentry.captureException(err) Sentry.captureException(err)
// Flushing before returning is necessary if deploying to Vercel, see
// https://vercel.com/docs/platform/limits#streaming-responses
await Sentry.flush(2000) await Sentry.flush(2000)
return errorInitialProps return errorInitialProps
} }
......
import { init } from '../../utils/sentry'
init()
const doAsyncWork = () => Promise.reject(new Error('API Test 1'))
doAsyncWork()
export default async function handler(req, res) {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
import { init } from '../../utils/sentry'
init()
function work() {
throw new Error('API Test 2')
}
work()
export default async function handler(req, res) {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
import { init } from '../../utils/sentry'
init()
function work() {
throw new Error('API Test 3')
}
export default async function handler(req, res) {
work()
res.statusCode = 200
res.json({ name: 'John Doe' })
}
import * as Sentry from '@sentry/node'
import { init } from '../../utils/sentry'
init()
export default async function handler(req, res) {
try {
throw new Error('API Test 4')
} catch (error) {
Sentry.captureException(error)
}
// Flushing before returning is necessary if deploying to Vercel, see
// https://vercel.com/docs/platform/limits#streaming-responses
await Sentry.flush(2000)
res.statusCode = 200
res.json({ name: 'John Doe' })
}
...@@ -16,35 +16,82 @@ const Index = () => ( ...@@ -16,35 +16,82 @@ const Index = () => (
Read more Read more
</a> </a>
</p> </p>
<ul> <ol>
<li>Server exceptions</li> <li>
<ul> API route exceptions (note that 1-3 are not expected to work if deployed
to Vercel yet)
</li>
<ol>
<li> <li>
getServerSideProps throws an Error. This should cause _error.js to API has a top-of-module Promise that rejects, but its result is not
render and record Error('Server Test 1') in Sentry.{' '} awaited. Sentry should record Error('API Test 1').{' '}
<a href="/server/test1" target="_blank"> <a href="/api/test1" target="_blank">
Open in a new tab
</a>
</li>
<li>
API has a top-of-module exception. Sentry should record Error('API
Test 2').{' '}
<a href="/api/test2" target="_blank">
Open in a new tab
</a>
</li>
<li>
API has has an exception in its request handler. Sentry should record
Error('API Test 3').{' '}
<a href="/api/test3" target="_blank">
Open in a new tab Open in a new tab
</a> </a>
</li> </li>
<li>
API uses a try/catch to handle an exception and records it. Sentry
should record Error('API Test 4').{' '}
<a href="/api/test4" target="_blank">
Open in a new tab
</a>
</li>
</ol>
<li>SSR exceptions</li>
<ol>
<li>
getServerSideProps throws an Error. This should cause _error.js to
render and record Error('SSR Test 1') in Sentry.{' '}
<a href="/ssr/test1" target="_blank">
Open in a new tab
</a>{' '}
or{' '}
<Link href="/ssr/test1">
<a>Perform client side navigation</a>
</Link>
</li>
<li> <li>
getServerSideProps returns a Promise that rejects. This should cause getServerSideProps returns a Promise that rejects. This should cause
_error.js to render and record Error('Server Test 2') in Sentry.{' '} _error.js to render and record Error('SSR Test 2') in Sentry.{' '}
<a href="/server/test2" target="_blank"> <a href="/ssr/test2" target="_blank">
Open in a new tab Open in a new tab
</a> </a>
</li> </li>
<li> <li>
getServerSideProps calls a Promise that rejects, but does not handle getServerSideProps calls a Promise that rejects, but does not handle
the rejection or await its result (returning synchronously). Sentry the rejection or await its result (returning synchronously). Sentry
should record Error('Server Test 3').{' '} should record Error('SSR Test 3'), but <strong>will not</strong> when
<a href="/server/test3" target="_blank"> deployed to Vercel because the serverless function will already have
exited.{' '}
<a href="/ssr/test3" target="_blank">
Open in a new tab
</a>
</li>
<li>
getServerSideProps manually captures an exception from a try/catch.
This should record Error('SSR Test 4') in Sentry.{' '}
<a href="/ssr/test4" target="_blank">
Open in a new tab Open in a new tab
</a> </a>
</li> </li>
</ul> </ol>
<li>Client exceptions</li> <li>Client exceptions</li>
<ul> <ol>
<li> <li>
There is a top-of-module Promise that rejects, but its result is not There is a top-of-module Promise that rejects, but its result is not
awaited. Sentry should record Error('Client Test 1').{' '} awaited. Sentry should record Error('Client Test 1').{' '}
...@@ -103,8 +150,8 @@ const Index = () => ( ...@@ -103,8 +150,8 @@ const Index = () => (
Open in a new tab Open in a new tab
</a> </a>
</li> </li>
</ul> </ol>
</ul> </ol>
</div> </div>
) )
......
const Test1 = () => <h1>Server Test 1</h1> const Test1 = () => <h1>SSR Test 1</h1>
export function getServerSideProps() { export function getServerSideProps() {
throw new Error('Server Test 1') throw new Error('SSR Test 1')
} }
export default Test1 export default Test1
const Test2 = () => <h1>Server Test 2</h1> const Test2 = () => <h1>SSR Test 2</h1>
export async function getServerSideProps() { export async function getServerSideProps() {
throw new Error('Server Test 2') throw new Error('SSR Test 2')
} }
export default Test2 export default Test2
const Test3 = () => <h1>Server Test 3</h1> const Test3 = () => <h1>SSR Test 3</h1>
export async function getServerSideProps() { export async function getServerSideProps() {
const doAsyncWork = () => Promise.reject(new Error('Server Test 3')) const doAsyncWork = () => Promise.reject(new Error('SSR Test 3'))
doAsyncWork() doAsyncWork()
......
import * as Sentry from '@sentry/node'
const Test4 = () => <h1>SSR Test 4</h1>
export async function getServerSideProps() {
try {
throw new Error('SSR Test 4')
} catch (error) {
Sentry.captureException(error)
// Flushing before returning is necessary if deploying to Vercel, see
// https://vercel.com/docs/platform/limits#streaming-responses
await Sentry.flush(2000)
}
return { props: {} }
}
export default Test4
import * as Sentry from '@sentry/node'
import { RewriteFrames } from '@sentry/integrations'
export const init = () => {
if (process.env.NEXT_PUBLIC_SENTRY_DSN) {
const integrations = []
if (
process.env.NEXT_IS_SERVER === 'true' &&
process.env.NEXT_PUBLIC_SENTRY_SERVER_ROOT_DIR
) {
// For Node.js, rewrite Error.stack to use relative paths, so that source
// maps starting with ~/_next map to files in Error.stack with path
// app:///_next
integrations.push(
new RewriteFrames({
iteratee: (frame) => {
frame.filename = frame.filename.replace(
process.env.NEXT_PUBLIC_SENTRY_SERVER_ROOT_DIR,
'app:///'
)
frame.filename = frame.filename.replace('.next', '_next')
return frame
},
})
)
}
Sentry.init({
enabled: process.env.NODE_ENV === 'production',
integrations,
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
release: process.env.NEXT_PUBLIC_COMMIT_SHA,
})
}
}
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