vercel / next.js

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

Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime #58673

Open azr-arch opened 10 months ago

azr-arch commented 10 months ago

Link to the code that reproduces this issue

https://github.com/azr-arch/realtime-chat-app

To Reproduce

try building the app with npm run build

Current vs. Expected behavior

Current Behavior: When I attempt to build my Next.js application for deployment, the build process fails. The error message indicates that dynamic code evaluation (e.g., 'eval', 'new Function', 'WebAssembly.compile') is not allowed in Edge Runtime. The error seems to originate from the @babel/runtime/regenerator and next-auth/react modules.

Here's the error message I received:

Failed to compile.

./node_modules/@babel/runtime/regenerator/index.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime 
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

Import trace for requested module:
./node_modules/@babel/runtime/regenerator/index.js
./node_modules/next-auth/react/index.js

> Build failed because of webpack errors

Expected Behavior: I expected the build process to complete without errors, allowing me to deploy my Next.js application.

Steps to Reproduce:

  1. Run the build command for the Next.js application.
  2. Observe the error message related to dynamic code evaluation in Edge Runtime.

Verify canary release

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 11 Home Single Language
Binaries:
  Node: 21.1.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.0.1
  eslint-config-next: 14.0.2
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.2.2
Next.js Config:
  output: N/A

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

Not sure

Additional context

also, any help regarding this

(node:7360) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)

would be appreciated.

Note: this warning only shows during npm run dev

IonelLupu commented 10 months ago

I got the same error in one of my files called "constants.ts":

./app/constants.ts
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime 

And guess what't in that file. Just this:

export const supportEmail = 'some@email.com'
export const announcementBarDisabledKey = 'announcementBarDisabled'

export const anonymousUniqueUserIdCookie = 'ajs_anonymous_id'
export const userIdCookie = 'userId'

export const publicChannels = ['ts-live-public-channel', 'ts-demo-channel']

Why would this give an error. It's nothing dynamic here 🤦

joniel commented 9 months ago

i'm used Next Auth v5. in auth.ts

  callbacks: {
    authorized(params) {
      return !!params.auth?.user;
    },
  },
  // adapter: FirestoreAdapter(), 

In my case, adapter: FirestoreAdapter() maybe burst build errors... After I made a comment that line, built ok. Uhm... I have to use that adapter... but... how i can resolve.

azr-arch commented 9 months ago

@joniel @IonelLupu i removed this piece of code

export const attachUser = async (req, next) => {
    const session = await getSession({ req });
    if (session) {
        req.user = session.user;
    }
    ).
};

from middleware.js and built works fine, hope it helps you guide through your issues

IonelLupu commented 9 months ago

@azr-arch I had to move the entire contents of my constants.ts file directly in the middleware.ts file. I basically have duplicated code now. It works, but it's sooo bad 😢

Monukumar777 commented 5 months ago

i see the same error Failed to compile.

./node_modules/mongoose/dist/browser.umd.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

Import trace for requested module: ./node_modules/mongoose/dist/browser.umd.js ./lib/Mongodb/Models/User.model.ts ./auth.ts

Build failed because of webpack errors when i remove this code form auth.ts file : async signIn({ user, account }) { "use server"; if (account?.provider === "google") { await connectToDatabase(); try { const createUser = await User.create({ name: user.name, email: user.email, image: user.image, }); return createUser; } catch (error) { console.error("Error creating user:", error); throw error; } } }, i works fine but i want to create user. i see in mongoose docs : Mongoose does not currently support Next.js Edge Runtime. While you can import Mongoose in Edge Runtime, you'll get Mongoose's browser library. There is no way for Mongoose to connect to MongoDB in Edge Runtime, because Edge Runtime currently doesn't support Node.js net API, which is what the MongoDB Node Driver uses to connect to MongoDB.

but when i try to change edge runtime to nodejs runtime . but it not works .

please help me to solve this error.

ronijaat commented 5 months ago

i see the same error Failed to compile.

