Skip to content

Auto-wrapping not working for Next.js Dynamic Routes #8442

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

Closed
3 tasks done
adeelejaz opened this issue Jul 2, 2023 · 12 comments
Closed
3 tasks done

Auto-wrapping not working for Next.js Dynamic Routes #8442

adeelejaz opened this issue Jul 2, 2023 · 12 comments
Labels
Package: nextjs Issues related to the Sentry Nextjs SDK

Comments

@adeelejaz
Copy link

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.57.0

Framework Version

7.57.0

Link to Sentry event

No response

SDK Setup

Sentry.init({
  environment: process.env.NEXT_PUBLIC_SITE_URL === "https://[..]" ? "production" : "development",
  dsn: SENTRY_DSN || "[..]",
  includeLocalVariables: true,
  tracesSampleRate: 0.2,
});

Steps to Reproduce

  1. Add a dynamic route when working with the Next.js 13 app directory e.g. app/checkout/[step]/page.jsx
  2. Get a warning during build.

Expected Result

Auto-wrapping to work

Actual Result

[@sentry/nextjs] Could not instrument /[..]/app/checkout/[step]/page.jsx. An error occurred while auto-wrapping:
SyntaxError: Unexpected token (14:55) in __SENTRY_WRAPPING_TARGET_FILE__.cjs
@lforst
Copy link
Member

lforst commented Jul 3, 2023

Hey, thanks for writing in!

I sadly cannot reproduce this. Would you mind sharing a reproduction setup? (git repo we could pull or stackblitz or similar)

I have a suspicion that app/checkout/[step]/page.jsx might simply have a syntax error.

@lforst lforst added the Package: nextjs Issues related to the Sentry Nextjs SDK label Jul 3, 2023
@AbhiPrasad
Copy link
Member

Closing this issue for cleanup. Please re-open if this still applies. Thanks!

@AbhiPrasad AbhiPrasad closed this as not planned Won't fix, can't repro, duplicate, stale Jul 27, 2023
@mayrsascha
Copy link

mayrsascha commented Sep 16, 2023

Still happening here. Works in Next.js 13.4.7 and fails when I try to upgrade to Next.js 13.4.9. I don't have an app directory (still using pages directory). It happens with dynamic routes pages/coin/[id].js as well as with multiple static routes.

Standard Next.js setup according to the docs,
"@sentry/nextjs": "^7.69.0",
"@sentry/node": "^7.69.0",
"@sentry/tracing": "^7.69.0",

Unfortunately I'm unable to share code as there is an NDA and I can't reproduce it with a minimal example either.

@lforst
Copy link
Member

lforst commented Sep 18, 2023

@mayrsascha Without proper reproduction we unfortunately not help you. I recommend upgrading nextjs to the newest version and opening a new issue if you have more information to share (your setup, full error messages, and so on)

@mayrsascha
Copy link

mayrsascha commented Sep 18, 2023

@lforst I checked again, there is one thing I can share here:

Again quickly about my setup:

"@sentry/nextjs": "^7.69.0",
"@sentry/node": "^7.69.0",
"@sentry/tracing": "^7.69.0",
"next": "^13.4.9",

