如何在前端获取NextAuth Github Provider自定义的Profile数据?
解决NextAuth自定义Profile字段前端获取问题
你已经重写了Github Provider的profile方法返回了userName,但前端用useSession()拿不到,核心原因是NextAuth不会自动把自定义字段同步到session中,需要通过jwt和session回调完成字段传递:
1. 补充NextAuth配置的回调逻辑
修改你的NextAuth配置,添加callbacks选项,把自定义的userName从token同步到session:
export default NextAuth({ providers: [ GithubProvider({ clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, async profile(profile: GithubProfile) { console.log('profile', profile) return { id: profile.id.toString(), name: profile.name, userName: profile.login, // 自定义的Github用户名字段 email: profile.email, image: profile.avatar_url, } }, }), ], callbacks: { // 把自定义字段写入JWT token async jwt({ token, user }) { // 用户首次登录时,user包含profile返回的所有字段 if (user) { token.userName = user.userName; } return token; }, // 从token中读取自定义字段,同步到session对象 async session({ session, token }) { if (session.user) { session.user.userName = token.userName as string; } return session; }, }, session: { strategy: "jwt", // 确保使用JWT策略(默认值,显式声明更清晰) }, })
2. 前端通过useSession获取自定义字段
现在在前端组件里,直接从session.user中就能拿到userName:
import { useSession } from "next-auth/react"; function UserProfile() { const { data: session } = useSession(); if (!session) return <p>未登录</p>; return ( <div> <p>Github用户名:{session.user.userName}</p> <p>昵称:{session.user.name}</p> <img src={session.user.image} alt="用户头像" width={80} /> </div> ); } export default UserProfile;
额外说明(TypeScript可选)
如果用TypeScript,建议扩展NextAuth的类型,获得更友好的代码提示:
// 可以放在next-auth.d.ts文件中 import NextAuth from "next-auth"; declare module "next-auth" { interface User { userName: string; } interface Session { user: User & DefaultSession["user"]; } } declare module "next-auth/jwt" { interface JWT { userName: string; } }
内容的提问来源于stack exchange,提问作者user3380738
相关产品推荐
相关产品推荐

