Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sentry doesn't work on Next 13.5 #9092

Closed
3 tasks done
RilDev opened this issue Sep 22, 2023 · 49 comments · Fixed by #9100 or #9114
Closed
3 tasks done

Sentry doesn't work on Next 13.5 #9092

RilDev opened this issue Sep 22, 2023 · 49 comments · Fixed by #9100 or #9114
Labels
Package: nextjs Issues related to the Sentry Nextjs SDK Type: Bug

Comments

@RilDev
Copy link

RilDev commented Sep 22, 2023

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which SDK are you using?

@sentry/nextjs

SDK Version

7.70.0

Framework Version

Next 13.5.2

Link to Sentry event

No response

SDK Setup

// This file configures the initialization of Sentry on the client.
// The config you add here will be used whenever a users loads a page in their browser.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

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

Sentry.init({
  dsn: DNS_URL,

  // Adjust this value in production, or use tracesSampler for greater control
  tracesSampleRate: 1,

  // Setting this option to true will print useful information to the console while you're setting up Sentry.
  debug: false,

  replaysOnErrorSampleRate: 1.0,

  // This sets the sample rate to be 10%. You may want this to be 100% while
  // in development and sample at a lower rate in production
  replaysSessionSampleRate: 0.1,

  // You can remove this option if you're not planning to use the Sentry Session Replay feature:
  integrations: [
    new Sentry.Replay({
      // Additional Replay configuration goes in here, for example:
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],
});

Steps to Reproduce

  1. update project from Next 13.4 to 13.5 with yarn add next@latest react@latest react-dom@latest eslint-config-next@latest
  2. remove and reinstall Sentry with npx @sentry/wizard@latest -i nextjs
  3. run dev server with yarn dev

Expected Result

When navigating to localhost:3000, it displays a page.

Actual Result

When navigating to localhost:3000, it throws an error:

⨯ ./app/layout.tsx
Module not found: Can't resolve 'next/dist/client/components/request-async-storage'

image

I check in my node_modules directory and indeed request-async-storage is missing.

@github-actions github-actions bot added the Package: nextjs Issues related to the Sentry Nextjs SDK label Sep 22, 2023
@lforst
Copy link
Member

lforst commented Sep 22, 2023

Can you try deleting your .next folder and re-building? Thanks!

@RilDev
Copy link
Author

RilDev commented Sep 22, 2023

Hi, thanks for answering so quickly!

I already tried deleting the .next directory but it didn't fix my issue.

And the next build command returns the same error:

./app/(dashboard)/layout.tsx
Module not found: Can't resolve 'next/dist/client/components/request-async-storage'

@bautistaaa
Copy link

We are experiencing the same issues after bumping to 13.5.
Confirmed that all suggested steps did not work and that removing sentry from next config resolved the issue

related change: typehero/typehero@09ae9b7#diff-197cd8ca285a4abd2f21479e0bf6e36e90b08528fcd7f3bdbe8d1221897e377d

@lforst
Copy link
Member

lforst commented Sep 25, 2023

@bautistaaa two things:

  • Is this also happening in CI runs or just locally?
  • Can you run node -e "console.log(require.resolve('next/dist/client/components/request-async-storage'))" and share the output? Thanks!

To me, something feels off. I cannot reproduce this yet we have a few reports of this. Our E2E tests also don't run into this issue.

I have a feeling that the people running into this have some sort of dirty state that the SDK doesn't particularily like (i.e. a state where next/dist/client/components/request-async-storage is available via require.resolve).

@RilDev
Copy link
Author

RilDev commented Sep 25, 2023

I have the issue on localhost.

Here is what the command node -e "console.log(require.resolve('next/dist/client/components/request-async-storage'))" gives me:

/Users/OBFUSCATED_USERNAME/node_modules/next/dist/client/components/request-async-storage.js

I ran rm -fr node_modules yarn.lock and yarn and I'm still experiencing this issue.

@lforst
Copy link
Member

lforst commented Sep 25, 2023

@RilDev Thanks so much for running the command. This more or less confirms my suspicion. It seems that there is a global installation of Next.js on a version pre-13.5 that makes our call to require.resolve('next/dist/client/components/request-async-storage') resolve to the global installation.

I opened a PR that will likely fix this: #9100

@lforst
Copy link
Member

lforst commented Sep 25, 2023

Dunno if this is fixed yet

@lforst lforst reopened this Sep 25, 2023
@RilDev
Copy link
Author

RilDev commented Sep 25, 2023

Hi again @lforst, I checked and although there is no new release yet, I tried to run the install wizard again, just in case.

It still isn't working for me.

@lforst
Copy link
Member

lforst commented Sep 25, 2023

@RilDev We just released version 7.71.0 of the SDK that should fix this. Would you mind trying it out?

@RilDev
Copy link
Author

RilDev commented Sep 25, 2023

The fix didn't work out. The error is still the exact same.

image

Here is my config:

"dependencies": {
    "@sentry/nextjs": "^7.71.0",
    "@supabase/auth-helpers-nextjs": "^0.8.1",
    "@supabase/auth-helpers-react": "^0.4.2",
    "@supabase/supabase-js": "^2.36.0",
    "@types/node": "20.6.5",
    "@types/react": "18.2.22",
    "@types/react-dom": "18.2.7",
    "autoprefixer": "10.4.16",
    "dayjs": "^1.11.10",
    "dotenv": "^16.3.1",
    "eslint": "8.50.0",
    "eslint-config-next": "^13.5.3",
    "husky": "^8.0.3",
    "jotai": "^2.4.2",
    "next": "^13.5.3",
    "postcss": "8.4.30",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-hook-form": "^7.46.2",
    "react-select": "^5.7.5",
    "react-toastify": "^9.1.3",
    "tailwindcss": "3.3.3",
    "typescript": "5.2.2",
    "uuid": "^9.0.1"
  },
  "devDependencies": {
    "@playwright/test": "^1.38.1",
    "@svgr/webpack": "^8.1.0",
    "@testing-library/jest-dom": "6.1.3",
    "@testing-library/react": "14.0.0",
    "@testing-library/user-event": "14.5.1",
    "@types/testing-library__jest-dom": "5.14.9",
    "@types/uuid": "^9.0.4",
    "encoding": "^0.1.13",
    "jest": "29.7.0",
    "jest-environment-jsdom": "29.7.0"
  }

@RilDev
Copy link
Author

RilDev commented Sep 26, 2023

@lforst I'll be waiting for your go to try again!

@FaresKi
Copy link

FaresKi commented Sep 26, 2023

Same issue here! On standby for more help if necessary.

@AbhiPrasad
Copy link
Member

AbhiPrasad commented Sep 26, 2023

We've released a fix for this in 7.72.0. Please give it a try! Thanks for your patience everyone.

@FaresKi
Copy link

FaresKi commented Sep 26, 2023

We've released a fix for this in 7.20.0. Please give it a try! Thanks for your patience everyone.

You mean 7.72 I think.
Thanks!

@RilDev
Copy link
Author

RilDev commented Sep 28, 2023

@RilDev Is the error you were getting still happening on release 7.72.0 of the SDK?

Sorry for the late reply.
My issue is fixed!
Thank you very much @lforst!

@FaresKi
Copy link

FaresKi commented Sep 28, 2023

I am in fact using a nx monorepo. Does that change something in how Sentry works? Since I configure Sentry at the app level, and not the monorepo level.

@FaresKi Thanks for letting me know. It indeed changes a bit how the SDK works, since we have to look for a particular file inside the Next.js dependency and that file's location changes a bit when you're in a monorepo. But that is for us to figure out.

Just curious. When can we expect the new release to be out? Thanks!

@lforst
Copy link
Member

lforst commented Sep 29, 2023

@FaresKi good point. I'll try to cut a release today.

@bautistaaa
Copy link

@lforst i am still seeing the issue. do you see anything missing here?

typehero/typehero#739

@AbhiPrasad
Copy link
Member

We've released changes in https://github.com/getsentry/sentry-javascript/releases/tag/7.73.0 to fix the requestAsyncStorageShim issues from before. Please give it a try and let us know if that helped. Sorry for the back and forth, appreciate the patience from all of you!

@FaresKi
Copy link

FaresKi commented Oct 2, 2023

Thanks a lot @AbhiPrasad and @lforst !!

@FaresKi
Copy link

FaresKi commented Oct 3, 2023

So I both upgraded Next.js to 13.5.4, and sentry upgraded to 7.73.
The good news: next builds as before, so nothing major.
The bad (?) news: Sentry still complains about not reaching the RequestAsyncStorage:

[@sentry/nextjs] You are using Next.js features that run on the Edge Runtime. Please add a "sentry.edge.config.js" or a "sentry.edge.config.ts" file to your project root in which you initialize the Sentry SDK with "Sentry.init()".
[@sentry/nextjs] You are using Next.js features that run on the Edge Runtime. Please add a "sentry.edge.config.js" or a "sentry.edge.config.ts" file to your project root in which you initialize the Sentry SDK with "Sentry.init()".
  ▲ Next.js 13.5.4
  - Local:        http://localhost:4200
  - Environments: .env
  - Experiments (use at your own risk):
     · serverActions
 ✓ Ready in 7.8s
[@sentry/nextjs] You are using Next.js features that run on the Edge Runtime. Please add a "sentry.edge.config.js" or a "sentry.edge.config.ts" file to your project root in which you initialize the Sentry SDK with "Sentry.init()".
 ✓ Compiled /src/middleware in 2.9s (291 modules)
warn  - The Sentry SDK could not access the RequestAsyncStorage module. Certain features may not work. There is nothing you can do to fix this yourself, but future SDK updates may resolve this.

@rsolomon
Copy link

rsolomon commented Oct 3, 2023

I am also seeing the same issue as @FaresKi . Fwiw the message is coming from <path>/node_modules/@sentry/nextjs/cjs/config/loaders/wrappingLoader.js (note cjs), so I'm guessing for some reason both esm and cjs versions are being loaded due to some sort of config issue. I'll keep digging but figured maybe that'd help someone else in the meantime.

Here's the stack:

 at Object.wrappingLoader (<path>/node_modules/@sentry/nextjs/cjs/config/loaders/wrappingLoader.js:173:17)
    at LOADER_EXECUTION (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:4134)
    at runSyncOrAsync (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:4145)
    at iterateNormalLoaders (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:5782)
    at iterateNormalLoaders (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:5650)
    at <path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:5879
    at r.callback (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:4039)
    at Object.transformSource (<path>/node_modules/next/dist/build/webpack/loaders/next-flight-loader/index.js:80:18)
    at LOADER_EXECUTION (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:4134)
    at runSyncOrAsync (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:4145)
    at iterateNormalLoaders (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:5782)
    at <path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:5142
    at r.callback (<path>/node_modules/next/dist/compiled/loader-runner/LoaderRunner.js:1:4039)
    at <path>/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js:175:23

@rsolomon
Copy link

rsolomon commented Oct 3, 2023

Ah ok @lforst I think this is what's up:

@sentry/nextjs does not have the "type": "module" property set in its package.json. So even though you've got the "module" property, nextjs is still assuming it's a commonjs package and using "main", which is cjs/index.server.js. In my case, this is in next.config.mjs: import { withSentryConfig } from '@sentry/nextjs';

For some reason when I add "type": "module" to @sentry/nextjs, it fails instead with:

Uncaught SyntaxError file:///<package>/next.config.mjs:1
import { withSentryConfig } from '@sentry/nextjs';
         ^^^^^^^^^^^^^^^^
SyntaxError: The requested module '@sentry/nextjs' does not provide an export named 'withSentryConfig'
    at _instantiate (internal/modules/esm/module_job:124:21)

which doesn't immediately make sense to me. Anyway, still digging.

@rsolomon
Copy link

rsolomon commented Oct 4, 2023

Here's the summary of the problem as I see it:

  1. This issue is occurring when attempting to import Sentry from next.config.mjs (extra emphasis on mjs, an ES Module). This is explicitly not transpiled, which is why Sentry imports in a NextJS app work fine anywhere other than here.
  2. Sentry's packages are not setup to be understood by a raw node bundler. Specifically they need "type": "module" and an "exports" field set. More info in this ticket: Sentry not working with ESModules while bundled #6147
  3. Due to the missing fields, the path is resolving to the commonJS module path set via the "main" attribute.
  4. The fallback set in @sentry/nextjs@7.73.0 is the mjs path for request-async-storage. Unsure if setting it to the cjs path would fix it in this case, but ideally the solution would be to configure for a proper mjs import.

Anyway, hope this helps identify and fix the root problem. Tagging @FaresKi again since this ticket is still closed and might not be getting direct attention.

@lforst
Copy link
Member

lforst commented Oct 5, 2023

@rsolomon I currently think none of this matters. Next.js has plugins configured under the hood to be able to import CJS/ESM and any combination thereof.

Did you upgrade to 7.73.0 and do you still face a build error? Or do you just see the The Sentry SDK could not access the RequestAsyncStorage module warning?

The latter is an issue in certain setups where the traditional node resolution algorithm wouldn't find the Next.js internal module. But it is not breaking builds so we can take our time figuring this out.

@rsolomon
Copy link

rsolomon commented Oct 5, 2023

Or do you just see the The Sentry SDK could not access the RequestAsyncStorage module warning?

Yes, this. v7.73.0 did indeed fix the build error, so these notes are specific to the inaccessible RequestAsyncStorage at runtime.

The latter is an issue in certain setups where the traditional node resolution algorithm

Yep, that's what the notes in the previous comment refer to. The aforementioned "Next.js ... plugins configured under the hood to be able to import CJS/ESM and any combination thereof" is not applicable to modules imported within the next.config.mjs, since all of that happens before build / transpilation.

But it is not breaking builds so we can take our time figuring this out.

True, but is Sentry fully functional in the scenario where RequestAsyncStorage cannot be found? If the warning is a noop then I can definitely stop thinking about it.

@lforst
Copy link
Member

lforst commented Oct 6, 2023

is not applicable to modules imported within the next.config.mjs, since all of that happens before build / transpilation.

@rsolomon Ok, it is possible that the package does not fully conform to esm, however, I still don't see how that relates to the SDK not being able to locate next/dist/client/components/request-async-storage.external?

Btw, if you have suggestions on how to make the package esm compatible without breaking existing cjs setups, PRs are super welcome!

@rsolomon
Copy link

rsolomon commented Oct 7, 2023

My hunch was that it had something to do with both the esm and cjs builds being loaded and being unaware of the work the others had done (init in A, check init in B).

It looks like the problem actually stems from a missing reference to root monorepo node_modules locations in incomingConfig.resolve.modules, passed from Next.js to src/config/webpack.ts.

In my project (using Yarn Workspaces), and I assume any other monorepo with default resolve webpack configs, incomingConfig.resolve.modules is populated with these 2 values:

  1. 'node_modules'
  2. '/<absolute_path_to_monorepo>/packages/<project_with_next_js>'

Sentry has some logic that turns (1) into '/<absolute_path_to_monorepo>/packages/<project_with_next_js>/node_modules', but @sentry/nextjs in this case is actually installed in the Monorepo's root node_modules directory, or '/<absolute_path_to_monorepo>/node_modules'. Since the resolution logic doesn't know modules can live here, it thinks request-async-module doesn't exist and errors out accordingly.

There's probably a better way to accomplish this, but adding the following to my project's webpack config in next.config.mjs fixes the problem and removes the console warning as expected:

import findWorkspaceRoot from 'find-yarn-workspace-root';

const nextConfig = {
  ...
  webpack: config => ({
    resolve: {
      ...config.resolve,
      modules: [...config.resolve.modules, findWorkspaceRoot()],
    },
  }),
};

export default withSentryConfig(nextConfig, { ... }, { ... });

@rsolomon
Copy link

rsolomon commented Oct 7, 2023

@FaresKi If your project is a monorepo or uses otherwise an atypical structure for node_modules, the above will probably fix this issue for you.

@lforst
Copy link
Member

lforst commented Oct 9, 2023

@rsolomon That is exactly what I am suspecting too, as per this comment. The thing is, we are already using webpackOptions.resolve.modules as base paths for the resolution algorithm. We should probably also add the root of the Next.js project there. Maybe Nx is messing with webpackOptions.resolve.modules 🤔.

As for

Sentry has some logic that turns (1) into '/<absolute_path_to_monorepo>/packages/<project_with_next_js>/node_modules', but @sentry/nextjs in this case is actually installed in the Monorepo's root node_modules directory, or '/<absolute_path_to_monorepo>/node_modules'. Since the resolution logic doesn't know modules can live here, it thinks request-async-module doesn't exist and errors out accordingly.

This is not entirely correct. The resolution algorithm will look upwards in the folder tree, layer for layer, checking each node_modules folder until it can find the requested module, which means the example you shared should actually work.

@rsolomon
Copy link

rsolomon commented Oct 9, 2023

This is not entirely correct. The resolution algorithm will look upwards in the folder tree, layer for layer, checking each node_modules folder until it can find the requested module, which means the example you shared should actually work.

The logic you're talking about happens before and is therefore counteracted by this check. requireResolveLocation is "/<absolute_path_to_monorepo>/node_modules/next/dist/client/components/request-async-storage.external.js", while absoluteWebpackResolvableModuleLocations is ["<absolute_path_to_monorepo>/packages/<project_with_next_js>/node_modules", "<absolute_path_to_monorepo>/packages/<project_with_next_js>"]. requireResolveLocation does not start with either value in absoluteWebpackResolvableModuleLocations, so moduleIsWebpackResolvable returns false, which makes potentialRequestAsyncStorageLocations.find(potentialLocation => moduleIsWebpackResolvable(potentialLocation)) return null, ultimately being the return value of getRequestAsyncStorageModuleLocation.

In other words, that line's intent (based on the comment) seems to be to filter out global node_modules locations, but it instead filters any node_modules location above the outermost location defined in config.resolve.modules. In this case, that's the directory of the nextjs package itself.

@lforst
Copy link
Member

lforst commented Oct 10, 2023

@rsolomon Oh you're absolutely right! Thanks for putting so much thought into this! <3 I'll try to find the time to find a solution here this week!

@rsolomon
Copy link

Happy to help 😄

@lforst
Copy link
Member

lforst commented Oct 16, 2023

@rsolomon I opened a PR to fix all of this mess. I'd love to have you also take a look: #9259

@rsolomon
Copy link

Thanks @lforst ! I'm at a conference all week but I'll do my best to check it out tonight or tomorrow night at the latest.

@lforst
Copy link
Member

lforst commented Oct 17, 2023

Hi everybody, we just released version 7.74.1 of the SDK which includes a fix for all of the problems discussed in this issue. Please try it out and let us know if the issue persists!

@jamespsterling
Copy link

Still seeing this on 7.77.0 trying to run with ts-node --esm

@lforst
Copy link
Member

lforst commented Nov 3, 2023

@jamespsterling Hi, can you please open a new issue with reproduction steps? Thanks!

@oxygenart
Copy link

Hi, I temporarily resolved the issue by downgrading Next.js to version 13.3.4 from 13.4.1. The Sentry SDK versions I am using are:

"@sentry/nextjs": "^7.80.1",
"@sentry/utils": "^7.80.1",

I'm unsure if this is related to Next.js or Sentry, as Next.js version 13.4.1 was working fine for me before integrating Sentry.

I hope this information helps anyone facing a similar problem. Thanks!

@remorses
Copy link

I had the same issue in a pnpm workspace, i fixed it by installing @sentry/nextjs in the right app folder instead of root

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