Reputation: 81
I'm trying to use next auth on nextjs to manage authentication using Google and using email and password (using signInWithEmailAndPassword from firebase), but I'm having problems in returning the user object that I need. In fact, it looks like the user object, inside the session object, consists of name, email and image, that for logging in using Google that's fine, however when I handle logging in with email I would like to return the ID as well... This is what I am trying to do in the file "src/app/api/auth/[...nextauth]/route.ts":
import NextAuth, { AuthOptions } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import CredentialsProvider from 'next-auth/providers/credentials';
import { signInWithEmailAndPassword } from 'firebase/auth';
import { auth } from '@/src/lib/firebase';
export interface Session {
user: {
id: string;
};
}
export const authOptions: AuthOptions = {
providers: [
GoogleProvider({
name: 'google',
clientId: process.env.GOOGLE_ID!,
clientSecret: process.env.GOOGLE_SECRET!,
}),
CredentialsProvider({
id: 'email',
name: 'email',
credentials: {
email: {
label: 'Email',
type: 'text',
placeholder: '[email protected]',
},
password: { label: 'Password', type: 'password' },
},
async authorize(credentials, req) {
try {
const user = await signInWithEmailAndPassword(
auth,
credentials?.email!,
credentials?.password!
);
if (user.user.uid) {
return {
name: 'myName',
id: 'myID',
email: 'myEmail',
address: '2w',
};
}
} catch (err) {
console.log(err);
}
return null as any;
},
}),
],
callbacks: {
session({ session, token, user }) {
console.log('server', session);
return { session, token, user };
},
// jwt({ token, user, account, profile, isNewUser }) {
// console.log('jwt', token, user);
// return token;
// },
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
At first I didn't use the callback attribute, thinking it would change "user" automatically, but using it I realized that the user in the session() parameters is not my user with the id.
Finally, I also tried redefining the Session interface, but again, nothing changed.
What can I try?
Upvotes: 0
Views: 1472
Reputation: 49661
try to set the session.user.id
in session callback
callbacks: {
session({ session, token, user }) {
if(session && user){
session.user.id=user.id
}
},
return session
},
Upvotes: 1