./node_modules/mongoose/dist/browser.umd.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

Import trace for requested module: ./node_modules/mongoose/dist/browser.umd.js ./lib/Mongodb/Models/User.model.ts ./auth.ts

Build failed because of webpack errors when i remove this code form auth.ts file : async signIn({ user, account }) { "use server"; if (account?.provider === "google") { await connectToDatabase(); try { const createUser = await User.create({ name: user.name, email: user.email, image: user.image, }); return createUser; } catch (error) { console.error("Error creating user:", error); throw error; } } }, i works fine but i want to create user. i see in mongoose docs : Mongoose does not currently support Next.js Edge Runtime. While you can import Mongoose in Edge Runtime, you'll get Mongoose's browser library. There is no way for Mongoose to connect to MongoDB in Edge Runtime, because Edge Runtime currently doesn't support Node.js net API, which is what the MongoDB Node Driver uses to connect to MongoDB.

but when i try to change edge runtime to nodejs runtime . but it not works .

please help me to solve this error.

hey, you find any solution for this?

Monukumar777 commented 4 months ago

yes, i use neon with drizzle

ronijaat commented 4 months ago

Okay but i added the create user functionality in server action while submitting the form and everything goes fine. I already use mongoose and changing mongoose is not suitable for me

IonelLupu commented 4 months ago

I just don't get what's dynamic at this code:

export const supportEmail = 'support@athotel.com'
export const announcementBarDisabledKey = 'announcementBarDisabled'
// Cookie names
export const anonymousUniqueUserIdCookie = 'ajs_anonymous_id'
export const userIdCookie = 'userId'
export const sessionIdCookie = 'sessionKey'
export const clerkAuthTypeKey = 'clerkAuthType'

Or what's dynamic at this code:

import dayjs from 'dayjs'

export function getValidDates(checkinInitial: string | null | undefined, checkoutInitial: string | null | undefined) {
    // If the dates are invalid, set them to defaults
    let checkin = dayjs(checkinInitial)
    let checkout = dayjs(checkoutInitial)
    if (
        !checkinInitial ||
        !checkoutInitial ||
        !checkin.isValid() ||
        !checkout.isValid() ||
        checkin.isBefore(dayjs().subtract(1, 'day')) ||
        checkout.isBefore(dayjs().subtract(1, 'day')) ||
        checkout.isBefore(checkin)
    ) {
        return {
            // it seems that using MM-DD-YYYY (with dashes) as a format is Invalid Date in Safari
            checkin: dayjs().add(30, 'day').format('MM/DD/YYYY'),
            checkout: dayjs().add(32, 'day').format('MM/DD/YYYY'),
        }
    }

    if (checkin.isSame(checkout)) {
        checkout = checkout.add(1, 'day')
    }
    return { checkin: checkin.format('MM/DD/YYYY'), checkout: checkout.format('MM/DD/YYYY') }
}

It's impossible to fix without just moving the entire

athikaf commented 4 months ago

Okay but i added the create user functionality in server action while submitting the form and everything goes fine. I already use mongoose and changing mongoose is not suitable for me

Can you share your code or some reference on how you did that? Because I'm also using mongoose and moving it completely to another DB is simply not feasible for me. I tried creating an auth.js and auth.config.js to seprate the context but it is not working.

mkimbo commented 4 months ago

Any solution on this? I am also using the latest version of next with mongoose. I am getting this error while trying to deploy to production..localhost is okay

ronijaat commented 4 months ago

Okay but i added the create user functionality in server action while submitting the form and everything goes fine. I already use mongoose and changing mongoose is not suitable for me

Can you share your code or some reference on how you did that? Because I'm also using mongoose and moving it completely to another DB is simply not feasible for me. I tried creating an auth.js and auth.config.js to seprate the context but it is not working.

Okay mongoose doesn’t support edge runtime so if you doing any db thing in auth js it gives error with mongoose. To overcome this, move all these from auth js

