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

Next.js项目npm run dev正常但npm run build失败求助

针对Next.js 14.1.0构建时next-auth核心模块解析失败的解决方案

1. 锁定next-auth兼容版本

Next.js 14.1.0的webpack配置有调整,部分新的next-auth版本会在客户端代码里意外引入Node核心模块。直接指定适配性稳定的版本:

  • 执行 npm install next-auth@4.24.7
  • 删掉node_modules和package-lock.json,重新安装依赖:rm -rf node_modules package-lock.json && npm install

2. 给webpack加polyfill配置(临时兼容方案)

如果换版本没用,就在next.config.js里加webpack配置,手动补全这些核心模块的浏览器兼容版本:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config, { isServer }) => {
    if (!isServer) {
      config.resolve.fallback = {
        ...config.resolve.fallback,
        stream: require.resolve('stream-browserify'),
        http: require.resolve('stream-http'),
        https: require.resolve('https-browserify'),
        querystring: require.resolve('querystring-es3'),
        crypto: require.resolve('crypto-browserify'),
      };
    }
    return config;
  },
};

module.exports = nextConfig;

然后装对应的依赖包:npm install stream-browserify stream-http https-browserify querystring-es3 crypto-browserify

3. 检查next-auth的使用场景

别在客户端组件里用next-auth的服务端专属功能,比如getServerSession、NextAuth配置这些代码,必须放在服务端组件、API路由或者Server Actions里。要是之前在客户端组件里调用了这些,赶紧移去服务端环境。

4. 同步Cloudflare Pages的构建配置

Cloudflare Pages的默认环境可能限制Node特性,要做这两步:

  • 在package.json里加engines字段指定Node版本:
"engines": {
  "node": ">=21.6.2"
}
  • 在Cloudflare Pages的构建设置里,把Node版本改成21.6.2,和本地保持一致;如果有“Node.js兼容性模式”选项,勾选上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:17:21