Next.js 13.4.1中top-level-await报错及配置问题求助
解决Next.js 13.4.1 App Router中bson模块的顶层await报错问题
问题原因
bson模块内部使用了顶层await语法,但Next.js默认未启用该特性,且你之前错误地将topLevelAwait配置放在了next.config.js的根层级,而非指定的experimental对象中。
解决步骤
1. 正确配置next.config.js
将topLevelAwait选项放在experimental对象内,修改后的配置文件如下:
/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { topLevelAwait: true } } module.exports = nextConfig;
2. 修正API接口中的异步调用
dbConnect是异步函数,调用时需要添加await确保数据库连接完成后再返回响应:
import dbConnect from "../../../../lib/connect"; export async function GET(req, res) { await dbConnect(); return new Response('Hello, Next.js! I can make twitter clone', { status: 200, }); }
3. 可选:添加transpilePackages(若仍报错)
如果上述配置后仍有模块解析问题,可将bson加入transpilePackages列表,强制Next.js转译该模块:
/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { topLevelAwait: true }, transpilePackages: ['bson'] } module.exports = nextConfig;
验证方法
重启Next.js开发服务器,重新调用/api/user接口,即可正常返回响应。
内容的提问来源于stack exchange,提问作者user20492045
相关产品推荐
相关产品推荐

