mirror of
https://github.com/hanzoai/next.js.git
synced 2026-09-24 17:00:51 +00:00
When using dependencies in Middleware that make use of dynamic code evaluation, Next.js emits a build error because this is not supported in the Edge runtime. In rare cases, when the code can not be reached at runtime and can't be removed by tree-shaking, users might opt in to using the `unstable_allowDynamic` config. When combined with pnpm, the provided glob patterns as documented at https://nextjs.org/docs/messages/edge-dynamic-code-evaluation#possible-ways-to-fix-it did not match correctly because of pnpm's use of the `.pnpm` directory. To fix the pattern matching, we need to provide the `dot` option to [picomatch](https://github.com/micromatch/picomatch), which enables dotfile matching. _Side note: Ideally we would detect dynamic code evaluation after tree shaking, to reduce the number of cases where users need to revert to using `unstable_allowDynamic`._ fixes #51401
48 lines
1.8 KiB
Plaintext
48 lines
1.8 KiB
Plaintext
---
|
|
title: Dynamic code evaluation is not available in Middleware
|
|
---
|
|
|
|
## Why This Error Occurred
|
|
|
|
`eval()`, `new Function()` or compiling WASM binaries dynamically is not allowed in Middleware.
|
|
Specifically, the following APIs are not supported:
|
|
|
|
- `eval()`
|
|
- `new Function()`
|
|
- `WebAssembly.compile`
|
|
- `WebAssembly.instantiate` with [a buffer parameter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code)
|
|
|
|
## Possible Ways to Fix It
|
|
|
|
You can bundle your WASM binaries using `import`:
|
|
|
|
```ts filename="middleware.ts"
|
|
import { NextResponse } from 'next/server'
|
|
import squareWasm from './square.wasm?module'
|
|
|
|
export default async function middleware() {
|
|
const m = await WebAssembly.instantiate(squareWasm)
|
|
const answer = m.exports.square(9)
|
|
|
|
const response = NextResponse.next()
|
|
response.headers.set('x-square', answer.toString())
|
|
return response
|
|
}
|
|
```
|
|
|
|
In rare cases, your code could contain (or import) some dynamic code evaluation statements which _can not be reached at runtime_ and which can not be removed by tree-shaking.
|
|
You can relax the check to allow specific files with your Middleware [configuration](/docs/pages/api-reference/edge#unsupported-apis):
|
|
|
|
```ts filename="pages/api/example.ts"
|
|
export const config = {
|
|
unstable_allowDynamic: [
|
|
'/lib/utilities.js', // allows a single file
|
|
'**/node_modules/function-bind/**', // use a glob to allow anything in the function-bind 3rd party module
|
|
],
|
|
}
|
|
```
|
|
|
|
`unstable_allowDynamic` is a glob, or an array of globs, ignoring dynamic code evaluation for specific files. The globs are relative to your application root folder.
|
|
|
|
Be warned that if these statements are executed on the Edge, _they will throw and cause a runtime error_.
|