next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Next.js warns about unsupported apis even if this api usage is tree shaken

Open r34son opened this issue 8 months ago • 2 comments

Link to the code that reproduces this issue

https://github.com/r34son/nextjs-edge-unsupported-api-repro

To Reproduce

  1. npm i
  2. npm run build

Current vs. Expected behavior

See in logs of build:

./node_modules/@opentelemetry/sdk-metrics/build/esm/export/ConsoleMetricExporter.js
A Node.js API is used (setImmediate at line: 35) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/@opentelemetry/sdk-metrics/build/esm/export/ConsoleMetricExporter.js
./node_modules/@opentelemetry/sdk-metrics/build/esm/index.js

This code is not even bundled in middleware. The logic is located here: https://github.com/vercel/next.js/blob/09e21f37d6100ec515a14420340cb87912274087/packages/next/src/build/webpack/plugins/middleware-plugin.ts#L329-L379

It uses webpack JavascriptParser Hooks https://webpack.js.org/api/parser/

I quess hooks are fired before tree shaking.

Maybe one of options will be to have something like unstable_allowDynamic https://nextjs.org/docs/pages/api-reference/edge#unsupported-apis. Or need another implementation for detecting unsupported api on edge.

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 24.3.0: Thu Jan  2 20:24:23 PST 2025; root:xnu-11215.81.4~3/RELEASE_ARM64_T6020
  Available memory (MB): 32768
  Available CPU cores: 12
Binaries:
  Node: 22.13.1
  npm: 10.9.2
  Yarn: N/A
  pnpm: 10.8.1
Relevant Packages:
  next: 15.2.4 // Latest available version is detected (15.2.4).
  eslint-config-next: N/A
  react: 19.1.0
  react-dom: 19.1.0
  typescript: 5.8.3
Next.js Config:
  output: N/A

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

Middleware

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

next build (local)

Additional context

No response

r34son avatar Apr 22 '25 16:04 r34son

@samcx Could someone from Next.js team please take a look

r34son avatar Jun 11 '25 21:06 r34son

Maybe rspack's approach solves issue, see https://github.com/vercel/next.js/pull/80485 cc @SyMind

r34son avatar Jun 13 '25 14:06 r34son

Hi,

// middleware.ts

export const config = {
  matcher: '/',
  unstable_allowDynamic: [
    './node_modules/@opentelemetry/sdk-metrics/build/esm/index.js'
  ],
};

This would quiet the error, and it seems to work fine.

You could also try out the nodeMiddleware mode, but that requires using next@canary, https://nextjs.org/docs/app/api-reference/file-conventions/middleware#runtime - soon this edge bundling stuff won't be an issue anymore.

icyJoseph avatar Jun 17 '25 21:06 icyJoseph