Skip to content

Error: Dynamic Code Evaluation Not Allowed in Edge Runtime When Using Mongoose #3

@sirajahmedx

Description

@sirajahmedx

Issue: Dynamic Code Evaluation Error in Edge Runtime

Description:

When trying to use mongoose in a Next.js project with the Edge runtime, I encountered an error indicating that dynamic code evaluation (such as eval, new Function, WebAssembly.compile) is not allowed in the Edge runtime. Specifically, the error occurs when importing mongoose/dist/browser.umd.js in the file ./lib/mongodb.ts.

Error Message:

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 './lib/mongodb.ts'.

Import trace for requested module:
./lib/mongodb.ts
./auth.ts
./middleware.ts

Steps to Reproduce:

  1. Create a Next.js project with the Edge runtime enabled.
  2. Install and import mongoose in a server-side file (e.g., ./lib/mongodb.ts).
  3. Attempt to build the project, either locally or in production.

Expected Behavior:

The project should build successfully without errors related to dynamic code evaluation when using mongoose in an Edge runtime.

Actual Behavior:

The build fails with an error related to dynamic code evaluation, as mongoose uses the browser.umd.js version, which is not compatible with the Edge runtime.

Possible Solution:

It seems that mongoose includes client-side code (like browser.umd.js) that is incompatible with the restrictions of the Edge runtime. A possible solution could be:

  • Use the native MongoDB driver (mongodb) instead of mongoose for Edge functions.
  • Ensure that mongoose is only used in environments that support dynamic code evaluation, such as the Node.js runtime.

Additional Information:

  • Next.js version: [Insert version]
  • Mongoose version: [Insert version]
  • Edge runtime enabled via next.config.js

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions