Skip to content

Latest commit

 

History

History
391 lines (286 loc) · 16.9 KB

manual-setup.mdx

File metadata and controls

391 lines (286 loc) · 16.9 KB
title sidebar_order description
Manual Setup
1
Learn how to set up the SDK manually.

If you can't (or prefer not to) run the configuration step, you can follow the instructions below to configure your application.

Create Initialization Config Files

Create two files in the root directory of your project, sentry.client.config.js and sentry.server.config.js. In these files, add your initialization code for the client-side SDK and server-side SDK, respectively. We've included some examples below.

For each configuration:

import * as Sentry from "@sentry/nextjs";

const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;

Sentry.init({
  dsn: SENTRY_DSN || "___PUBLIC_DSN___",
  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
  // ...
  // Note: if you want to override the automatic release value, do not set a
  // `release` value here - use the environment variable `SENTRY_RELEASE`, so
  // that it will also get attached to your source maps
});
import * as Sentry from "@sentry/nextjs";

const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;

Sentry.init({
  dsn: SENTRY_DSN || "___PUBLIC_DSN___",
  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
  // ...
  // Note: if you want to override the automatic release value, do not set a
  // `release` value here - use the environment variable `SENTRY_RELEASE`, so
  // that it will also get attached to your source maps
});

You can include your DSN directly in these two files, or provide it in either of two environment variables, SENTRY_DSN or NEXT_PUBLIC_SENTRY_DSN.

Create a Custom _error Page

In serverless deployment environments, including Vercel, the Next.js server runs in a "minimal" mode to reduce serverless function size. As a result, some of the auto-instrumentation done by @sentry/nextjs doesn't run, and therefore certain errors aren't caught. In addition, Next.js includes a custom error boundary which will catch certain errors before they bubble up to our handlers.

To capture these errors in Sentry, you can use the Next.js error page customization option. To do this, create pages/_error.js, and include the following:

/**
 * NOTE: This requires `@sentry/nextjs` version 7.3.0 or higher.
 *
 * This page is loaded by Nextjs:
 *  - on the server, when data-fetching methods throw or reject
 *  - on the client, when `getInitialProps` throws or rejects
 *  - on the client, when a React lifecycle method throws or rejects, and it's
 *    caught by the built-in Nextjs error boundary
 *
 * See:
 *  - https://nextjs.org/docs/basic-features/data-fetching/overview
 *  - https://nextjs.org/docs/api-reference/data-fetching/get-initial-props
 *  - https://reactjs.org/docs/error-boundaries.html
 */

import * as Sentry from "@sentry/nextjs";
import NextErrorComponent from "next/error";

const CustomErrorComponent = props => {
  // If you're using a Nextjs version prior to 12.2.1, uncomment this to
  // compensate for https://github.com/vercel/next.js/issues/8592
  // Sentry.captureUnderscoreErrorException(props);

  return <NextErrorComponent statusCode={props.statusCode} />;
};

CustomErrorComponent.getInitialProps = async contextData => {
  // In case this is running in a serverless function, await this in order to give Sentry
  // time to send the error before the lambda exits
  await Sentry.captureUnderscoreErrorException(contextData);

  // This will contain the status code of the response
  return NextErrorComponent.getInitialProps(contextData);
};

export default CustomErrorComponent;
/**
 * NOTE: This requires `@sentry/nextjs` version 7.3.0 or higher.
 *
 * This page is loaded by Nextjs:
 *  - on the server, when data-fetching methods throw or reject
 *  - on the client, when `getInitialProps` throws or rejects
 *  - on the client, when a React lifecycle method throws or rejects, and it's
 *    caught by the built-in Nextjs error boundary
 *
 * See:
 *  - https://nextjs.org/docs/basic-features/data-fetching/overview
 *  - https://nextjs.org/docs/api-reference/data-fetching/get-initial-props
 *  - https://reactjs.org/docs/error-boundaries.html
 */

import * as Sentry from "@sentry/nextjs";
import type { NextPage } from "next";
import type { ErrorProps } from "next/error";
import NextErrorComponent from "next/error";

const CustomErrorComponent: NextPage<ErrorProps> = props => {
  // If you're using a Nextjs version prior to 12.2.1, uncomment this to
  // compensate for https://github.com/vercel/next.js/issues/8592
  // Sentry.captureUnderscoreErrorException(props);

  return <NextErrorComponent statusCode={props.statusCode} />;
};

