getsentry / sentry-javascript

Official Sentry SDKs for JavaScript
https://sentry.io
MIT License
7.87k stars 1.55k forks source link

Attempted import error: 'withSentry' is not exported from '@sentry/nextjs'. #3673

Closed HarshaDW closed 2 years ago

HarshaDW commented 3 years ago

Package + Version

Description

Describe your issue in detail, ideally, you have a reproducible demo that you can show.

Attempted import error: 'withSentry' is not exported from '@sentry/nextjs'.

Though exported in handlers.ts enabled import into api/index handler.

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

onurtemizkan commented 3 years ago

Hi @HarshaDW, I just checked and could not reproduce it. Could you provide a reproducible example (preferably a repo) for us to confirm?

lobsterkatie commented 3 years ago

@HarshaDW - The minimum version of nextjs we support is 10.0.8, as documented here. I'm going to close this, but if you're still having trouble after updating nextjs, please let us know.

mavlikwowa commented 2 years ago

@lobsterkatie, @onurtemizkan, I faced with a same error. Could you reopen this issue?

An example of using in API:

import type { NextApiRequest, NextApiResponse } from "next"
import { withSentry } from "@sentry/nextjs";

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  throw new Error("API throw error test")
  res.status(200).json({ name: "John Doe" });
};

export default withSentry(handler);

next.config.js:

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

const SentryWebpackPluginOptions = {
  silent: true,
};

module.exports = withSentryConfig(() => {
  const env = {};

  return {
    webpack: (config, { isServer }) => {
      config.resolve.alias['~'] = path.resolve('./src');
      config.resolve.alias['react'] = path.resolve('./node_modules/react');
      if (!isServer) {
        config.node = {
          fs: 'empty',
        };
      }
      return config;
    },
    env,
  };
}, SentryWebpackPluginOptions);

sentry.client.config:

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

const SENTRY_DSN =
  'https://xxxxxxxxxxxxxx@api-traceback.planeta.tc/2';

Sentry.init({
  dsn: SENTRY_DSN || 'null',
  tracesSampleRate: 1.0,
});

sentry.server.config:

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

const SENTRY_DSN =
  'https://xxxxxxxxxxxxxx@api-traceback.planeta.tc/2';

Sentry.init({
  dsn: SENTRY_DSN || 'null',
  tracesSampleRate: 1.0,
});

After next dev || next build: Attempted import error: 'withSentry' is not exported from '@sentry/nextjs'

Currently, I was managed to find a soulition with a capture exepction. As for me, this isn't convenient solution.:

export const example = async (): Promise<string[]> => {
  const data = await fetch(
    `exampleFetch`,
    reqData,
  );
  const res = await data.json();
  if (!data.ok) {
    Sentry.captureException('test');
    throw { statusCode: data.status, errorMessage: JSON.stringify(res) };
  }
  return res;
};
onurtemizkan commented 2 years ago

Hi @mavlikwowa, I still can't reproduce the issue using the snippets you provided. Could you create a repo if possible?

After next dev || next build:

And, are you using the global installation of next while running your app? I'm just wondering whether there is a global/local conflict that could lead to this issue.

mavlikwowa commented 2 years ago

GA, @onurtemizkan I have created an example repo where you can reproduce this issue. https://github.com/mavlikwowa/sentry_nexjs_issue When I had been creating this I payed an attention that error appointed when I used API call in getInitialProps function:

App.getInitialProps = async () => {
  await apiCall();
};

Perhaps, it can help us to resolve this probem. P.S I can't publish all working repo due to NDA, sorry. There's only for error's reproducing.

onurtemizkan commented 2 years ago

Thanks a lot for the reproduction @mavlikwowa.

njfix6 commented 2 years ago

What was the resolution for the issue? I am running into this as well.

zkhalapyan commented 2 years ago

Hitting this issue as well.

lobsterkatie commented 2 years ago

@mavlikwowa - circling back around to this. I checked out your repro repo, and one thing I noticed is that your api/ folder is not inside of pages/. I haven't yet quite put together why that leads to the import error you're seeing, but I can tell you that your usage of withSentry in api/api.ts won't work in any case, because the Sentry.init() code is only injected into files in the pages/ directory. That's where nextjs expects to find your API routes, and in my testing, putting them anywhere else makes them 404. Leaving aside Sentry, does this work for you? Does making a request to /api result in that handler being called? (I tried to run your example app but ended up getting a number of build errors.)

I'll also say that I've never seen a handler function called directly. Normally nextjs calls the handler, once a request has been made to the handler's route, and the SDK works based on that assumption. Is there a reason you're calling it directly?

@njfix6 @zkhalapyan - Are your nextjs apps set up the same way as in @mavlikwowa's repo? If not, could either of you post a reproduction of your setup?

zkhalapyan commented 2 years ago

@lobsterkatie ours is under pages, it's the same setup that next.js autogens through the script, so pretty it's at least setup the the way they want it to be setup.

I wonder if next.js does some pruning with NPM packages and ends up cutting off sentry for some reason?

lobsterkatie commented 2 years ago

I wonder if next.js does some pruning with NPM packages and ends up cutting off sentry for some reason?

Wouldn't it complain that it can't find sentry at all in that case, though?

Are you able to create a small repro of the error? If not, it'd be helpful to see your next.config.js and your sentry.server.config.js. Also, what version of next are you using, and what version of the SDK?

lobsterkatie commented 2 years ago

I played around again with the repro in the related issue here, and in that case, I think I've diagnosed the problem. @njfix6 @zkhalapyan, are you importing anything from pages/api/xxx.js into a non-API page?

github-actions[bot] commented 2 years ago

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 🥀

federico-moretti commented 2 years ago

I've also fixed this problem removing the exports from the /api/... files.

ka2n commented 2 years ago

Here is my current implementation pattern and editor setup:

My Tips:

import { FooResponse, fetchFoo } from "pages/api/_foo"
export default () => {
  const { data } =useSWR(key, fetchFoo)
 return <>...</>
}

VSCode: And use with Explorer file nesting,

  "explorer.experimental.fileNesting.patterns": {
    "*.ts": "$(capture).js, _$(capture).ts, $(capture).d.ts, $(capture).test.ts"
  }

image

lobsterkatie commented 2 years ago

And use with Explorer file nesting,

TIL! Thanks for sharing your setup, @ka2n!

lobsterkatie commented 2 years ago

It sounds like we've identified the problem, so I'm going to close this. Please let us know if that's not the case.

Cheers!