Skip to content

TypeError: withSentryConfig is not a function #5511

Closed

Description

@coreypett33

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which package are you using?

@sentry/nextjs

SDK Version

7.8.1

Framework Version

"react": "^17.0.2", "next": "^11.1.2",

Link to Sentry event

No response

Steps to Reproduce

  1. add sentry to nextjs application.
    https://docs.sentry.io/platforms/javascript/guides/nextjs/
  2. update 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
  reactStrictMode: true,
  swcMinify: true,
};

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);

  1. run yarn dev

Expected Result

App should start

Actual Result

localhost:3001 shows the following error in chrome.
Screen Shot 2022-08-02 at 5 40 42 AM

Terminal does not show the error.

Screen Shot 2022-08-02 at 5 52 03 AM

Activity

  1. lobsterkatie commented on Aug 2, 2022

    @lobsterkatie
    Member

    Hi, @coreypett33.

    I've tried and can't replicate this behavior. Can you please provide a small repro app?

  2. github-actions commented on Aug 24, 2022

    @github-actions
    Contributor

    This issue has gone three weeks without activity. In another week, I will close it.

    But! If you comment or otherwise update it, I will reset the clock, and if you label it Status: Backlog or Status: In Progress, I will leave it alone ... forever!


    "A weed is but an unloved flower." ― Ella Wheeler Wilcox 🥀

  3. bramski commented on Oct 25, 2022

    @bramski

    I immediately hit this error using the sentry wizard. Something is broken with it.

  4. BARK-RMILLER commented on Oct 31, 2022

    @BARK-RMILLER

    For future people who encounter this error: I fixed this by converting my next.config.js file into next.config.mjs. This allowed me to do the sentry import like so: const { withSentryConfig } = await import('@sentry/nextjs');

    Then export the config like so: export default withSentryConfig(nextConfig, sentryWebpackPluginOptions);

    The issue seems to be that the Sentry configuration requires that you do a module import, which isn't supported by a regular next.config.js. See the next.js docs on the config file here.

  5. Geczy commented on Jan 20, 2023

    @Geczy

    const { withSentryConfig } = await import('@sentry/nextjs');

    this didnt fix the issue for me

  6. prateekjain98 commented on Mar 15, 2023

    @prateekjain98

    I'm trying to upgrade from 7.30.0 to 7.43.0 but when I try to upgrade, it throws this error while building.

  7. 18 remaining items

  8. lforst commented on May 15, 2023

    @lforst
    Contributor

    @ianbayne can you try wiping your node_modules and reinstalling them? Thanks.

  9. ianbayne commented on May 16, 2023

    @ianbayne

    Thanks, @lforst.

    Unfortunately even after doing so I still get the same error. Interestingly I notice my local Next server is showing a different error than the browser:

    wait  - compiling...
    error - (middleware)/src/pages/_middleware.ts (17:0) @ <unknown>
    TypeError: Cannot read properties of undefined (reading 'getInitialProps')
      15 | const pageComponent = userPageModule.default;
      16 | 
    > 17 | const origGetInitialProps = pageComponent.getInitialProps;
      18 | const origGetStaticProps = userPageModule.getStaticProps;
      19 | const origGetServerSideProps = userPageModule.getServerSideProps;
    

    The content of my _middleware.ts file is:

    import { NextRequest, NextResponse } from 'next/server';
    
    // Regex to check whether something has an extension, e.g. .jpg
    const PUBLIC_FILE = /\.(.*)$/;
    
    const countries = ['en-US', 'fr', 'de', 'it'];
    
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    export const middleware = (request: NextRequest) => {
      const { nextUrl, headers } = request;
      const url = nextUrl.clone();
    
      const language =
        headers
          .get('accept-language')
          ?.split(',')?.[0]
          .split('-')?.[0]
          .toLowerCase() || 'en-US';
    
      try {
        // Early return if it is a public file such as an image
        if (PUBLIC_FILE.test(nextUrl.pathname)) {
          return undefined;
        }
        // Early return if this is an api route
        if (nextUrl.pathname.includes('/api')) {
          return undefined;
        }
    
        if (nextUrl.pathname === '/' && nextUrl.locale === '__default') {
          url.pathname = countries.includes(language) ? `/${language}` : `/en-US`;
          return NextResponse.redirect(url);
        }
    
        // If everything else falls through continue on with response as normal
        return undefined;
      } catch (error) {
        console.log(error);
      }
    };

    and the file where getInitialProps() is used:

    // src/pages/_document.tsx
    
    import Document, {
      Html,
      Head,
      Main,
      NextScript,
      DocumentContext,
      DocumentInitialProps,
    } from 'next/document';
    
    class MyDocument extends Document {
      static async getInitialProps(
        ctx: DocumentContext
      ): Promise<DocumentInitialProps> {
        const initialProps = await Document.getInitialProps(ctx);
    
        return initialProps;
      }
    
      render(): JSX.Element {
        return (
          <Html>
            <Head />
            <body>
              <Main />
              <NextScript />
            </body>
          </Html>
        );
      }
    }
    
    export default MyDocument;

    I've looked through the Sentry GitHub issues on getInitialProps() but don't see anything applicable...

  10. lforst commented on May 16, 2023

    @lforst
    Contributor

    @ianbayne Can you try migrating your _middleware.ts from the legacy version ("_middleware") to the current version ("middleware.ts") - https://nextjs.org/docs/pages/building-your-application/routing/middleware#convention

  11. ianbayne commented on May 17, 2023

    @ianbayne

    Thanks for the response, @lforst. I was actually able to resolve the issue I was having by doing both of the following:

    1. We had a component file that was importing the Next config in order to get access to the i18n object / locales. Instead of doing that, I used Next's useRouter() hook to access locales as shown in Next's docs here. I'm assuming the Next config should never be imported into another file; is this correct?
    2. Updating the Sentry section of my Next config to have autoInstrumentServerFunctions set to false. It seems with it set to true you can't have named exports from the middleware file. (Alternatively, I could of course have changed the middleware file to have a default export.) I discovered this from issue @sentry/next.js 7.31 autoinstrumentation breaks middleware with named export #6815.

    Thanks again for all your help!

  12. lforst commented on May 18, 2023

    @lforst
    Contributor

    @ianbayne Thanks for giving an update! We didn't consider that people may import the next config from components. I think this is something we should fix (by exporting the function on the clientside but making it a noop).

    As for the middleware. I actually wanna discourage you from setting autoInstrumentServerFunctions to false, this will disable a huge chunk of features in the SDK unless you wrap everything manually. It should honestly be enough if you rename/move src/pages/_middleware.ts to src/middleware.ts. If that won't work with autoInstrumentServerFunctions: true we have something to fix. You're currently using an outdated way of defining middleware which we don't support: https://nextjs.org/docs/messages/middleware-upgrade-guide#how-to-upgrade

  13. ianbayne commented on May 19, 2023

    @ianbayne

    Thanks, @lforst.

    Despite the error message above, my middleware file is indeed located at src/middleware.ts, not src/pages/_middleware.ts. Additionally, the file name is not prefixed with an underscore (I must have gotten confused above by the error message).

    What's more, removing autoInstrumentServerFunctions: false does not seem to impact the functioning of our app. I must have been mistaken about that.

    Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions