Next.js认证中间件报错:TypeError无法读取substring属性求助
TypeError: Cannot read properties of undefined (reading 'substring') in next-auth Credentials Provider with middleware
这个错误是因为openid-client依赖的oidc-token-hash库在Edge Runtime(Next.js中间件运行环境)中无法正常初始化导致的。根源是你的配置里冗余的空providers数组,加上未明确指定Session策略,让NextAuth错误加载了OpenID相关依赖模块,最终触发了未定义属性调用。
解决步骤
移除authConfig中的空providers数组
你的authconfig.js里保留的空providers数组会让NextAuth尝试加载默认OpenID逻辑,直接删除该字段:export const authConfig = { pages: { signIn: "/login", }, callbacks: { authorized({ auth, request }) { const isLoggedIn = auth?.user; const isOnDashboard = request.nextUrl.pathname.startsWith("/dashboard"); if (isOnDashboard) { return !!isLoggedIn; } else if (isLoggedIn) { return Response.redirect(new URL("/dashboard", request.nextUrl)); } return true; }, }, };明确指定Session策略为jwt
Credentials Provider默认不支持Database Session(除非配置Adapter),设置session.strategy: "jwt"可避免加载不必要依赖,同时保证会话处理正常:export const { signIn, signOut, auth } = NextAuth({ ...authConfig, session: { strategy: "jwt", }, providers: [ CredentialsProvider({ async authorize(credentials) { try { const user = await login(credentials); // 将Mongoose文档转为普通对象,避免序列化问题 return { id: user._id.toString(), username: user.username, isAdmin: user.isAdmin }; } catch (err) { return null; } }, }), ], });修复login函数返回值
直接返回Mongoose的User文档可能存在序列化问题,转为普通JavaScript对象(如上代码所示),确保JWT能正确存储用户信息。清理缓存并重新构建
执行以下命令清理旧构建缓存和依赖,避免残留问题:rm -rf .next node_modules package-lock.json npm install npm run build
内容的提问来源于stack exchange,提问作者Yoon
相关产品推荐
相关产品推荐