CustomErrorComponent.getInitialProps = async contextData => {
  // In case this is running in a serverless function, await this in order to give Sentry
  // time to send the error before the lambda exits
  await Sentry.captureUnderscoreErrorException(contextData);

  // This will contain the status code of the response
  return NextErrorComponent.getInitialProps(contextData);
};

export default CustomErrorComponent;

Extend Next.js Configuration

Use withSentryConfig to extend the default Next.js usage of Webpack. This will do two things:

  • Automatically call the code in sentry.server.config.js and sentry.client.config.js, at server start up and client page load, respectively. Using withSentryConfig is the only way to guarantee that the SDK is initialized early enough to catch all errors and start performance monitoring.
  • Generate and upload source maps to Sentry, so that your stacktraces contain original, demangled code.

Include the following in your next.config.js:

// This file sets a custom webpack configuration to use your Next.js app
// with Sentry.
// https://nextjs.org/docs/api-reference/next.config.js/introduction
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

const { withSentryConfig } = require("@sentry/nextjs");

const moduleExports = {
  // your existing module.exports

  // Optional build-time configuration options
  sentry: {
    // See the sections below for information on the following options:
    //   'Configure Source Maps':
    //     - disableServerWebpackPlugin
    //     - disableClientWebpackPlugin
    //     - hideSourceMaps
    //     - widenClientFileUpload
    //   'Configure Legacy Browser Support':
    //     - transpileClientSDK
    //   'Configure Serverside Auto-instrumentation':
    //     - autoInstrumentServerFunctions
    //     - excludeServerRoutes
  },
};

const sentryWebpackPluginOptions = {
  // Additional config options for the Sentry Webpack plugin. Keep in mind that
  // the following options are set automatically, and overriding them is not
  // recommended:
  //   release, url, org, project, authToken, configFile, stripPrefix,
  //   urlPrefix, include, ignore

  silent: true, // Suppresses all logs
  // For all available options, see:
  // https://github.com/getsentry/sentry-webpack-plugin#options.
};

// Make sure adding Sentry options is the last code to run before exporting, to
// ensure that your source maps include changes from all other Webpack plugins
module.exports = withSentryConfig(moduleExports, sentryWebpackPluginOptions);

@sentry/nextjs does not support configurations with the serverless target. To use the SDK in serverless environments, switch to using the experimental-serverless-trace target, which is recommended by the Next.js maintainers for apps using Next.js 10 or Next.js 11.

Make sure to add the Sentry config last; otherwise, the source maps the plugin receives may not be final.

Configure Source Maps

By default, withSentryConfig will add an instance of SentryWebpackPlugin to the webpack plugins, for both server and client builds. This means that when you run a production build (next build), sentry-cli will automatically detect and upload your source files, source maps, and bundles to Sentry, so that your stacktraces can be demangled. (This behavior is disabled when running the dev server (next dev), because otherwise the full upload process would reoccur on each file change.)

To configure the plugin, pass a sentryWebpackPluginOptions argument to withSentryConfig, as seen in the example above. All available options are documented here.

Disable SentryWebpackPlugin

If you want or need to handle source map uploading separately, the plugin can be disabled for either the server or client build process. To do this, add a sentry object to moduleExports above, and set the relevant options there:

const moduleExports = {
  sentry: {
    disableServerWebpackPlugin: true,
    disableClientWebpackPlugin: true,
  },
};

If you disable the plugin for both server and client builds, it's safe to omit the sentryWebpackPluginOptions parameter from your withSentryConfig call:

module.exports = withSentryConfig(moduleExports);

In that case you can also skip the sentry-cli configuration step below.

Use hidden-source-map

(New in version 6.17.1, will default to true in 8.0.0 and beyond.)

Depending on your deployment setup, adding sentry/nextjs to your app may cause your source code to be visible in browser devtools when it wasn't before. (This happens because of the default behavior of Webpack's source-map built-in devtool.) To prevent this, you can use hidden-source-map rather than source-map, which will prevent your built files from containing a sourceMappingURL comment, thus making sourcemaps invisible to the browser. To use hidden-source-map, add a sentry object to moduleExports above, and set the hideSourceMaps option to true:

const moduleExports = {
  sentry: {
    hideSourceMaps: true,
  },
};

Note that this only applies to client-side builds, and requires the SentryWebpackPlugin to be enabled. This option will default to true starting in version 8.0.0. See https://webpack.js.org/configuration/devtool/ for more information.

Widen the Upload Scope

(New in version 6.19.1)

If you find that there are in-app frames in your client-side stack traces that aren't getting source-mapped even when most others are, it's likely because they are from files in static/chunks/ rather than static/chunks/pages/. By default, such files aren't uploaded because the majority of the files in static/chunks/ only contain Next.js or third-party code, and are named in such a way that it's hard to distinguish between relevant files (ones containing your code) and irrelevant ones.

