NX Next.js 13启用experimental-edge runtime时出现TypeError报错
问题场景
基于NX的Next.js13项目,部署在Cloudflare Pages。在next.config.js中配置启用experimental-edge runtime后,启动Next.js服务器时抛出错误:
TypeError: Cannot read properties of null (reading 'registered')
项目由Next.js12升级至13,且已更新所有NX相关依赖,但问题未解决。
配置代码如下:
//@ts-check // eslint-disable-next-line @typescript-eslint/no-var-requires const { withNx } = require('@nrwl/next/plugins/with-nx'); /** * @type {import('@nrwl/next/plugins/with-nx').WithNxOptions} **/ const nextConfig = { experimental: { runtime: 'experimental-edge', appDir: false }, nx: { // Set this to true if you would like to to use SVGR // See: https://github.com/gregberge/svgr svgr: true, }, presets: ['next/babel'], env: { customKey: 'here-env', }, images: { domains: [ 'cdn.pixabay.com', 'localhost', 'pixabay.com', 'jsdevs-attachments.sgp1.digitaloceanspaces.com', 'lh3.googleusercontent.com', 'lh5.googleusercontent.com', 'lh4.googleusercontent.com', ], remotePatterns: [ { protocol: 'https', hostname: 'jsdevs-attachments.sgp1.digitaloceanspaces.com', port: '', pathname: '', }, { protocol: 'https', hostname: 'lh3.googleusercontent.com', port: '', pathname: '', }, { protocol: 'https', hostname: 'https://1zrfq19u.directus.app', port: '', pathname: '', }, ], }, swcMinify: false, }; module.exports = withNx(nextConfig);
解决方案
对齐NX与Next.js版本
确保@nrwl/next版本与Next.js版本完全匹配,比如Next.js13.4.x对应@nrwl/next13.x版本。版本不匹配会导致Edge Runtime相关的钩子函数初始化失败,引发null引用错误。修正图片配置
Next.js13中domains与remotePatterns存在兼容性冲突,且Edge Runtime对图片配置解析更严格:- 移除
domains配置,改用remotePatterns(Next.js13推荐方式) - 修正第三个
remotePattern的hostname,去掉前缀https://,改为1zrfq19u.directus.app - 为每个
remotePattern添加pathname: '/**',确保匹配所有子路径
修改后的images配置:
images: { remotePatterns: [ { protocol: 'https', hostname: 'jsdevs-attachments.sgp1.digitaloceanspaces.com', pathname: '/**', }, { protocol: 'https', hostname: 'lh3.googleusercontent.com', pathname: '/**', }, { protocol: 'https', hostname: '1zrfq19u.directus.app', pathname: '/**', }, { protocol: 'https', hostname: 'cdn.pixabay.com', pathname: '/**', }, { protocol: 'https', hostname: 'pixabay.com', pathname: '/**', }, { protocol: 'http', hostname: 'localhost', pathname: '/**', }, { protocol: 'https', hostname: 'lh5.googleusercontent.com', pathname: '/**', }, { protocol: 'https', hostname: 'lh4.googleusercontent.com', pathname: '/**', }, ], },- 移除
临时禁用SVGR自动转换
配置中启用的nx.svgr: true可能在Edge Runtime环境下未正确初始化,导致null引用。先将其设为false验证:nx: { svgr: false, },若问题解决,可改用手动导入SVG(如
import Icon from './icon.svg?component'),或等待NX更新对Edge Runtime下SVGR的支持。清理缓存并重建
升级依赖后的缓存残留可能引发冲突,执行以下命令:npx nx reset rm -rf node_modules .next npm install npm run build检查Cloudflare Pages配置
确保Cloudflare Pages的构建配置中,Next.js运行时设置为Edge,且未启用与Edge Runtime冲突的自定义中间件或旧版Serverless函数。
内容的提问来源于stack exchange,提问作者ali hussain