example : If you add user to db on login in auth js. It gives error To overcome this Allow user to login, then redirect to home page and there u can add the user to db.

Iamsidar07 commented 4 months ago

Okay but i added the create user functionality in server action while submitting the form and everything goes fine. I already use mongoose and changing mongoose is not suitable for me

Can you share your code or some reference on how you did that? Because I'm also using mongoose and moving it completely to another DB is simply not feasible for me. I tried creating an auth.js and auth.config.js to seprate the context but it is not working.

Okay mongoose doesn’t support edge runtime so if you doing any db thing in auth js it gives error with mongoose. To overcome this, move all these from auth js

example : If you add user to db on login in auth js. It gives error To overcome this Allow user to login, then redirect to home page and there u can add the user to db.

Can you share your source code

ronijaat commented 4 months ago

Okay but i added the create user functionality in server action while submitting the form and everything goes fine. I already use mongoose and changing mongoose is not suitable for me

Can you share your code or some reference on how you did that? Because I'm also using mongoose and moving it completely to another DB is simply not feasible for me. I tried creating an auth.js and auth.config.js to seprate the context but it is not working.

Okay mongoose doesn’t support edge runtime so if you doing any db thing in auth js it gives error with mongoose. To overcome this, move all these from auth js example : If you add user to db on login in auth js. It gives error To overcome this Allow user to login, then redirect to home page and there u can add the user to db.

Can you share your source code

yes sure But now i am using prisma for authentication in auth js and mongoose in other part of application.

bxljoy commented 3 months ago

I encounter the same issue, when I use Next.js 14.2.3 and Mongoose 8.3.4 to connect Mongodb Atlas. When I deploy my project to Vercel or just "npm run build", it will show some errors:

Creating an optimized production build ... Failed to compile.

./models/user.ts Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

The error was caused by importing 'mongoose/dist/browser.umd.js' in './models/user.ts'.

Import trace for requested module: ./models/user.ts ./auth.ts ./middleware.ts

Build failed because of webpack errors

Any solutions on this? If I just use Prisma to replace mongoose, is it an option?

ronijaat commented 3 months ago

I encounter the same issue, when I use Next.js 14.2.3 and Mongoose 8.3.4 to connect Mongodb Atlas. When I deploy my project to Vercel or just "npm run build", it will show some errors:

Creating an optimized production build ... Failed to compile.

./models/user.ts Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

The error was caused by importing 'mongoose/dist/browser.umd.js' in './models/user.ts'.

Import trace for requested module: ./models/user.ts ./auth.ts ./middleware.ts

Build failed because of webpack errors

Any solutions on this? If I just use Prisma to replace mongoose, is it an option?

Depending on your use case. If you are fetching user in auth.ts then use prisma

bxljoy commented 3 months ago

I encounter the same issue, when I use Next.js 14.2.3 and Mongoose 8.3.4 to connect Mongodb Atlas. When I deploy my project to Vercel or just "npm run build", it will show some errors: Creating an optimized production build ... Failed to compile. ./models/user.ts Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation The error was caused by importing 'mongoose/dist/browser.umd.js' in './models/user.ts'. Import trace for requested module: ./models/user.ts ./auth.ts ./middleware.ts

Build failed because of webpack errors

Any solutions on this? If I just use Prisma to replace mongoose, is it an option?

Depending on your use case. If you are fetching user in auth.ts then use prisma

Thank you so much. I'm indeed fetching user in auth.ts, so I will try.

By the way, I also tried to downgrade my Next.js to older version, but it didn't work. Because the Next-Auth 5@beta depends on the latest version of Next.js.

ronijaat commented 3 months ago

I encounter the same issue, when I use Next.js 14.2.3 and Mongoose 8.3.4 to connect Mongodb Atlas. When I deploy my project to Vercel or just "npm run build", it will show some errors: Creating an optimized production build ... Failed to compile. ./models/user.ts Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation The error was caused by importing 'mongoose/dist/browser.umd.js' in './models/user.ts'. Import trace for requested module: ./models/user.ts ./auth.ts ./middleware.ts