To upload all of the files in static/chunks/ anyway, add a sentry object to moduleExports above, and set the widenClientFileUpload option to true:

const moduleExports = {
  sentry: {
    widenClientFileUpload: true,
  },
};

Configure sentry-cli

The SentryWebpackPlugin uses sentry-cli to manage releases and source maps, which can be configured in one of two ways - using configuration files, or with environment variables - both of which are discussed below. For full details, see the CLI configuration docs.

If you choose to combine the two approaches, the environment variables will take precedence over values set in the configuration files. One common approach is to set sensitive data (like tokens) in the environment and include everything else in the configuration files added to your VCS.

The URL, organization, and project properties identify your organization and project, and the auth token authenticates your user account.

Use Configuration Files

You should commit all the properties to your VCS, except the auth token. You can accomplish this by using two files: sentry.properties including the properties of your organization and project, and .sentryclirc including your auth token. This is the approach taken by the wizard and it allows you to commit the former while ignoring the latter in your VCS.

Here is an example:

defaults.url=https://sentry.io/
defaults.org=___ORG_SLUG___
defaults.project=___PROJECT_SLUG___
# cli.executable=../path/to/bin/sentry-cli

Add the token to .sentryclirc:

[auth]
token=___TOKEN___

And don't forget to ignore .sentryclirc in your VCS.

Use Environment Variables

Alternatively, the cli can be configured using environment variables.

Property name Environment variable
defaults.url SENTRY_URL
defaults.org SENTRY_ORG
defaults.project SENTRY_PROJECT
auth.token SENTRY_AUTH_TOKEN

Configure Legacy Browser Support

(New in version 7.8.0)

The @sentry/nextjs SDK is designed to run in browsers which support ES6 (and certain ES6+ language features like object spread). If you need to support older browsers, and have configured Next.js to down-compile your code, you can apply the same down-compilation to the injected SDK code by using the transpileClientSDK option in your next.config.js:

const moduleExports = {
  sentry: {
    transpileClientSDK: true,
  },
};

(This assumes you are using the next.config.js setup shown above.)

Configure Server-side Auto-instrumentation

The SDK will automatically instrument API routes and server-side Next.js data fetching methods with error and performance monitoring.

Disable API Route and Data Fetching Auto-instrumentation Entirely

(New in version 7.14.0)

To disable the automatic instrumentation of API route handlers and server-side data fetching functions, set the autoInstrumentServerFunctions to false.

const moduleExports = {
  sentry: {
    autoInstrumentServerFunctions: false,
  },
};

With this option, under the hood, the SDK is using a Webpack loader to wrap all your API route handlers and data fetching methods.

Opt In to Auto-instrumentation on Specific Routes

(New in version 7.14.0)

If the automatic instrumentation doesn't work for your use case, you can turn it off globally and choose to only wrap specific API route handlers or data fetching functions instead.

For API routes, use the withSentry function:

import { withSentry } from "@sentry/nextjs";

const handler = (req, res) => {
  res.status(200).json({ name: "John Doe" });
};

export default withSentry(handler);
import type { NextApiRequest, NextApiResponse } from "next"
import { withSentry } from "@sentry/nextjs";

const handler = (req: NextApiRequest, res: NextApiResponse) => {
  res.status(200).json({ name: "John Doe" });
};

export default withSentry(handler);

For data fetching methods, use the following functions:

  • withSentryServerSideGetInitialProps for getInitialProps
  • withSentryGetServerSideProps for getServerSideProps
  • withSentryGetStaticProps for getStaticProps
  • withSentryServerSideErrorGetInitialProps for getInitialProps in custom Error pages
  • withSentryServerSideAppGetInitialProps for getInitialProps in custom App components
  • withSentryServerSideDocumentGetInitialProps for getInitialProps in custom Document components

Opt Out of Auto-instrumentation on Specific Routes

(New in version 7.20.0)

If you want auto-instrumenatation to apply by default, but want to exclude certain routes, use the excludeServerRoutes option in the sentry object in your next.config.js:

const moduleExports = {
  sentry: {
    excludeServerRoutes: [
      "/some/excluded/route",
      "/excluded/route/with/[parameter]",
      /^\/route\/beginning\/with\/some\/prefix/,
      /\/routeContainingASpecificPathSegment\/?/,
    ],
  },
};

Excluded routes can be specified either as regexes or strings. When using a string, make sure that it matches the route exactly, and has a leading slash but no trailing one.