使用NextAuth为Next.js应用添加认证时遇TypeScript类型错误
问题原因
你遇到的类型错误是因为authorize方法返回的对象不符合NextAuth要求的User类型结构。默认的User类型需要包含id字段(或其他核心属性),而你当前只返回了email,导致类型校验不通过。
解决方案
1. 补充返回对象的必需字段
MongoDB用户文档默认用_id作为主键,需要将其转为字符串后加入返回结果,匹配User类型的要求:
修改authorize方法的返回语句:
return { id: user._id.toString(), // 将MongoDB的ObjectId转为字符串格式 email: user.email };
2. (TypeScript项目可选)显式扩展NextAuth类型
如果是TypeScript项目,可以在项目中创建types/next-auth.d.ts文件,自定义符合业务需求的User类型:
import NextAuth from "next-auth"; declare module "next-auth" { interface User { id: string; email: string; } }
修改后的完整代码
export default NextAuth({ providers: [ CredentialsProvider({ async authorize(credentials) { let client; try { client = await MongoClient.connect('my mongo db credentials goes here'); const usersCollection = client.db().collection("users"); const user = await usersCollection.findOne({ email: credentials.email, }); if (!user) { throw new Error("Invalid username or password provided"); } const validPassword = await verifyPassword( credentials.password, user.password ); if (!validPassword) { throw new Error("Invalid username or password provided"); } return { id: user._id.toString(), email: user.email }; } finally { if (client) client.close(); // 确保连接始终关闭 } }, }), ], });
内容的提问来源于stack exchange,提问作者abelteha
相关产品推荐
相关产品推荐