Build failed because of webpack errors

Any solutions on this? If I just use Prisma to replace mongoose, is it an option?

Depending on your use case. If you are fetching user in auth.ts then use prisma

Thank you so much. I'm indeed fetching user in auth.ts, so I will try.

By the way, I also tried to downgrade my Next.js to older version, but it didn't work. Because the Next-Auth 5@beta depends on the latest version of Next.js.

Use prisma in auth.js, and mongoose remains in the other part of the code

IonelLupu commented 3 months ago

Using import type { SomeType } from './myTypes' also doesn't work. I literally have no logic except a JS object in my file and I still get this error.

traez commented 2 months ago

I encounter the same issue, when I use Next.js 14.2.3 and Mongoose 8.3.4 to connect Mongodb Atlas. When I deploy my project to Vercel or just "npm run build", it will show some errors:

Creating an optimized production build ... Failed to compile.

./models/user.ts Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

The error was caused by importing 'mongoose/dist/browser.umd.js' in './models/user.ts'.

Import trace for requested module: ./models/user.ts ./auth.ts ./middleware.ts

Build failed because of webpack errors

Any solutions on this? If I just use Prisma to replace mongoose, is it an option?

Same issue here "next": "14.2.5", "next-auth": "^5.0.0-beta.19", "mongoose": "^8.5.0",

Creating an optimized production build ... Failed to compile.

./node_modules\mongoose\dist\browser.umd.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

Import trace for requested module: ./node_modules\mongoose\dist\browser.umd.js ./src\utils\modelUser.ts ./src\auth.ts ./src\middleware.ts

Build failed because of webpack errors

"Because the Edge runtime only uses standard Web APIs, many packages are not compatible with it, such as the mongodb driver package."

2 articles I saw about Authjs, Magic Links Email Provider with MongoDB as backend also mentioned and provided a workaround. I wish I could see a video with this workaround being practically utilized and built.

bxljoy commented 2 months ago

I encounter the same issue, when I use Next.js 14.2.3 and Mongoose 8.3.4 to connect Mongodb Atlas. When I deploy my project to Vercel or just "npm run build", it will show some errors: Creating an optimized production build ... Failed to compile. ./models/user.ts Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation The error was caused by importing 'mongoose/dist/browser.umd.js' in './models/user.ts'. Import trace for requested module: ./models/user.ts ./auth.ts ./middleware.ts

Build failed because of webpack errors

Any solutions on this? If I just use Prisma to replace mongoose, is it an option?

Same issue here "next": "14.2.5", "next-auth": "^5.0.0-beta.19", "mongoose": "^8.5.0",

Creating an optimized production build ... Failed to compile.

./node_modules\mongoose\dist\browser.umd.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

Import trace for requested module: ./node_modules\mongoose\dist\browser.umd.js ./src\utils\modelUser.ts ./src\auth.ts ./src\middleware.ts

Build failed because of webpack errors

"Because the Edge runtime only uses standard Web APIs, many packages are not compatible with it, such as the mongodb driver package."

2 articles I saw about Authjs, Magic Links Email Provider with MongoDB as backend also mentioned and provided a workaround. I wish I could see a video with this workaround being practically utilized and built.

Using prisma to replace the mongoose part in your auth.ts, this issue will be fixed. Go to read the documentation on the official website of Prisma, there are some examples for mongodb.

traez commented 2 months ago

I encounter the same issue, when I use Next.js 14.2.3 and Mongoose 8.3.4 to connect Mongodb Atlas. When I deploy my project to Vercel or just "npm run build", it will show some errors: Creating an optimized production build ... Failed to compile. ./models/user.ts Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation The error was caused by importing 'mongoose/dist/browser.umd.js' in './models/user.ts'. Import trace for requested module: ./models/user.ts ./auth.ts ./middleware.ts

Build failed because of webpack errors

Any solutions on this? If I just use Prisma to replace mongoose, is it an option?

