【问题标题】:integrating Sentry in Next.js project在 Next.js 项目中集成 Sentry
【发布时间】:2019-12-03 08:31:36
【问题描述】:

我正在使用带有 AMP 的 Next.js。 这意味着我的代码仅在服务器上运行。没有客户端代码。

我正在尝试整合@sentry/node 但是,虽然我将这一行单独添加到 index.js in /pages const Sentry = require('@sentry/node');

构建失败并出现以下错误:

[ wait ]  compiling ...
[ error ] ./node_modules/@sentry/node/esm/integrations/console.js
Module not found: Can't resolve 'console' in '/Users/lirancohen/Projects/amp-app/node_modules/@sentry/node/esm/integrations'

对于理解此问题的任何帮助,我将不胜感激。 使用 next 9.0.1 和 sentry 5.0.5

【问题讨论】:

  • 我面临着完全相同的问题,但我的设置不包括 Next.js 或 AMP,只是一个带有单独 Node.js 服务器的 React 应用程序。

标签: javascript next.js sentry


【解决方案1】:

作为替代方案,您不需要使用@sentry/node。您也可以使用@sentry/browser。查看此link 以查看示例实现。

或者,here 您可以找到与npx create-react-app 一起运行的有据可查的with-sentry 选项。

【讨论】:

    【解决方案2】:

    对于希望使用 Next.js 实现 Sentry 的人,请务必查看 https://github.com/UnlyEd/next-right-now

    最有趣的部分是:

    免责声明:我是该项目的贡献者之一

    请注意,上述链接指向修复提交以避免中断,但您应该考虑查看最新版本。分公司:https://github.com/UnlyEd/next-right-now/blob/v2-mst-aptd-at-lcz-sty/


    utils/sentry.ts

    import { NowRequest } from '@now/node/dist';
    import * as Sentry from '@sentry/node';
    import get from 'lodash.get';
    import { isBrowser } from '@unly/utils';
    
    /**
     * Initialize Sentry and export it.
     *
     * Helper to avoid duplicating the init() call in every /pages/api file.
     * Also used in pages/_app for the client side, which automatically applies it for all frontend pages.
     */
    Sentry.init({
      dsn: process.env.SENTRY_DSN,
      enabled: process.env.NODE_ENV !== 'test',
      environment: process.env.APP_STAGE,
      release: process.env.APP_VERSION_RELEASE,
    });
    
    if (!process.env.SENTRY_DSN && process.env.NODE_ENV !== 'test') {
      // eslint-disable-next-line no-console
      console.error('Sentry DSN not defined');
    }
    
    // Scope configured by default, subsequent calls to "configureScope" will add additional data
    Sentry.configureScope((scope) => { // See https://www.npmjs.com/package/@sentry/node
      scope.setTag('nodejs', process.version);
      scope.setTag('nodejsAWS', process.env.AWS_EXECUTION_ENV || null); // Optional - Available on production environment only
      scope.setTag('memory', process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE || null); // Optional - Available on production environment only
      scope.setTag('runtimeEngine', isBrowser() ? 'browser' : 'server');
      scope.setTag('buildTime', process.env.BUILD_TIME);
    });
    
    /**
     * Configure the Sentry scope by extracting useful tags and context from the given request.
     *
     * @param req
     */
    export const configureReq = (req: NowRequest): void => {
      Sentry.configureScope((scope) => {
        scope.setTag('host', get(req, 'headers.host'));
        scope.setTag('url', get(req, 'url'));
        scope.setTag('method', get(req, 'method'));
        scope.setContext('query', get(req, 'query'));
        scope.setContext('cookies', get(req, 'cookies'));
        scope.setContext('body', get(req, 'body'));
        scope.setContext('headers', get(req, 'headers'));
      });
    };
    
    export default Sentry;
    

    使用示例(pages/_app.tsx):

    import * as Sentry from '@sentry/node';
    import '../utils/sentry';
    
    //...
    
    Sentry.configureScope((scope) => { // See https://www.npmjs.com/package/@sentry/node
      scope.setTag('customer', customerRef);
      scope.setTag('userId', userSession.id);
      scope.setContext('userSession', userSession);
      scope.setContext('cookies', readonlyCookies);
    });
    
    Sentry.addBreadcrumb({ // See https://docs.sentry.io/enriching-error-data/breadcrumbs
      category: fileLabel,
      message: `Preparing app (${isBrowser() ? 'browser' : 'server'})`,
      level: Sentry.Severity.Debug,
    });
    

    Webpack 配置 (next.config.js)

    webpack: (config, { isServer, buildId }) => {
        // Fixes npm packages that depend on `fs` module
        config.node = {
          fs: 'empty',
        };
    
        // XXX See https://github.com/zeit/next.js/blob/canary/examples/with-sentry-simple/next.config.js
        // In `pages/_app.js`, Sentry is imported from @sentry/node. While
        // @sentry/browser will run in a Node.js environment, @sentry/node will use
        // Node.js-only APIs to catch even more unhandled exceptions.
        //
        // This works well when Next.js is SSRing your page on a server with
        // Node.js, but it is not what we want when your client-side bundle is being
        // executed by a browser.
        //
        // Luckily, Next.js will call this webpack function twice, once for the
        // server and once for the client. Read more:
        // https://nextjs.org/docs#customizing-webpack-config
        //
        // So ask Webpack to replace @sentry/node imports with @sentry/browser when
        // building the browser's bundle
        if (!isServer) {
          config.resolve.alias['@sentry/node'] = '@sentry/browser';
        }
    
        return config;
      },
    

    【讨论】:

    【解决方案3】:

    确保在需要后调用该函数...

    const withSourceMaps = require('@zeit/next-source-maps')();
                                                            ^^
    

    我遇到了同样的问题,并且为我解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 1970-01-01
      • 2020-08-29
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多