vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.01k stars 26.99k forks source link

Edge runtime causing terser panic due to top level await #64792

Closed samtgarson closed 4 months ago

samtgarson commented 6 months ago

Link to the code that reproduces this issue

https://github.com/samtgarson/next-edge-prisma-reproduction

To Reproduce

  1. Run npm run build
  2. Observe error in console
    ./node_modules/.prisma/client/wasm-edge-light-loader.js
    The generated code contains 'async/await' because this module is using "topLevelAwait".
    However, your target environment does not appear to support 'async/await'.

Current vs. Expected behavior

I expect no error to be thrown

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:25 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6030
  Available memory (MB): 18432
  Available CPU cores: 11
Binaries:
  Node: 20.11.1
  npm: 10.2.4
  Yarn: 1.22.22
  pnpm: N/A
Relevant Packages:
  next: 14.3.0-canary.11 // Latest available version is detected (14.3.0-canary.11).
  eslint-config-next: 13.5.2
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.4.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Runtime, Turbopack, SWC

Which stage(s) are affected? (Select all that apply)

next dev (local), next build (local)

Additional context

The reproduction provided demonstrates the error, but does not demonstrate the panic I receive on the production repo (https://github.com/samtgarson/books-about-food/tree/cloudflare)

In this repo, the build fails completely with the following error:

edge-chunks/267.js from Terser
  x await isn't allowed in non-async function
       ,-[39681:1]
 39681 | /* harmony export */ __webpack_require__.d(__webpack_exports__, {
 39682 | /* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
 39683 | /* harmony export */ });
 39684 | /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 48785, 23))).default);
       :                                                                         ^^^^^^^
 39685 |
 39686 | /***/ }),
       `----

Caused by:
    0: failed to parse input file
    1: Syntax Error

This only occurs when runtime is set to edge (even in a single page) and completely explodes the build.

(side note: I'm not sure why this larger repo seems to be using Terser when I've not disabled swcMinify)

This has been occurring for at least a couple of minor versions.

Related: https://github.com/vercel/next.js/issues/63283 https://github.com/vercel/next.js/issues/51077 https://github.com/prisma/prisma/issues/21780#issuecomment-2061783971 https://github.com/prisma/prisma/issues/23600 https://github.com/vercel/next.js/issues/31054

enricoros commented 6 months ago

Experiencing the same issue with 2 packages, pdfjs and tiktoken.

Updating 14.1.4 -> 14.2.2 produces these warnings on an otherwise clean npm run build:

> next build

  ▲ Next.js 14.2.2

   Creating an optimized production build ...
 ⚠ Compiled with warnings

./node_modules/pdfjs-dist/build/pdf.mjs
The generated code contains 'async/await' because this module is using "topLevelAwait".
However, your target environment does not appear to support 'async/await'.
As a result, the code may not run as expected or may cause runtime errors.

Import trace for requested module:
./node_modules/pdfjs-dist/build/pdf.mjs
./src/common/util/pdfUtils.ts
./src/apps/chat/components/composer/attachments/pipeline.tsx
./src/apps/chat/components/composer/attachments/store-attachments.tsx
./src/apps/chat/components/composer/attachments/useAttachments.tsx
./src/apps/chat/components/composer/Composer.tsx
./src/apps/chat/AppChat.tsx

./node_modules/tiktoken/tiktoken_bg.wasm
The generated code contains 'async/await' because this module is using "asyncWebAssembly".
However, your target environment does not appear to support 'async/await'.
As a result, the code may not run as expected or may cause runtime errors.

Import trace for requested module:
./node_modules/tiktoken/tiktoken_bg.wasm
./node_modules/tiktoken/tiktoken.js
./src/common/util/token-counter.ts
./src/common/providers/ProviderBackendCapabilities.tsx

 ✓ Linting and checking validity of types
...
vegandiet705 commented 6 months ago

I'm experiencing the same issue since I migrated from Next v14.1.4 to v14.2.1, using @prisma/client v5.12.1. My prisma setup:

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["driverAdapters"]
}
const neon = new Pool({ connectionString: process.env["DATABASE_URL"] });
const adapter = new PrismaNeon(neon);
const prisma = new PrismaClient({ adapter });

When attempting to access the DB from middleware.ts:

 ⚠ ../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/.prisma/client/wasm-edge-light-loader.js
The generated code contains 'async/await' because this module is using "topLevelAwait".
However, your target environment does not appear to support 'async/await'.
As a result, the code may not run as expected or may cause runtime errors.

Import trace for requested module:
../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/.prisma/client/wasm-edge-light-loader.js
../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/.prisma/client/wasm.js
../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/.prisma/client/default.js
../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/@prisma/client/default.js
./src/lib/prisma.ts
tjx666 commented 6 months ago

facing the same issue when import vtracer-webapp:

The generated code contains 'async/await' because this module is using "asyncWebAssembly".
However, your target environment does not appear to support 'async/await'.
As a result, the code may not run as expected or may cause runtime errors.

I find it is related with webpack experiment feeature:

// next.config.js
{
      webpack: (config) => {
      config.experiments = {
        asyncWebAssembly: true,
        syncWebAssembly: true,
        layers: true,
      };
      return config;
    },
}
kdy1 commented 5 months ago

This is not a bug of swc minifier / terser, and the error message is correct. edge runtime does not support top-level awaits.

See https://www.prisma.io/docs/orm/prisma-client/deployment/edge/overview

abelbeak commented 5 months ago

@kdy1 Please check whether the reference URL you provided is accurate. The URL indicates that Prisma can operate on NextJS middleware.

I confirmed that edge runtime does not support top-level awaits. Therefore, it seems like this issue should be created in Prisma rather than NextJS.

abelbeak commented 5 months ago

As edge runtime stops supporting await It has been confirmed that several libraries and services are experiencing failures.

We couldn't find any other tickets similar to this issue I'd love to hear about future patch plans or reasons for patching in this issue.

enricoros commented 5 months ago

@kdy1 things seem to work with both asyncWebAssembly and topLevelAwait, because the environment is the browser.

Somehow the warnings are emitted verbosely when compiling various routes, despite the target being the browser and not the edge runtime.

Is there a way to suppress this warning? Is the warning incorrect?

enricoros commented 5 months ago

Updating pdfjs-dist to 4.36.136 removes the warning (topLevelAwait). Warning still present for asyncWebAssembly on tiktoken. (note it's not used by the edge function, it's only used in the browser)

To silence the warning, I used the following:

...

  webpack: (config, { isServer }) => {
    ...

    // @dqbd/tiktoken: enable asynchronous WebAssembly
    config.experiments = {
      asyncWebAssembly: true,
      layers: true,
    };

    // fix warnings for async functions in the browser (https://github.com/vercel/next.js/issues/64792)
    if (!isServer) {
      config.output.environment = { ...config.output.environment, asyncFunction: true };
    }

    ...
    return config;
  },

  ...
LeakedDave commented 5 months ago

Came here for TikToken problems in browser lol thanks!

huozhi commented 4 months ago

Close per kdy's response here

github-actions[bot] commented 4 months ago

This closed issue has been automatically locked because it had no new activity for 2 weeks. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.