Same issue here "next": "14.2.5", "next-auth": "^5.0.0-beta.19", "mongoose": "^8.5.0", Creating an optimized production build ... Failed to compile. ./node_modules\mongoose\dist\browser.umd.js Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation Import trace for requested module: ./node_modules\mongoose\dist\browser.umd.js ./src\utils\modelUser.ts ./src\auth.ts ./src\middleware.ts

Build failed because of webpack errors

"Because the Edge runtime only uses standard Web APIs, many packages are not compatible with it, such as the mongodb driver package." 2 articles I saw about Authjs, Magic Links Email Provider with MongoDB as backend also mentioned and provided a workaround. I wish I could see a video with this workaround being practically utilized and built.

Using prisma to replace the mongoose part in your auth.ts, this issue will be fixed. Go to read the documentation on the official website of Prisma, there are some examples for mongodb.

Thank you. Also saw same advice here: https://medium.com/@chxiuy/mongodb-in-nextjs-overcoming-the-edge-runtime-middleware-hurdle-4beee31eaa30

Anyways following Article and comparing from a previous app i build all i did was remove the middleware file (middleware.ts) and npm run build was then successful. Remember Authjs documentation states that middleware is optional https://authjs.dev/getting-started/installation

JawadAzizi commented 1 month ago

Link to the code that reproduces this issue

https://github.com/azr-arch/realtime-chat-app

To Reproduce

try building the app with npm run build

Current vs. Expected behavior

Current Behavior: When I attempt to build my Next.js application for deployment, the build process fails. The error message indicates that dynamic code evaluation (e.g., 'eval', 'new Function', 'WebAssembly.compile') is not allowed in Edge Runtime. The error seems to originate from the @babel/runtime/regenerator and next-auth/react modules.

Here's the error message I received:

Failed to compile.

./node_modules/@babel/runtime/regenerator/index.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime 
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

Import trace for requested module:
./node_modules/@babel/runtime/regenerator/index.js
./node_modules/next-auth/react/index.js

> Build failed because of webpack errors

Expected Behavior: I expected the build process to complete without errors, allowing me to deploy my Next.js application.

Steps to Reproduce:

1. Run the build command for the Next.js application.

2. Observe the error message related to dynamic code evaluation in Edge Runtime.

Verify canary release

* [x]  I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 11 Home Single Language
Binaries:
  Node: 21.1.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.0.1
  eslint-config-next: 14.0.2
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.2.2
Next.js Config:
  output: N/A

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

Not sure

Additional context

also, any help regarding this

(node:7360) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)

would be appreciated.

Note: this warning only shows during npm run dev

My solution to a problem the same like this as stated in the response in here was as bellow:

I add the following code in middleware.ts file

export const config = {
  unstable_allowDynamic: [
    '/node_modules/sweetalert2/dist/sweetalert2.all.js',
  ],
};

so in your case the solution would be some thing like this:

export const config = {
  unstable_allowDynamic: [
    '/node_modules/@babel/runtime/regenerator/index.js',
   '/node_modules/next-auth/react/index.js',
  ],
//...rest of the config
};
abhishekkovuritw commented 1 month ago

This is the issue I am facing unfortunately no stack trace

Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime 
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

The error was caused by importing 'next/dist/esm/server/web/adapter.js' in 'undefined'.

Import trace for requested module:

> Build failed because of webpack errors

Can someone please help here? I have also tried unstable_allowDynamic and included next/dist/esm/server/web/adapter.js but I couldn't resolve.

abhishekkovuritw commented 1 month ago

This is the issue I am facing unfortunately no stack trace

Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime 
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation

The error was caused by importing 'next/dist/esm/server/web/adapter.js' in 'undefined'.

Import trace for requested module:

> Build failed because of webpack errors

Can someone please help here? I have also tried unstable_allowDynamic and included next/dist/esm/server/web/adapter.js but I couldn't resolve.

Fixed my issue, it was related to babel config