You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Edge Runtime中Mongoose动态代码评估不允许的问题?

解决Next.js Edge Runtime中动态代码评估禁用问题

问题场景与报错

在Next.js的Middleware或Edge API Routes中使用Mongoose时,触发Edge Runtime的安全限制,报错如下:

./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
./models\users\userModel.js
./auth.config.js
./middleware.js.

解决方案

1. 隔离数据库操作到非Edge环境

Edge Runtime的安全规则禁止动态代码执行,而Mongoose浏览器版本依赖这类特性。直接调整架构:

  • 把数据库查询、模型操作等逻辑转移到普通Node.js API Routes,Middleware只负责身份校验、路径转发等轻量任务,通过调用普通API完成数据交互。

2. 替换为Edge兼容的数据库客户端

若必须在Edge环境操作数据库,弃用Mongoose,改用原生MongoDB驱动的Edge兼容版本,或使用Vercel官方的@vercel/kv、@vercel/postgres等适配Edge Runtime的工具。

  • 原生MongoDB驱动:安装最新版mongodb包,它已移除动态代码评估依赖,完全适配Edge环境。

3. 配置Next.js隔离Mongoose依赖

修改next.config.js,通过实验性配置将Mongoose排除在Edge环境的依赖之外:

// next.config.js
module.exports = {
  experimental: {
    serverComponentsExternalPackages: ['mongoose'],
  },
}

同时确保Middleware或Edge API Routes中没有直接导入Mongoose模型,将模型相关逻辑封装到非Edge模块中。

4. 使用Mongoose的Edge专属版本

检查Mongoose版本,若为支持Edge的版本,修改导入路径为Edge专属入口,该版本移除了动态代码评估逻辑:

// CommonJS
const mongoose = require('mongoose/edge');
// ES模块
import mongoose from 'mongoose/edge';

内容的提问来源于stack exchange,提问作者M.A.Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:04:58