Skip to content
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

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

Open
1 task done
azr-arch opened this issue Nov 20, 2023 · 34 comments
Labels
bug Issue was opened via the bug report template.

Comments

@azr-arch
Copy link

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

  • 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

@azr-arch azr-arch added the bug Issue was opened via the bug report template. label Nov 20, 2023
@IonelLupu
Copy link

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
Copy link

joniel commented Dec 12, 2023

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
Copy link
Author

@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
Copy link

@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
Copy link

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
Copy link

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
Copy link

yes, i use neon with drizzle

@ronijaat
Copy link

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
Copy link

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
Copy link

athikaf commented May 8, 2024

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
Copy link

mkimbo commented May 12, 2024

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
Copy link

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
Copy link

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
Copy link

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
Copy link

bxljoy commented May 29, 2024

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
Copy link

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
Copy link

bxljoy commented May 29, 2024

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
Copy link

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
Copy link

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
Copy link

traez commented Jul 16, 2024

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
Copy link

bxljoy commented Jul 16, 2024

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
Copy link

traez commented Jul 16, 2024

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
Copy link

JawadAzizi commented Aug 12, 2024

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
Copy link

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
Copy link

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

@w3nl
Copy link

w3nl commented Sep 27, 2024

Why does NextJS ever use eval in the generated Javascript.
I have the issue that we want to generate a static SPA, and it only works to add unsafe-eval and unsafe-inline.

@abhishekkapoorx
Copy link

import NextAuth, { CredentialsSignin } from "next-auth"
import Credentials from "next-auth/providers/credentials"
import Google from "next-auth/providers/google"
import bcrypt from 'bcryptjs'
import { connect } from "./utils/lib/db/connectDb"
import User from "./utils/models/users"


export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Credentials({
      // You can specify which fields should be submitted, by adding keys to the `credentials` object.
      // e.g. domain, username, password, 2FA token, etc.
      credentials: {
        email: {
          label: "Email",
          type: "email",
          name: "email",
          placeholder: "Enter your email",
          required: true,
          // pattern: "/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/"
        },
        password: {
          label: "Password",
          type: "password",
          name: "password",
          placeholder: "Enter your password",
          required: true,
          minLength: 8,
        },
      },
      authorize: async (credentials) => {
        const email = credentials.email as string|null;
        const password = credentials.password as string|null;

        if (!email || !password){
          throw new CredentialsSignin("Please provide both email and password")
        }

        const connection = await connect();
        const user = await User.findOne({email}).select("+password +role")
        if (!user || !user.password) {
          throw new Error("Invalid email or password")
        }

        const isMatched = await bcrypt.compare(password, user.password)

        if (!isMatched) {
          throw new Error("Invalid password")
        }

        const userData = {
          name: user.name,
          email: user.email,
          role: user.role,
          isVerified: user.isVerified,
          id: user._id
        }
        console.log(userData);
        return userData;

      },
    }),

    Google({
      clientId: process.env.AUTH_GOOGLE_ID,
      clientSecret: process.env.AUTH_GOOGLE_SECRET,
      // Optional: redirect to this URL after sign in/up
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code",
        },
      },
    }),
  ],

  pages: {
    signIn: "/auth/sign-in"
  }, 

  callbacks: {
    async session({session, token}) {
      // Add user to session
      if (token?.role && token?.sub){
        session.user.id = token.sub
        session.user.role = token.role
      }
      return session;
    },

    async jwt({token, user}){
      if (user){
        token.role = user.role
      }
      return token;
    },

    signIn: async ({user, account}) => {
      if (account?.provider === "google"){
        try {
          const {email, name, image, id} = user || {};
          const connection = await connect();
          const alreadyUser = await User.findOne({email})

          if (!alreadyUser){
            await User.create({email, name, image, authProviderId: id })
          } else {
            return true;
          }
        } catch (error) {
          throw new Error("Error while creating user");
        }
      }

      if (account?.provider === "credentials"){
        return true;
      } else {
        return false;
      }
    }
  }
})

I have auth.js file something like this. And getting the error

./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
  ./utils\lib\db\connectDb.ts
  ./auth.ts
  ./middleware.ts


> Build failed because of webpack errors
PS E:\illumeWork\illumework-web-2> npm run build

> next-app-template@0.0.1 build
> next build

  ▲ Next.js 14.2.6
  - Environments: .env.local

   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
  ./utils\lib\db\connectDb.ts
  ./auth.ts
  ./middleware.ts


> Build failed because of webpack errors

Please help to resolve this error

@ronijaat
Copy link

ronijaat commented Oct 4, 2024

import NextAuth, { CredentialsSignin } from "next-auth"
import Credentials from "next-auth/providers/credentials"
import Google from "next-auth/providers/google"
import bcrypt from 'bcryptjs'
import { connect } from "./utils/lib/db/connectDb"
import User from "./utils/models/users"


export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Credentials({
      // You can specify which fields should be submitted, by adding keys to the `credentials` object.
      // e.g. domain, username, password, 2FA token, etc.
      credentials: {
        email: {
          label: "Email",
          type: "email",
          name: "email",
          placeholder: "Enter your email",
          required: true,
          // pattern: "/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/"
        },
        password: {
          label: "Password",
          type: "password",
          name: "password",
          placeholder: "Enter your password",
          required: true,
          minLength: 8,
        },
      },
      authorize: async (credentials) => {
        const email = credentials.email as string|null;
        const password = credentials.password as string|null;

        if (!email || !password){
          throw new CredentialsSignin("Please provide both email and password")
        }

        const connection = await connect();
        const user = await User.findOne({email}).select("+password +role")
        if (!user || !user.password) {
          throw new Error("Invalid email or password")
        }

        const isMatched = await bcrypt.compare(password, user.password)

        if (!isMatched) {
          throw new Error("Invalid password")
        }

        const userData = {
          name: user.name,
          email: user.email,
          role: user.role,
          isVerified: user.isVerified,
          id: user._id
        }
        console.log(userData);
        return userData;

      },
    }),

    Google({
      clientId: process.env.AUTH_GOOGLE_ID,
      clientSecret: process.env.AUTH_GOOGLE_SECRET,
      // Optional: redirect to this URL after sign in/up
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code",
        },
      },
    }),
  ],

  pages: {
    signIn: "/auth/sign-in"
  }, 

  callbacks: {
    async session({session, token}) {
      // Add user to session
      if (token?.role && token?.sub){
        session.user.id = token.sub
        session.user.role = token.role
      }
      return session;
    },

    async jwt({token, user}){
      if (user){
        token.role = user.role
      }
      return token;
    },

    signIn: async ({user, account}) => {
      if (account?.provider === "google"){
        try {
          const {email, name, image, id} = user || {};
          const connection = await connect();
          const alreadyUser = await User.findOne({email})

          if (!alreadyUser){
            await User.create({email, name, image, authProviderId: id })
          } else {
            return true;
          }
        } catch (error) {
          throw new Error("Error while creating user");
        }
      }

      if (account?.provider === "credentials"){
        return true;
      } else {
        return false;
      }
    }
  }
})

I have auth.js file something like this. And getting the error

./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
  ./utils\lib\db\connectDb.ts
  ./auth.ts
  ./middleware.ts


> Build failed because of webpack errors
PS E:\illumeWork\illumework-web-2> npm run build

> next-app-template@0.0.1 build
> next build

  ▲ Next.js 14.2.6
  - Environments: .env.local

   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
  ./utils\lib\db\connectDb.ts
  ./auth.ts
  ./middleware.ts


> Build failed because of webpack errors

Please help to resolve this error

Mongoose not support edge runtime so use prisma orm in auth.js file

@rodrigotv
Copy link

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

Thanks @traez , removing the middleware file worked like charm.

@ronijaat
Copy link

ronijaat commented Nov 5, 2024

finally, i came up with a solution, using mongoose (not any ORM like Prisma)and it didn't gives any error on build time and working perfectly in production.

@rickn0024
Copy link

finally, i came up with a solution, using mongoose (not any ORM like Prisma)and it didn't gives any error on build time and working perfectly in production.

What ended up working?

@Code-Journey-77
Copy link

I resolved this issue in my Next.js project using the following configuration. I am using the latest version of Next.js:

this is my config:

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  env:{
    DATABASE_URL:process.env.DATABASE_URL,
    AUTH_SECRET:process.env.AUTH_SECRET,
    GOOGLE_CLIENT_ID:process.env.GOOGLE_CLIENT_ID,
    GOOGLE_CLIENT_SECRET:process.env.GOOGLE_CLIENT_SECRET,
    GITHUB_CLIENT_ID:process.env.GITHUB_CLIENT_ID,
    GITHUB_CLIENT_SECRET:process.env.GITHUB_CLIENT_SECRET
  },
  serverExternalPackages: ["mongoose"],
  webpack: (config, { isServer }) => {
    if (isServer) {
      config.externals = [
        ...config.externals,
        "mongoose",
      ];
    }
    config.experiments = {
      topLevelAwait: true,
      layers: true,
    };
    return config;
  },
};

export default nextConfig;

I successfully resolved the issue in my case. I hope this is helpful for you!

@Edgarcillo2k
Copy link

I solved the issue by removing an import. Let's say that I have @/app/lib/db-connection.ts, if in @/app/lib I have an index.ts exporting the contents of db-connection.ts and I use some code of other file in the middleware by using import { myfunction } from @/app/lib, it will import that db-connection.ts file which has the connection with mongoose and will throw the error. So the solution in this case would be to remove the export * from "./db-connection" in @/app/lib/index.ts, then import { dbConn } from "@/app/lib/db-connection" where dbConn function is required. This problem happened when using auth.js v5 and middleware, same as some other people, so for them resolving this import "hell" should fix the problem. Additionally, server actions can't be call from middleware, or at least node runtime server actions, so if you need to perform some database check or something else you should put that code in a route handler and fetch it from middleware or some other non node runtime code, as auth code for auth.js v5.

@ronijaat
Copy link

Easy solution: instead of server actions use api in auth.js or in middleware.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Issue was opened via the bug report template.
Projects
None yet
Development

No branches or pull requests