Next.js Discord

Discord Forum

Return custom user object in authorize() of next auth

Unanswered
Blue-headed Vireo posted this in #help-forum
Open in Discord
Blue-headed VireoOP
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 { auth } from '@/src/lib/firebase';

export interface Session {
user: {
id: string;
};
}
export const authOptions: AuthOptions = {
providers: [
CredentialsProvider({
id: 'email',
name: 'email',
credentials: {
...
},
async authorize(credentials, req) {
try {
const user = await signInWithEmailAndPassword(
auth,
credentials?.email!,
credentials?.password!
);
if (user) {
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;
// },
},
};
'''
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?

2 Replies

Try using JWT callback to add the stuff you need inside the token like this:

https://next-auth.js.org/configuration/callbacks#jwt-callback
Also you should read this part too