I am currently working on enhancing the API response by adding the unique identifier (id
) property during the login process. I followed the recommendation to use callbacks from a discussion on Stack Overflow (Get User ID from session in next-auth client), but encountered an error that seems to be related to TypeScript according to this GitHub thread (https://github.com/nextauthjs/next-auth/issues/7132). How can I address this issue? I want to get the id
in my response and manipulate it later. Here is the current API response structure:
https://i.stack.imgur.com/uXICV.png
Error Found:
https://i.stack.imgur.com/iJxnB.png
The error seems to originate within the callback function:
callbacks: {
session: async ({ session, token }) => {
if (session?.user) {
session.user.id = token.sub;
}
return session;
},
jwt: async ({ user, token }) => {
if (user) {
token.sub = user.id;
}
return token;
},
},
Next Auth Configuration File:
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma as any),
providers:[
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
CredentialProvider({
name: "credentials",
credentials: {
name: {label: "Name", type: "text", placeholder: "John Due"},
email: {label: "Email", type: "text", placeholder: "jsmith"},
password: {label: "Password", type: "password", placeholder: "password"},
},
async authorize(credentials, req): Promise<any>{
console.log("Authorize method", credentials)
if(!credentials?.email || !credentials?.password) throw new Error("Login data required")
const user = await prisma.user.findUnique({
where:{
email: credentials?.email
}
})
if(!user || !user.hashedPassword) {
throw new Error("User not registered")
}
const matchPassword = await bcrypt.compare(credentials.password, user.hashedPassword);
if(!matchPassword)
throw new Error("Incorrect password")
return user
}
})
],
session: {
strategy: "jwt",
maxAge: 60 * 60,
},
jwt: { encode, decode },
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
session: async ({ session, token }) => {
if (session?.user) {
session.user.id = token.sub;
}
return session;
},
jwt: async ({ user, token }) => {
if (user) {
token.sub = user.id;
}
return token;
},
},
debug: process.env.NODE_ENV === "development",
pages: {
signIn: "/dashboard"
}
}
- I went through the documentation of Next Auth, but couldn't find relevant details for this specific task.