The error happens on the _error.js page that was generated by @sentry/wizard (as described in the NextJS guide.

Here again the content of _error.js:

import NextErrorComponent from 'next/error';

import { captureException, flush } from '@sentry/nextjs';

const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => {
  if (!hasGetInitialPropsRun && err) {
    // getInitialProps is not called in case of
    // https://github.com/vercel/next.js/issues/8592. As a workaround, we pass
    // err via _app.js so it can be captured
    captureException(err);
    // Flushing is not required in this case as it only happens on the client
  }

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

MyError.getInitialProps = async (context) => {
  const errorInitialProps = await NextErrorComponent.getInitialProps(context);

  const { res, err, asPath } = context;

  // Workaround for https://github.com/vercel/next.js/issues/8592, mark when
  // getInitialProps has run
  errorInitialProps.hasGetInitialPropsRun = true;

  // Returning early because we don't want to log 404 errors to Sentry.
  if (res?.statusCode === 404) {
    return errorInitialProps;
  }

  // Running on the server, the response object (`res`) is available.
  //
  // Next.js will pass an err on the server if a page's data fetching methods
  // threw or returned a Promise that rejected
  //
  // Running on the client (browser), Next.js will provide an err if:
  //
  //  - a page's `getInitialProps` threw or returned a Promise that rejected
  //  - an exception was thrown somewhere in the React lifecycle (render,
  //    componentDidMount, etc) that was caught by Next.js's React Error
  //    Boundary. Read more about what types of exceptions are caught by Error
  //    Boundaries: https://reactjs.org/docs/error-boundaries.html

  if (err) {
    captureException(err);

    // Flushing before returning is necessary if deploying to Vercel, see
    // https://vercel.com/docs/platform/limits#streaming-responses
    await flush(2000);

    return errorInitialProps;
  }

  // If this point is reached, getInitialProps was called without any
  // information about what the error might be. This is unexpected and may
  // indicate a bug introduced in Next.js, so record it in Sentry
  captureException(
    new Error(`_error.js getInitialProps missing data at path: ${asPath}`),
  );
  await flush(2000);

  return errorInitialProps;
};

export default MyError;

And this is the error I'm seeing:

[@sentry/nextjs] Could not instrument /vercel/path0/pages/_error.js. An error occurred while auto-wrapping:
--
17:57:02.279 | SyntaxError: Unexpected token (25:15) in __SENTRY_WRAPPING_TARGET_FILE__.cjs
17:57:02.282 | [@sentry/nextjs] Could not instrument /vercel/path0/pages/_error.js. An error occurred while auto-wrapping:
17:57:02.283 | SyntaxError: Unexpected token (25:15) in __SENTRY_WRAPPING_TARGET_FILE__.cjs

My sentry.server.config.js:

// This file configures the initialization of Sentry on the server.
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import { init } from '@sentry/nextjs';

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

init({
  dsn: SENTRY_DSN,
  // Adjust this value in production, or use tracesSampler for greater 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
});

My sentry.client.config.js:

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

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

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

Sentry.init({
  dsn: SENTRY_DSN,
  // 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,
  // If the entire session is not sampled, use the below sample rate to sample
  // sessions when an error occurs.
  replaysOnErrorSampleRate: 1.0,

  integrations: [new Sentry.Replay()],
});

My sentry.edge.config.js:

// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on).
// The config you add here will be used whenever one of the edge features is loaded.
// Note that this config is unrelated to the Verel Edge Runtime and is also required when running locally.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

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

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

Sentry.init({
  dsn: SENTRY_DSN,

  // 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,
});

Again: this works with NextJS 13.4.7 for me. When I try to upgrade to NextJS 13.4.9 it fails. Not just for this NextJS page, but for others as well (can't share those unfortunately)

@lforst
Copy link
Member

lforst commented Sep 19, 2023

@mayrsascha Can you please try upgrading to the latest Next.js version? Thanks!

Other than that we need full and proper reproduction. In general this error is not dangerous. You application will still work. The error doesn't even mean that Sentry did something wrong. It basically means that the SDK encountered invalid syntax when wepback passed the /vercel/path0/pages/_error.js file to our Webpack plugin.

@mayrsascha
Copy link

@lforst I Just upgraded to the latest version 13.5.1. Still happening.

I ran the Next.js build locally now. The problem is that this error does seem to break the build, so even though my application would work the build can't pass -> No deployment.

I think I figured out why the issue is happening now. It seems that the "invalid syntax" is the ES6 optional chaining. For example, in Sentry's auto-generated_error.js it fails on this line:

if (res?.statusCode === 404) {

While I, unfortunately, can't share the rest of the code, all the other pages that don't build are also failing exactly on lines where optional chaining is used.

My local error trace:

./pages/_error.js
Module parse failed: Unexpected token (25:15)
File was processed with these loaders:
 * ./node_modules/@sentry/nextjs/cjs/config/loaders/wrappingLoader.js
 * ./node_modules/@sentry/nextjs/cjs/config/loaders/wrappingLoader.js
 * ./node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
You may need an additional loader to handle the result of these loaders.
|     errorInitialProps.hasGetInitialPropsRun = _withSuperJSONInitProps(true, []);
|     // Returning early because we don't want to log 404 errors to Sentry.
>     if (this?. === 404) {
|         return errorInitialProps;
|     }

Import trace for requested module:
./pages/_error.js

@Zarathustra2
Copy link

@mayrsascha Have you been able to resolve this, I am running into a similar issue

@mayrsascha
Copy link

@mayrsascha Have you been able to resolve this, I am running into a similar issue

No, I ultimately removed the error page, haven't tried this on the latest Sentry version though.

@Zarathustra2
Copy link

interestingly running npm run build locally does not cause this error but when deploying to vercel which runs vercel build causes this issue.

The error I am getting is:

SyntaxError: Unexpected token (9:48) in __SENTRY_WRAPPING_TARGET_FILE__.cjs
[@sentry/nextjs] Could not instrument /vercel/path0/pages/<SOME_PAGE>/index.js. An error occurred while auto-wrapping:
  • "@sentry/nextjs": "^7.113.0",

I think the unexpected token is this line:

import data from "../../data/foo.json" assert { type: "json" }

@lforst

@lforst
Copy link
Member

lforst commented May 8, 2024

The SDK doesn't support import assertions yet. Please exclude the file from auto-instrumentation: https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#opt-in-to-auto-instrumentation-on-specific-routes

@Zarathustra2 would you mind opening a separate issue for this?

@Zarathustra2
Copy link

Thanks!

Done #11949

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Package: nextjs Issues related to the Sentry Nextjs SDK
Projects
Archived in project
Development

No branches or pull requests

5 participants