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

Next.js集成EdgeDB时出现Module not found: Can't resolve 'fs'构建错误

Next.js 14.2.3 + EdgeDB 构建报错:Module not found: Can't resolve 'fs'

问题详情

构建时触发如下错误:

Build Error
Failed to compile Next.js (14.2.3)
./node_modules/edgedb/dist/adapter.node.js:31:1
Module not found: Can't resolve 'fs'

导入追踪:

./node_modules/edgedb/dist/primitives/buffer.js
./dbschema/edgeql-js/json.ts
./dbschema/edgeql-js/query.ts
./dbschema/edgeql-js/params.ts
./dbschema/edgeql-js/external.ts

已尝试的排查动作:

  • 复查Next.js和EdgeDB官方文档,确认遵循推荐实践与配置
  • 尝试调整Webpack配置处理fs模块,但未解决问题
  • 验证EdgeDB等依赖与Next.js版本兼容性

解决方案

1. 严格限制EdgeDB在服务器端代码中使用

EdgeDB的Node.js适配器依赖Node.js内置的fs模块,绝对不能在客户端组件(Client Components)中导入或调用。

将所有EdgeDB相关逻辑移至以下服务器端场景:

  • 服务器组件(Server Components,Next.js默认组件类型)
  • API路由(app/api/目录下的路由文件)
  • Server Actions
  • 专属后端逻辑文件(如lib/edgedb.ts,仅在服务器端导入)

示例代码:

// lib/edgedb.ts - 仅用于服务器端的初始化文件
import { createClient } from 'edgedb';

export const client = createClient();

在服务器组件中调用:

// app/page.tsx - 默认服务器组件
import { client } from '@/lib/edgedb';

export default async function Home() {
  const userList = await client.query(`SELECT User { name, email } LIMIT 5`);
  return (
    <ul>
      {userList.map(user => <li key={user.email}>{user.name}</li>)}
    </ul>
  );
}

2. 配置Next.js Webpack处理Node.js内置模块(兜底方案)

如果因特殊场景需要保留导入(不推荐客户端使用),可在next.config.js中添加Webpack配置,告知Webpack将fs等内置模块标记为空模块:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config, { isServer }) => {
    // 仅在客户端构建时处理Node.js内置模块
    if (!isServer) {
      config.resolve.fallback = {
        ...config.resolve.fallback,
        fs: false,
        net: false,
        tls: false
      };
    }
    return config;
  },
};

module.exports = nextConfig;

3. 使用EdgeDB无依赖API(客户端场景备选)

如果需要在客户端与EdgeDB交互,可跳过Node.js客户端,直接使用EdgeDB提供的REST或GraphQL API:

  • 通过EdgeDB CLI启用REST API:edgedb project configure --add-api rest
  • 客户端通过HTTP请求直接调用API,无需依赖edgedb npm包

示例:

// 客户端组件中调用EdgeDB REST API
async function fetchUserList() {
  const res = await fetch('/db/edgedb/rest/v1/query', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: 'SELECT User { name, email } LIMIT 5' })
  });
  return res.json();
}

核心说明

EdgeDB的Node.js客户端是为服务器端环境设计的,浏览器环境不支持其依赖的Node.js内置模块。优先采用“服务器端处理数据库逻辑,客户端仅获取渲染数据”的架构,这也是Next.js的推荐最佳实践。

内容的提问来源于stack exchange,提问作者Debuger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:05:07